Viper 在解组时不考虑我的结构中的 yaml 标签

mes*_*ati 1 yaml go viper-go

当我使用Unmarshalviper 的方法用 yaml 文件中的值填充我的配置结构时,一些结构字段变成了空!我这样做:

viper.SetConfigType("yaml")
viper.SetConfigName("config")
viper.AddConfigPath("/etc/myapp/")
viper.AddConfigPath(".")

err := viper.ReadInConfig()
// error checking ...
conf := &ConfYaml{}
err = viper.Unmarshal(conf)
// error checking ...
Run Code Online (Sandbox Code Playgroud)

我的结构是这样的:

type ConfYaml struct {
    Endpoints SectionStorageEndpoint `yaml:"endpoints"`
}

type SectionStorageEndpoint struct {
    URL       string `yaml:"url"`
    AccessKey string `yaml:"access_key"`
    SecretKey string `yaml:"secret_key"`
    UseSSL    bool   `yaml:"use_ssl"`
    Location  string `yaml:"location"`
}
Run Code Online (Sandbox Code Playgroud)

这里url和location字段在 yaml 文件中填充了正确的值,但其他字段为空!

很想知道当我尝试打印如下字段时:

viper.Get("endpoints.access_key")
Run Code Online (Sandbox Code Playgroud)

它在 yaml 文件中打印正确的值并且不为空!

mes*_*ati 11

终于找到了解决方案,更改yaml:标签mapstructure:即可解决问题。

看来 viper 无法解组我的.yaml文件中没有相同键名的字段。就像问题中的access_keyand一样,导致结构体字段位于 where和。secret_keyAccessKeySecretKey

location但是像和that这样的字段url在结构体和文件中具有相同的名称.yaml,并且没有问题。

正如这个问题所说:

问题是viper使用 MapStructure 包将配置映射解组到结构。它不支持 yaml 包使用的 yaml 标签。

因此,更改yaml:标签中的 即可mapstructure:解决问题。