I wish to initialize (create and populate with defaults) a config file with viper if it doesn't exist.
My attempt is as follow:
func setConfig() {
usr, _ := user.Current()
homedir := usr.HomeDir
v := viper.New()
v.SetDefault("instance", "acmedev01")
v.SetDefault("account", "serviceaccount")
v.SetDefault("password", "svcacctpassword")
v.SetConfigName("." + filepath.Base(os.Args[0]) + ".cfg")
v.AddConfigPath(homedir)
v.SetConfigType("toml")
err := v.ReadInConfig()
if _, ok := err.(viper.ConfigFileNotFoundError); ok {
// Config file not found, initialize config file
v.SafeWriteConfig()
//log.Fatal("Please populate config file with appropriate values")
} else {
// Config file was found but another error was produced
checkerr(err)
}
fmt.Println(v.ConfigFileUsed())
The above doesn't seem to write any file nor give me a return on ConfigFileUsed
. I must be missing something obvious.
There are two pints to consider:
The line
err := v.ReadInConfig()
does not return any error if file does not exist, it just creates a new one. So the execution does not go into if block but into else.
And then it depends on how the checkerr()
function is implemented (the function does not seem to exist in the golang standard lib). If it looks like this
func checkerr(e error) { os.Exit(0) }
you will never reach the line
fmt.Println(v.ConfigFileUsed())
actually the file is created in user folder and it is a hidden file (starts with .) to see it just use ls -a
in your user home directory.