Koanf is another configuration module, and it's way better than the viper.
Koanf has providers and parsers. Providers specify where the configuration is and parsers providers a way for parsing the given configuration. First of all you must define a configuration structure as before:
type(
// Config holds all configurations
Config struct {
Token string `koanf:"token"`
Words []string `koanf:"words"`
}
)
Before anything, we create an instance of Koanf for the current location.
Here you only use the koanf
tag to specify the configuration fields name. After that you must load the following locations:
- Default (specify in an instance of configuration structure)
// load default configuration from file
if err := k.Load(structs.Provider(Default(), "konaf"), nil); err != nil {
logrus.Fatalf("error loading default: %s", err)
}
// load configuration from file
if err := k.Load(file.Provider("config.yml"), yaml.Parser()); err != nil {
logrus.Errorf("error loading config.yml: %s", err)
}
// Prefix indicates environment variables prefix
const Prefix = "jasoos_"
// load environment variables
if err := k.Load(env.Provider(Prefix, ".", func(s string) string {
return strings.Replace(strings.ToLower(
strings.TrimPrefix(s, Prefix)), "_", ".", -1)
}), nil); err != nil {
logrus.Errorf("error loading environment variables: %s", err)
}
Koanf has a provider for structures so you can define Default configuration in an instance of Configuration structure as follow:
// Default return default configuration
// nolint: gomnd
func Default() Config {
return Config{
Token: "AwesomeBotToken",
Words: []string{
"Hello",
"Home",
"Raha",
"Room",
},
}
}
In the end, you unmarshal the configuration from Koanf into an instance of Configuration structure.
if err := k.Unmarshal("", &instance); err != nil {
logrus.Fatalf("error unmarshalling config: %s", err)
}