Here's my config.yaml file
server:
port: 5000
here's my logic to unmarshal using viper
type Configurations struct {
Server ServerConfig
}
type ServerConfig struct {
Port int
}
// LoadConfig reads configuration from file or environment variables.
func LoadConfig(path string) (config Configurations, err error) {
viper.AddConfigPath(path)
viper.SetConfigName("config")
viper.SetConfigType("yaml")
viper.AutomaticEnv()
err = viper.ReadInConfig()
if err != nil {
return
}
err = viper.Unmarshal(&config)
return
}
I have set env variable export PORT=9000, now my question is how can I map the environmental variable PORT to Configurations.ServerConfig.Port.
I would like to have config file with default values for dev and would like my app to read/override config from env variables on production, how can I achieve this using viper.
I see following options
- set
SERVER_PORTand then use replacer like below to unmarshal it to struct
replacer := strings.NewReplacer(".", "_")
viper.SetEnvKeyReplacer(replacer)
But I would like to map variable PORT to the struct member, probably because my hosting service provider sets PORT env variable, and I cannot use 2nd point because I would like to have yaml for default values.