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

Viper is not considering the yaml tags in my structs on unmarshalling

当我使用 viper 的 Unmarshal 方法用我的 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 ...

我的结构是这样的:

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"`
}

这里urllocation字段在yaml文件中填写了正确的值,但其他字段为空!

奇怪的是,当我尝试打印如下字段时:

viper.Get("endpoints.access_key")

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

终于找到了解决办法,将 yaml: 标签更改为 mapstructure: 即可解决问题。

似乎 viper 无法解组在我的 .yaml 文件中没有相同键名的字段。就像问题中的 access_keysecret_key 一样,导致结构字段 AccessKeySecretKey.

但是像locationurl这样的字段在struct和.yaml文件中同名,没有问题。

正如this issue所说:

The problem is that viper uses mapstructure package for unmarshalling config maps to structs. It doesn't support yaml tags used by the yaml package.

因此将标签中的 yaml: 更改为 mapstructure: 已解决问题。