Viper在反序列化时没有考虑我的结构体中的mapstructure标签。

huangapple go评论81阅读模式
英文:

Viper is not considering the mapstructure tags in my structs on umarshalling

问题

当我使用Viper的Unmarshal方法将我的结构体填充为Yaml文件中的值时,所有的结构体字段仍然为空,我搜索了很多解决方案,但它们都没有起作用 Viper在反序列化时没有考虑我的结构体中的mapstructure标签。

我尝试将标签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>

请有人帮我修复这个错误!

英文:

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 Viper在反序列化时没有考虑我的结构体中的mapstructure标签。

I tried changing the tag mapstructure to yaml and structure , still didn't work...

main.go:

type Test struct {
	T TConfig `mapstructure:&quot;apiserver&quot;`
}

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

config.yml:

apiserver:
  - host: localhost
  - port: 8080

output:

read config error: 1 error(s) decoding:

* &#39;apiserver&#39; expected a map, got &#39;slice&#39;
config: &lt;nil&gt;

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".

huangapple
  • 本文由 发表于 2022年2月7日 23:19:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/71020975.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定