0

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?

Alberto Coletta
  • 1,563
  • 2
  • 15
  • 24
  • To test : try `WriteConfigAs(filename)` ; you will be able to name the file to write to. – LeGEC Apr 01 '21 at 08:47
  • `viper.ConfigFileUsed()` should return the path used by default. If there is no error in `WriteConfig`, it's probably that the changes are not written to the file you expect. – LeGEC Apr 01 '21 at 08:50
  • Thanks. Turned out I was actually trying to write to a different file. There are several problems with Viper, in particular, this bug needs a work-around in how you read and write the config file: https://github.com/spf13/viper/issues/1017 – Alberto Coletta Apr 01 '21 at 16:27
  • If you want to answer officially, I'll accept it. – Alberto Coletta Apr 01 '21 at 16:29

2 Answers2

2
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
gudgl
  • 61
  • 6
  • Thanks. Turned out I was actually trying to write to a different file. There are several problems with Viper, in particular, this bug needs a work-around in how you read and write the config file: https://github.com/spf13/viper/issues/1017 – Alberto Coletta Apr 01 '21 at 16:28
1

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.

LeGEC
  • 46,477
  • 5
  • 57
  • 104