Configuration mapping on the Go struct based on viper
Configuration struct:
type HttpClientConfig struct {
Url string `mapstructure:"url"`
Timeout string `mapstructure:"timeout"`
}
Environment variables:
export PREFIX_URL=example.com
export PREFIX_TIMEOUT=200ms
Init code:
var config HttpClientConfig
if err := confmap.MapEnvs("PREFIX", &config); err != nil {
panic(err)
}
client := NewHttpClient(config)
With Generics:
config, err := confmap.MapEnvsTyped[HttpClientConfig]("PREFIX")
if err != nil {
panic(err)
}
client := NewHttpClient(config)
type HttpClientConfig struct {
Url string `mapstructure:"url"`
Timeout string `mapstructure:"timeout"`
}
func (c Http) DefaultEnvs() map[string]any {
return map[string]any{
"timeout": "1s",
}
}