go - Viper 在解码时不考虑我的结构中的 yaml 标签

标签 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 文件中打印正确的值并且不为空!!

最佳答案

终于找到了解决办法,将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: 已解决问题。

关于go - Viper 在解码时不考虑我的结构中的 yaml 标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56773979/

相关文章:

python - 按操作系统限制 Environment.yml 依赖项

golang : How can I use pflag with other packages that use flag?

go - 使用 Viper 在 Go 中将字符串映射作为环境变量传递

go - 如何让 sqlite 出错而不是在 golang 中创建丢失的数据库文件?

go - 错误 400 oauth2 谷歌云存储 - go lang

kubernetes - helm 获取子图服务名称

go - 如何使用 Viper 从嵌套的 YAML 结构中获取值?

go - 没有取消传播的上下文

Go中的正则表达式字符串

doctrine - 如何用 Doctrine 在 yaml 中定义当前时间戳?