亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

從 viper 配置文件中刪除鍵值對

從 viper 配置文件中刪除鍵值對

Go
拉丁的傳說 2023-04-04 14:51:55
有沒有辦法從加載的配置文件中刪除鍵/值對?viper.Set("key", nil)不起作用
查看完整描述

2 回答

?
弒天下

TA貢獻1818條經驗 獲得超8個贊

嘗試


delete(viper.Get("path.to.key").(map[string]interface{}), "key")

例子:


[backends]

  [backends.setibe]

    [backends.setibe.servers]

      [backends.setibe.servers.server0]

      url = "http://192.168.1.20:80"

      weight = 1

      [backends.setibe.servers.server1]

      url = "http://192.168.1.21:80"

      weight = 1

刪除“backends.setibe.servers.server1”


delete(viper.Get("backends.setibe.servers").(map[string]interface{}), "server2")


查看完整回答
反對 回復 2023-04-04
?
眼眸繁星

TA貢獻1873條經驗 獲得超9個贊

以下內容:


var rootCmd = &cobra.Command{

? ? //...

? ? PersistentPreRunE: writeConfig, //if --writeCfg, write viper config file and exit

}

func writeConfig(cmd *cobra.Command, args []string) error {

? ? if !writeCfg {

? ? ? ? return nil

? ? }

? ? cfg := viper.New()

? ? for k, v := range viper.AllSettings() {

? ? ? ? switch k {

? ? ? ? case "writecfg", "config", "dryrun":

? ? ? ? ? ? //do not propagate these

? ? ? ? default:

? ? ? ? ? ? //TODO: also check for zero values and exclude

? ? ? ? ? ? cfg.Set(k, v)

? ? ? ? }

? ? }

? ? if cfgFile == "" {

? ? ? ? filename := "." + os.Args[0] + ".yaml"

? ? ? ? home, err := os.UserHomeDir()

? ? ? ? cobra.CheckErr(err)

? ? ? ? cfgFile = filepath.Join(home, filename)

? ? }


? ? cfg.SetConfigFile(cfgFile)

? ? var err error

? ? if _, err = os.Stat(cfgFile); err != nil {

? ? ? ? err = os.WriteFile(cfgFile, nil, 0644)

? ? ? ? cobra.CheckErr(err)

? ? }

? ? err = cfg.WriteConfig()

? ? cobra.CheckErr(err)

? ? fmt.Println("config written successfully:")

? ? f, err := os.Open(cfgFile)

? ? cobra.CheckErr(err)

? ? defer f.Close()

? ? _, err = io.Copy(os.Stdout, f)

? ? cobra.CheckErr(err)

? ? os.Exit(0)

? ? return nil //unreachable

}


查看完整回答
反對 回復 2023-04-04
  • 2 回答
  • 0 關注
  • 197 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號