...

/

Viper and Environment Variables

Viper and Environment Variables

You'll learn about Viper and environment variables in this lesson.

Viper supports automatic environment variables, aliases, binding, prefixes, and empty environment variables.

Viper and environment variables

Environment variables are an important configuration source and the only one for 12-factor applications, which is a common pattern for building service-based systems.

Viper has excellent support for environment variables. When using Viper with environment variables it’s important to note that environment variables are case-sensitive.

Automatic environment

The simplest way to use environment variables is via the viper.AutomaticEnv() function, which makes all environment variables available as Viper keys.

func main() {
	viper.AutomaticEnv()
	home := viper.Get("home")
	fmt.Println(home)
}

/Users/gigi.sayfan

This is very straightforward, but in many cases, you may want to map environment variables to specific Viper keys. This is especially important using multiple configuration modes. For example, your program may have a configuration key called “output-dir” for the location of your output files, but if it is not defined you want to default to the HOME environment variable. You can do that with Viper’s RegisterAlias() function that allows us to have multiple keys for the same value.

Using aliases

func main() {
	viper.AutomaticEnv()
	viper.Register
...