go語言yaml轉map、map遍歷的實現

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遍歷內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: