【发布时间】:2022-02-08 03:12:44
【问题描述】:
当我使用 Viper 的 Unmarshal 方法用我的 Yaml 文件中的值填充我的结构时,所有结构文件仍然是空的,我搜索了很多解决方案,但它们都没有工作:(
我尝试将标签 mapstructure 更改为 yaml 和 structure ,仍然没有工作...
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