英文:
Viper is not considering the mapstructure tags in my structs on umarshalling
问题
当我使用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>
请有人帮我修复这个错误!
英文:
when I use the Unmarshal
method of Viper to fill my struct with the values in my Yaml file, All struct fileds were still empty, I searched many solutions, but all of them didn't work at all
I tried changing the tag mapstructure
to yaml
and structure
, still didn't work...
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
output:
read config error: 1 error(s) decoding:
* 'apiserver' expected a map, got 'slice'
config: <nil>
Please someone help me fix the bug!
答案1
得分: 1
请删除配置文件中的破折号。这表示一个值的数组或切片。
以下是正确的配置:
apiserver:
host: localhost
port: 8080
此外,你将地址(Address)设置为整数值;但在配置文件中,它应该是一个字符串:"localhost"。
英文:
Remove the dashes in your config file. That indicates an array or slice of values.
This should work:
apiserver:
host: localhost
port: 8080
Also you have Address set to int value; in the config file it is a string: "localhost".
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论