2 minutes
Overriding configuration variables with env vars in Go
Intro
Here is a demo repository which shows how you can fetch and override variables from configuration file.
Code: https://github.com/pgaijin66/go-config-yaml
Everything is pretty straight forward, you add viper configuraton, show it where to look and read the variables.
You can override variables using env vars using viper.AutomaticEnv()
function. When using viper.AutomaticEnv(), it checks for env variables of the uppercased(key)
and if its defined the overrides it with the value from env variable.
viper.AutomaticEnv()
is case sensitive. It checks for environment varible but uppercased verison i.e if you want to override environment in config file you need to set export ENVIRONMENT="PROD"
in your shell.
Gotcha
For nested yaml file, override the data in the yaml file it’s a bit different.
For example: In configuration like below
server:
host: "localhost"
port: 9090
Viper looks for values in environment variables first like this SERVER.HOST
and SERVER.PORT
instead of PORT
or HOST
but since shell does not support dot
format for environment variables, we transform it to dash
format using
viper.SetEnvKeyReplacer(strings.NewReplacer(., _))
viper needs to replace .
with _
and you need to set environment variable like this. After this if you want to override port, then your environment variable should be set to export SERVER_PORT=9999
Here is in depth implementation of the above concept in video
Part 1