Trying to Unmarshal
a hcl
config file to a struct, using viper
, this error is returned: 1 error(s) decoding:\n\n* 'NATS' expected a map, got 'slice'
. What is missing?
The code:
func lab() {
var c conf
// config file
viper.SetConfigName("draft")
viper.AddConfigPath(".")
viper.SetConfigType("hcl")
if err := viper.ReadInConfig(); err != nil {
log.Error(err)
return
}
log.Info(viper.Get("NATS")) // gives [map[port:10041 username:cl1 password:__Psw__4433__ http_port:10044]]
if err := viper.Unmarshal(&c); err != nil {
log.Error(err)
return
}
log.Infow("got conf", "conf", c)
}
type conf struct {
NATS struct {
HTTPPort int
Port int
Username string
Password string
}
}
And the config file (draft.hcl
inside current directory):
NATS {
HTTPPort = 10044
Port = 10041
Username = "cl1"
Password = "__Psw__4433__"
}
Edit
Have checked this struct with hcl
package and it gets marshaled/unmarshalled correctly. Also this works correctly with yaml
and viper
.
There is a difference between these two where log.Info(viper.Get("NATS"))
is called. While the hcl
version returns a slice of maps, the yaml
version returns a map: map[password:__psw__4433__ httpport:10044 port:10041 username:cl1]
.