Alberto Coletta
Alberto Coletta

Reputation: 1603

Writing new key to configuration file with Viper

First easy project with Go here.

Based on user input, I need to add new keys to my existing configuration file. I manage to read it correctly with Viper and use it throughout the application, but WriteConfig doesn't seem to work.

Here's a snippet:

        oldConfig := viper.AllSettings()
        fmt.Printf("All settings #1 %+v\n\n", oldConfig)

        viper.Set("setting1", chosenSetting1)
        viper.Set("setting2", chosenSetting2)

        newConfig := viper.AllSettings()
        fmt.Printf("All settings #2 %+v\n\n", newConfig)

        err := viper.WriteConfig()
        if err != nil {
            log.Fatalln(err)
        }

newConfig includes new settings as expected, but WriteConfig doesn't apply changes to the config file.

I've read in Viper repo that writing functions are quite controversial and a bit buggy in terms of treating existing or non-existing files, but I expect them to work in simple cases like this.

I also tried other functions (i.e. SafeWriteConfig) with no success.

I'm using Go 1.16.2 and Viper 1.7.1.

What am I doing wrong?

Upvotes: 0

Views: 6548

Answers (2)

LeGEC
LeGEC

Reputation: 51890

try WriteConfigAs(filename) ; you will be able to name the file to write to.

If there is no error in WriteConfig, it's probably that the changes are not written to the file you expect.

viper.ConfigFileUsed() should return the path used by default.

Upvotes: 1

gudgl
gudgl

Reputation: 61

viper.WriteConfig() // writes current config to predefined path set by 'viper.AddConfigPath()' and 'viper.SetConfigName'

you first need to specify the path to the config file

or try this method bellow

viper.SafeWriteConfigAs("/path/to/my/.config") // will error since it has already been written

Upvotes: 2

Related Questions