1

有没有办法从加载的配置文件中删除键/值对?

viper.Set("key", nil)

不工作

4

2 回答 2

1

尝试

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")
于 2018-10-05T14:26:15.077 回答
0

基于@user539810 的评论,我有以下内容:

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
}
于 2021-08-19T19:34:40.980 回答