go - 无法将 yaml 数组映射和解码到 golang 结构

标签 go

我想解码我的 ~/.kube/config文件到 go结构。

我正在使用以下方法

func ListContexts(pathToKubeConfig string) ([]string, error) {
    type Contexts struct {
        Ctx []string `yaml:"contexts"`
        //ApiVersion string              `yaml:"apiVersion"`
    }
    var ctx []string
    var c Contexts

    file, err := ioutil.ReadFile(pathToKubeConfig)
    if err != nil {
        return nil, err
    }

    err = yaml.Unmarshal(file, &c)
    fmt.Printf("%#v\n", c.Ctx)
    return ctx, nil
}
}

众所周知,kubeconfig 文件具有以下结构:
apiVersion: v1
. . . 
contexts:
- context:
    cluster: cluster1
    user: user1
  name: context1
- context:
    cluster: cluster2
    user: user2
  name: context2

我的方法是打印:
[]string(nil)

由于context是一个 yaml 数组,为什么我映射到一个字符串数组不起作用?

当我取消注释 ApiVersion我的结构的字段并尝试打印它,它可以工作。

最佳答案

context是一个数组,但不是字符串数组。使用 []map[string]interface{}对于上下文,或将上下文定义为结构,并使用其数组:

type context struct {
   Cluster string `yaml:"cluster"`
   ...
}

type contexts struct {
   Contexts []context `yaml:"contexts"`
}

关于go - 无法将 yaml 数组映射和解码到 golang 结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62135573/

相关文章:

pointers - 通过引用设置结构中的字段

windows - 在 Windows 中使用 InterfaceByName 获取网络接口(interface)名称

go - 如何在最新的 Go 周刊中比较两个函数的指针相等性?

go - Go 中的 .a 文件是什么?

google-app-engine - Google App Engine 中的实际应用程序二进制限制是多少?

go - 测试Golang导入的函数被调用?

从不完整的字符串解析 golang 时间对象

sql - 使 SQL INSERT 语句更易于阅读

google-app-engine - GAE Go 和长轮询?

go - grpc 生成的 stub 线程安全吗?