如何解组毒蛇配置以连字符

Agu*_*ama 5 go viper-go go-cobra

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

[staging]
project-id = "projectId"
cluster-name = "cluster"
zone = "asia-southeast1-a"
Run Code Online (Sandbox Code Playgroud)

然后,我有这个结构

type ConfigureOpts struct {
    GCPProjectID       string `json:"project-id"`
    ClusterName        string `json:"cluster-name"`
    Zone               string `json:"zone"`
}
Run Code Online (Sandbox Code Playgroud)

请注意,与配置文件中定义的格式不同,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)
Run Code Online (Sandbox Code Playgroud)

这是输出

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

testUnmarshall {GCPProjectID: ClusterName: Zone:asia-southeast1-a AuthMode: AuthServiceAccount:}
Run Code Online (Sandbox Code Playgroud)

Agu*_*ama 5

我根据此参考获得了答案https://github.com/spf13/viper/issues/258

因此,解决方案是将struct中的任何json:标签更改ConfigureOptsmapstructure:

因此,这将解决问题。

type ConfigureOpts struct {
    GCPProjectID       string `mapstructure:"project-id"`
    ClusterName        string `mapstructure:"cluster-name"`
    Zone               string `mapstructure:"zone"`
}
Run Code Online (Sandbox Code Playgroud)