当我使用Unmarshal方法viper用yaml文件中的值填充我的配置结构时,一些struct字段变为空!我是这样做的:
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"`
}在这里,url和location字段在yaml文件中使用适当的值填充,但是其他字段是空的!
我想知道,当我试图打印这样的字段时:
viper.Get("endpoints.access_key")它在yaml文件中打印正确的值,而不是空的!!
发布于 2019-06-26 14:31:39
最后找到了解决方案,将yaml:标记更改为mapstructure:将解决问题。
看来,毒蛇无法解除我的.yaml文件中没有相同密钥名的字段的编组。与问题中的access_key和secret_key一样,导致AccessKey和SecretKey所在的struct字段。
但是像location和url这样的字段在struct和.yaml文件中具有相同的名称,并且没有问题。
正如本期所说:
问题是,
viper使用mapstructure包将配置映射解组到结构。它不支持yaml包使用的yaml标记。
因此,将标记中的yaml:更改为mapstructure:解决了问题。
https://stackoverflow.com/questions/56773979
复制相似问题