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

管理管理2022-11-25210 阅读0 评论

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遍历内容请搜索M135模板网以前的文章或继续浏览下面的相关文章希望大家以后多多支持M135模板网!

The End 微信扫一扫

文章声明:以上内容(如有图片或视频在内)除非注明,否则均为模板汇原创文章,转载或复制请以超链接形式并注明出处。

本文作者:管理本文链接:https://baijiaci.com/news/2146.html

上一篇 下一篇

相关阅读

取消
微信二维码
微信二维码
支付宝二维码