I am trying to write an app which only has one command, hence, I was thinking I might skip Cobra.
The app should be able to support all types of config:
- command line params
- env vars
- config file
I am using viper but I can't get it to read my cli params.
v := viper.New()
viper.SetConfigName("config")
viper.AddConfigPath(".")
v.SetDefault(pathKey, defaultPath)
fs := pflag.NewFlagSet("app", pflag.ExitOnError)
fs.String(pathKey, defaultPath, "Default path")
fs.StringSlice(wordsKey, []string{""}, "Words")
fs.String(loglevelKey, "info", "Log level")
if err := v.BindPFlags(fs); err != nil {
fmt.Println(err)
os.Exit(1)
}
if err := fs.Parse(os.Args[1:]); err != nil {
fmt.Println(err)
os.Exit(1)
}
v.AutomaticEnv()
if err := v.ReadInConfig(); err != nil {
fmt.Println("no conf file") //ignore, it can be either cli params, or conf file
}
var c conf
if err := v.Unmarshal(&c); err != nil {
fmt.Println(err)
os.Exit(1)
}
But I never get the cli params into the conf struct. Printing v
before the Unmarshal
doesn't show any of the cli params I provide.
What am I missing? Do I need to use cobra for this?
Or do I have to assign each flagset flag, e.g. fs.String(pathKey, defaultPath, "Default path")
, manually to the config struct?