goviper-go

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?


Solution

  • 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.