I have structs defined as follows
type config struct {
Contexts map[string]Context `mapstructure:"contexts"`
CurrentContext string `mapstructure:"current-context"`
Tokens []Token `mapstructure:"tokens"`
}
type Context struct {
Endpoint string `mapstructure:"endpoint,omitempty"`
Token string `mapstructure:"token,omitempty"`
Platform string `mapstructure:"platform"`
Components []string `mapstructure:"components,omitempty"`
Channel string `mapstructure:"channel,omitempty"`
Version string `mapstructure:"version,omitempty"`
EnforcedProvider string `mapstructure:"enforced-provider,omitempty"`
}
I'm writing to a YAML config file as follows
configObj.Contexts[contextName] = context
viper.Set("contexts", configObj.Contexts)
viper.Set("current-context", configObj.CurrentContext)
viper.Set("tokens", configObj.Tokens)
err = viper.WriteConfig()
if err != nil {
return err
}
The mapstructure tags I have defined are not written to the YAML file, instead the field names are written in lower case. This is especially a problem with the EnforcedProvider field which is written as enforcedprovider instead of enforced-provider.
How do I make it so that the mapstructure tag is used ?

The documentation mentions mapstructure tags in its Unmarshaling section, but not in its WriteConfig section.
It looks like WriteConfig will go through one of the default encoders :
https://github.com/spf13/viper/blob/b89e554a96abde447ad13a26dcc59fd00375e555/viper.go#L341
Marshal/Unmarshalfunctions):https://github.com/spf13/viper/blob/b89e554a96abde447ad13a26dcc59fd00375e555/internal/encoding/yaml/codec.go
If you know you will read/write from yaml files only, the simplest way is to set
yamltags on your struct (following the documentation of thegopkg.in/yaml.v2package) :