when I use the Unmarshal
method of viper to fill my config structs with the values in my yaml file, some of the struct fields became empty!
I do it in this way:
viper.SetConfigType("yaml")
viper.SetConfigName("config")
viper.AddConfigPath("/etc/myapp/")
viper.AddConfigPath(".")
err := viper.ReadInConfig()
// error checking ...
conf := &ConfYaml{}
err = viper.Unmarshal(conf)
// error checking ...
And my structs are like this:
type ConfYaml struct {
Endpoints SectionStorageEndpoint `yaml:"endpoints"`
}
type SectionStorageEndpoint struct {
URL string `yaml:"url"`
AccessKey string `yaml:"access_key"`
SecretKey string `yaml:"secret_key"`
UseSSL bool `yaml:"use_ssl"`
Location string `yaml:"location"`
}
Here the url
and location
fields are filled with proper value in the yaml file, but the other fields are empty!
It's wondering that when I try to print a field like:
viper.Get("endpoints.access_key")
it prints the proper value in the yaml file and is not empty!!
Finally found the solution, changing yaml:
tags to mapstructure:
will fix the problem.
It seems that viper couldn't unmarshal the fields that haven't the same key name in my .yaml
file. Like the access_key
and secret_key
in the question, cause the struct fields where AccessKey
and SecretKey
.
But the fields like location
and url
that had the same name in the struct and .yaml
file, and there was no problem.
As this issue says:
The problem is that
viper
uses mapstructure package for unmarshalling config maps to structs. It doesn't support yaml tags used by the yaml package.
So changing the yaml:
in the tags to mapstructure:
had fixed the problem.