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

问题描述

Go here 的第一个简单项目。

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

这是一个片段:

        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 按预期包含新设置,但 WriteConfig 不会将更改应用于配置文件

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

我也尝试了其他函数(即 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() 应该返回默认使用的路径。