第一個簡單的項目,去這里。根據用戶輸入,我需要將新密鑰添加到現有配置文件中。我設法用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存儲庫中讀到,編寫函數在處理現有或不存在的文件方面非常有爭議,并且有點錯誤,但我希望它們在像這樣的簡單情況下工作。我還嘗試了其他功能(即),但沒有成功。SafeWriteConfig我使用的是Go 1.16.2和Viper 1.7.1。我做錯了什么?
2 回答

12345678_0001
TA貢獻1802條經驗 獲得超5個贊
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

慕田峪4524236
TA貢獻1875條經驗 獲得超5個贊
嘗試 ;您將能夠命名要寫入的文件。WriteConfigAs(filename)
如果 WriteConfig 中沒有錯誤,則可能是更改未寫入您期望的文件。
viper.ConfigFileUsed()
應返回默認使用的路徑。
- 2 回答
- 0 關注
- 91 瀏覽
添加回答
舉報
0/150
提交
取消