毒蛇没有在解组时考虑我结构中的yaml标签

时间:2019-06-26 13:27:15

标签: go yaml viper-go

当我使用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文件中打印正确的值,并且不为空

1 个答案:

答案 0 :(得分:0)

最终找到了解决方案,将yaml:标签更改为mapstructure:将解决此问题。

在我的.yaml文件中,毒蛇似乎无法解组没有相同键名的字段。像问题中的access_keysecret_key一样,将结构域放在AccessKeySecretKey处。

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

this issue说:

  

问题是viper使用mapstructure包用于   解组配置映射到结构。它不支持Yaml标签   由yaml软件包使用。

因此,将标记中的yaml:更改为mapstructure:已解决了该问题。