使用Viper将新密钥写入配置文件



Go here的第一个简单项目。

根据用户输入,我需要向现有的配置文件中添加新的密钥。我设法用Viper正确地阅读了它,并在整个应用程序中使用它,但WriteConfig似乎不起作用。

这里有一个片段:

oldConfig := viper.AllSettings()
fmt.Printf("All settings #1 %+vnn", oldConfig)
viper.Set("setting1", chosenSetting1)
viper.Set("setting2", chosenSetting2)
newConfig := viper.AllSettings()
fmt.Printf("All settings #2 %+vnn", newConfig)
err := viper.WriteConfig()
if err != nil {
log.Fatalln(err)
}

newConfig包括预期的新设置,但WriteConfig不将更改应用于配置文件。

我在Viper repo中读到,编写函数在处理现有或不存在的文件方面非常有争议,而且有点bug,但我希望它们能在这样的简单情况下工作。

我还尝试了其他功能(即SafeWriteConfig(,但没有成功。

我使用的是Go 1.16.2和Viper 1.7.1。

我做错了什么?

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

首先需要指定配置文件的路径

或者试试下面的方法

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

尝试WriteConfigAs(filename);您将能够命名要写入的文件。

如果WriteConfig中没有错误,则可能是更改没有写入您期望的文件。

viper.ConfigFileUsed()应返回默认情况下使用的路径。

最新更新