Last active
November 2, 2019 01:49
-
-
Save ianfoo/1737a7986cd3303506014c0193523e52 to your computer and use it in GitHub Desktop.
Deleting a setting in Viper (any config type)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| bobjects: | |
| limit: 100 | |
| foo: | |
| blatz: quux |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| bobjects: | |
| limit: 100 | |
| foo: | |
| bar: baz | |
| blatz: quux |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package main | |
| import ( | |
| "log" | |
| "os" | |
| "path/filepath" | |
| "github.com/spf13/viper" | |
| ) | |
| func main() { | |
| cfgType := "hcl" | |
| if len(os.Args) > 1 { | |
| cfgType = os.Args[1] | |
| } | |
| mkCfgFileName := func(base string) string { | |
| return filepath.Join(os.TempDir(), base+"."+cfgType) | |
| } | |
| viper.Set("foo.bar", "baz") | |
| viper.Set("foo.blatz", "quux") | |
| viper.Set("bobjects.limit", 100) | |
| if err := writeConfig(mkCfgFileName("config")); err != nil { | |
| bail(err) | |
| } | |
| viper.Set("foo.bar", nil) | |
| if err := writeConfig(mkCfgFileName("config-del")); err != nil { | |
| bail(err) | |
| } | |
| } | |
| func writeConfig(filename string) error { | |
| viper.SetConfigFile(filename) | |
| return viper.WriteConfig() | |
| } | |
| func bail(err error) { | |
| log.SetFlags(0) | |
| log.SetPrefix("error: ") | |
| log.Fatalln(err) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment