如何解组毒蛇配置以使用破折号字符进行结构化

How to unmarshall viper config to struct with dash character

我将以下配置文件定义为 toml 文件:

[staging]
project-id = "projectId"
cluster-name = "cluster"
zone = "asia-southeast1-a"

然后,我有这个结构

type ConfigureOpts struct {
    GCPProjectID       string `json:"project-id"`
    ClusterName        string `json:"cluster-name"`
    Zone               string `json:"zone"`
}

请注意,我的 ConfigureOpts 字段名格式与配置文件中定义的格式不同。

我试过这段代码,但失败了

test_opts := ConfigureOpts{}
fmt.Printf("viper.staging value %+v\n", viper.GetStringMap("staging"))
viper.UnmarshalKey("staging", &test_opts)
fmt.Printf("testUnmarshall %+v\n", test_opts)

这是输出

viper.staging value map[zone:asia-southeast1-a project-id:projectId cluster-name:cluster]

testUnmarshall {GCPProjectID: ClusterName: Zone:asia-southeast1-a AuthMode: AuthServiceAccount:}

我根据这个参考得到了答案https://github.com/spf13/viper/issues/258

所以解决方案是将 ConfigureOpts 结构中的任何 json: 标记更改为 mapstructure:

所以这将解决问题。

type ConfigureOpts struct {
    GCPProjectID       string `mapstructure:"project-id"`
    ClusterName        string `mapstructure:"cluster-name"`
    Zone               string `mapstructure:"zone"`
}