【问题标题】:Viper is not considering the mapstructure tags in my structs on umarshallingViper 没有考虑我的 umarshalling 结构中的 mapstructure 标签
【发布时间】:2022-02-08 03:12:44
【问题描述】:

当我使用 Viper 的 Unmarshal 方法用我的 Yaml 文件中的值填充我的结构时,所有结构文件仍然是空的,我搜索了很多解决方案,但它们都没有工作:(

我尝试将标签 mapstructure 更改为 yamlstructure ,仍然没有工作...

main.go:

type Test struct {
    T TConfig `mapstructure:"apiserver"`
}

type TConfig struct {
    Address int `mapstructure:"host"`
    Port    int `mapstructure:"port"`
}
func main() {
    var aaa *Test
    viper.AutomaticEnv()
    viper.AddConfigPath("./")
    viper.SetConfigName("config")
    if err := viper.ReadInConfig(); err != nil {
        panic(err)
    }
    if err := viper.Unmarshal(&aaa); err != nil {
        fmt.Println("read config error:", err)
    }
    fmt.Println("config:", aaa)
}

config.yml:

apiserver:
  - host: localhost
  - port: 8080

输出:

read config error: 1 error(s) decoding:

* 'apiserver' expected a map, got 'slice'
config: <nil>

请有人帮我修复错误!

【问题讨论】:

  • 我认为信息很清楚,你需要传递 map 但你传递 struct。
  • 删除配置文件中的破折号。这表示一个数组或值切片。此外,您将“主机”设置为 int 值;在配置文件中它是一个字符串。
  • maptstructure 是来自特定库的结构标记。你确定毒蛇正在使用这些吗?

标签: go yaml unmarshalling viper


【解决方案1】:

删除配置文件中的破折号。这表示一个数组或值切片。

这应该可行:

apiserver:
  host: localhost
  port: 8080

您也将 Address 设置为 int 值;在配置文件中它是一个字符串:“localhost”。

【讨论】:

    猜你喜欢
    • 2019-11-08
    • 2022-12-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多