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

3.6k Views Asked by At

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

There are 1 best solutions below

0
On

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