Skip to content

Instantly share code, notes, and snippets.

@ianfoo
Last active November 2, 2019 01:49
Show Gist options
  • Select an option

  • Save ianfoo/1737a7986cd3303506014c0193523e52 to your computer and use it in GitHub Desktop.

Select an option

Save ianfoo/1737a7986cd3303506014c0193523e52 to your computer and use it in GitHub Desktop.
Deleting a setting in Viper (any config type)
bobjects:
limit: 100
foo:
blatz: quux
bobjects:
limit: 100
foo:
bar: baz
blatz: quux
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