dqnqpqv3841 2019-05-04 04:42
浏览 148
已采纳

为什么解码返回结果为空

I have below code, I would like to convert yaml to client go data structure and get the object name from it

package main

import (
  "fmt"

  "k8s.io/api/extensions/v1beta1"
  "k8s.io/client-go/kubernetes/scheme"
)

var yml = `
apiVersion: extensions/v1beta1
kind: Deployment
metadata: 
name: testnginx
replicas: 1
spec: 
template:
  metadata:
    labels:
      run: testnginx
  spec:
    containers:
    - image: nginx
      name: testnginx
      ports:
      - containerPort: 8080
`

func main() {
    decode := scheme.Codecs.UniversalDeserializer().Decode

    obj, _, err := decode([]byte(yml), nil, nil)
    if err != nil {
        fmt.Printf("%#v", err)
    }

  //fmt.Printf("%#v
", obj)
  deployment := obj.(*v1beta1.Deployment)

    fmt.Printf("%#v
", deployment.ObjectMeta.Name)
}

The return result supposes to be testnginx but it is empty

$ ./decode-k8s-exercise 
""

Not sure why. thanks

  • 写回答

1条回答 默认 最新

  • douguadao3883 2019-05-04 06:05
    关注

    The problem is in the yaml. The name field should be an attribute inside metadata but they are currently at the same level. If you space indent the name then it should work (the same applies to template later on). relicas should also be inside spec:

    var yml = `
    apiVersion: extensions/v1beta1
    kind: Deployment
    metadata: 
      name: testnginx
    spec:
      replicas: 1
      template:
        metadata:
          labels:
            run: testnginx
        spec:
          containers:
          - image: nginx
            name: testnginx
            ports:
            - containerPort: 8080
    `
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Python爬取指定微博话题下的内容,保存为txt
  • ¥15 vue2登录调用后端接口如何实现
  • ¥65 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥15 latex怎么处理论文引理引用参考文献
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?