Viper: Simple way to initialize a config file

Created on 22 Dec 2017  路  3Comments  路  Source: spf13/viper

Hello. I was searching for a way to initialize the config file, but still couldn't find one.

viper.SetConfigName("config")
viper.SetConfigType("json")
viper.AddConfigPath("$HOME")

And then I tried the new SafeWriteConfig() or any of the variety merged two weeks ago, but it didn't create new file or it will overwrite the original config file no matter what. And because of the $HOME, I might need to write a function to be cross-platform. I just wish there could be a cleaner way.

Or we could add O_CREATE to this line of code ?
https://github.com/spf13/viper/blob/master/viper.go#L1254

And also is it a good idea to have SafeWriteConfig() to create a new file with the first config path and config name ?

Most helpful comment

Is there anyone working on this issue? 18 months passed and WriteConfig still requires the file must exist before writing, which is different from what the docs say.

All 3 comments

Is there anyone working on this issue? 18 months passed and WriteConfig still requires the file must exist before writing, which is different from what the docs say.

This seems to be fixed?

v1.4.0: SafeWriteConfig() does not create a new config file:

File "config" Not Found in "[{path hidden}]"

Create and initialize with:

// stub init
configHome := "my/path"
configName := "config"
configType := "yml"
configPath := filepath.Join(configHome, configName+"."+configType)
// ----

viper.AddConfigPath(configHome)
viper.SetConfigName(configName)
viper.SetConfigType(configType)

_, err := os.Stat(configPath)
if !os.IsExist(err) {
    if _, err := os.Create(configPath); err != nil { // perm 0666
        // handle failed create
        ....
    }
}
if err := viper.SafeWriteConfig(); err != nil {
    // handle failed write
    ....
}
Was this page helpful?
0 / 5 - 0 ratings

Related issues

gmaxwell94 picture gmaxwell94  路  5Comments

Giri4joyz picture Giri4joyz  路  3Comments

TimJones picture TimJones  路  4Comments

akshaylb picture akshaylb  路  4Comments

kubaugustyn picture kubaugustyn  路  3Comments