Here is a demo repository which shows how you can fetch and override variables from configuration file.
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.
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.PORT instead of
HOST but since shell does not support
dot format for environment variables, we transform it to
dash format using
viper needs to replace
_ 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