I have a config format that looks like below:
type config struct {
FooBar string `mapstructure:"foo_bar"`
BazBot string `mapstructure:"baz_bot"`
}
And my Cobra based CLI has flags with dashes (e.g. --foo-bar=value1 --baz-bot=value2
).
Viper does not know how to map these properly into the config when they are set at the CLI for the purpose of overriding the config file value. Is there any solution here? Viper config setup looks like this:
func loadConfig(cmd *cobra.Command) (*config, error) {
res := &config{}
if err := viper.BindPFlags(cmd.Flags()); err != nil {
return nil, err
}
viper.SetEnvPrefix("K")
viper.SetEnvKeyReplacer(strings.NewReplacer(".", "_", "-", "_"))
viper.AutomaticEnv()
var useConfigFile bool
if configFile, _ := cmd.Flags().GetString("config"); configFile != "" {
useConfigFile = true
viper.SetConfigFile(configFile)
}
if useConfigFile {
if err := viper.ReadInConfig(); err != nil {
return nil, err
}
if err := viper.Unmarshal(res); err != nil {
return nil, err
}
}
return res, nil
}
Also open to taking recommendations for a library that does support this if viper cannot do it.