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")
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
}
- 2 回答
- 0 关注
- 142 浏览
添加回答
举报