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

Go 使用Viper将新密钥写入配置文件,go,viper-go,Go,Viper Go,第一个简单的项目是围棋 根据用户输入,我需要向现有配置文件添加新密钥。 我设法用Viper正确地阅读它,并在整个应用程序中使用它,但WriteConfig似乎不起作用 下面是一个片段: oldConfig := viper.AllSettings() fmt.Printf("All settings #1 %+v\n\n", oldConfig) viper.Set("setting1", chosenSe

第一个简单的项目是围棋

根据用户输入,我需要向现有配置文件添加新密钥。 我设法用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(文件名)
;您将能够命名要写入的文件

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


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

要进行测试,请尝试
WriteConfigAs(文件名)
;您将能够命名要写入的文件。
viper.ConfigFileUsed()
应返回默认使用的路径。如果
WriteConfig
中没有错误,则可能是更改没有写入您期望的文件。谢谢。事实证明,我实际上是在尝试写入另一个文件。Viper有几个问题,特别是,这个bug需要解决如何读取和写入配置文件的问题:如果你想正式回答,我会接受。谢谢。事实证明,我实际上是在尝试写入另一个文件。Viper有几个问题,特别是,这个bug需要解决如何读写配置文件的问题:谢谢。最后的解决方案是读取具有完整路径和扩展名的文件:
viper.SetConfigFile(path.Join(home,.myconfig.json))
。我甚至以书面形式指定了完整路径和扩展名:
viper.writeConfigFile(viper.ConfigFileUsed())