Skip to content

Instantly share code, notes, and snippets.

@xcoulon
Last active June 28, 2023 16:30
Show Gist options
  • Save xcoulon/fc088768cd895c4cb8f68dc3cd238a28 to your computer and use it in GitHub Desktop.
Save xcoulon/fc088768cd895c4cb8f68dc3cd238a28 to your computer and use it in GitHub Desktop.
const (
// Constants for viper variable names. Will be used to set
// default values as well as to get each value
...
varLogLevel = "log.level"
)
func New() *Configuration {
c := Configuration{
v: viper.New(),
}
...
c.v.SetDefault(varPathToConfig, "./config.yaml")
c.v.SetDefault(varLogLevel, "info")
c.v.AutomaticEnv()
c.v.SetEnvKeyReplacer(strings.NewReplacer(".", "_"))
c.v.SetTypeByDefaultValue(true)
c.v.SetConfigFile(c.GetPathToConfig())
err := c.v.ReadInConfig() // Find and read the config file
logrus.WithField("path", c.GetPathToConfig()).Warn("loading config")
// just use the default value(s) if the config file was not found
if _, ok := err.(*os.PathError); ok {
logrus.Warnf("no config file '%s' not found. Using default values", c.GetPathToConfig())
} else if err != nil { // Handle other errors that occurred while reading the config file
panic(fmt.Errorf("fatal error while reading the config file: %s", err))
}
setLogLevel(c.GetLogLevel())
// monitor the changes in the config file
c.v.WatchConfig()
c.v.OnConfigChange(func(e fsnotify.Event) {
logrus.WithField("file", e.Name).Warn("Config file changed")
setLogLevel(c.GetLogLevel())
})
return &c
}
// GetLogLevel returns the log level
func (c *Configuration) GetLogLevel() string {
return c.v.GetString(varLogLevel)
}
...
@malikbenkirane
Copy link

malikbenkirane commented Jun 28, 2023

hi can you give us please a little more context or a complete example
who is supposed to get Configuration instantiated with New()*Configuration

Sorry, I mean, how can I access my configuration from my cobra Command for instance
That is the example I am definitely looking forward to find.

EDIT

most of the answers can easily be found at https://github.com/spf13/viper

ReadInConfig makes the configuration available simply with calling New(). This is that simple. After-all, all the getters are available to the interface you design (here it is Configuration).

Also there is much more viper can do dealing with key/value stores (encrypted and unencrypted). For example
https://github.com/spf13/viper#remote-keyvalue-store-example---encrypted

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment