欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

go语言yaml转map、map遍历的实现

程序员文章站 2022-06-16 22:26:29
yaml文件内容apiversion: policy/v1beta1kind: podsecuritypolicymetadata: name: mysql-snapshotspec: priv...

yaml文件内容

apiversion: policy/v1beta1
kind: podsecuritypolicy
metadata:
  name: mysql-snapshot
spec: 
  privileged: false
  allowprivilegeescalation: false
  volumes:
  - "*"
  hostnetwork: false
  hostipc: false
  hostpid: false
  runasuser:
    rule: runasany
  selinux:
    rule: runasany
  supplementalgroups:
    rule: runasany
  fsgroup:
    rule: runasany

示例代码:实现了base64 编解码、yaml转map、以及map遍历

func main() {
f, err := os.open("cmd/test.yaml")
 if err != nil {
  log.fatalln(err)
  return
 }

 input, _ := ioutil.readall(f)
 // base64 编码
 encodestring := base64.stdencoding.encodetostring(input)
fmt.println(encodestring)


// base64 解码
 decodebytes, err := base64.stdencoding.decodestring(encodestring)
 if err != nil {
  log.fatalln(err)
 }

//yaml文件内容转换成map[interface{}]interface{})

 resultmap := make(map[interface{}]interface{})
 if err := yaml.unmarshal(decodebytes, &resultmap); err != nil {
  // error handling
  log.fatalln(err)

 }

// 遍历map ,此处取metadata.name值
 for key, value := range resultmap {
  switch key := key.(type) {
  case string:
   if key == "metadata" {
    switch value := value.(type) {
    case string:
    case map[interface{}]interface{}:
     for k, v := range value {
      switch k.(type) {
      case string:
        if k == "name" {
         fmt.println("value=", v)
        }
      }
     }

    }

   }
  }
 }
}

结果

encodestring = "yxbpvmvyc2lvbjogcg9sawn5l3yxymv0yteka2luzdogug9ku2vjdxjpdhlqb2xpy3kkbwv0ywrhdge6ciagbmftztogbxlzcwwtc25hchnob3qkc3blyzogciagchjpdmlszwdlzdogzmfsc2ukicbhbgxvd1byaxzpbgvnzuvzy2fsyxrpb246igzhbhnlciagdm9sdw1lczokicaticiqigogighvc3rozxr3b3jroibmywxzzqogighvc3rjuem6igzhbhnlciagag9zdfbjrdogzmfsc2ukicbydw5bc1vzzxi6ciagicbydwxloibsdw5bc0fueqogihnltgludxg6ciagicbydwxloibsdw5bc0fueqogihn1chbszw1lbnrhbedyb3vwczokicagihj1bgu6ifj1bkfzqw55ciagznnhcm91cdokicagihj1bgu6ifj1bkfzqw55cg=="

value=mysql-snapshot

到此这篇关于go语言yaml转map、map遍历的实现的文章就介绍到这了,更多相关go语言yaml转map、map遍历内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!