当我使用 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"`
}
此处url
和location
字段在yaml文件中填入了正确的值,但其他字段为空!
奇怪的是,当我尝试打印如下字段时:
viper.Get("endpoints.access_key")
它在 yaml 文件中打印正确的值并且不为空!!
最佳答案
终于找到了解决办法,将yaml:
标签改成mapstructure:
即可解决问题。
似乎 viper 无法解码在我的 .yaml
文件中没有相同键名的字段。就像问题中的 access_key
和 secret_key
一样,导致 AccessKey
和 SecretKey
的结构字段。
但是location
和url
等字段在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:
已解决问题。
关于go - Viper 在解码时不考虑我的结构中的 yaml 标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56773979/