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
    `
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法