Using Viper for Configuration Management
Discover how to use Viper for flexible configuration management in Go command-line applications built with Cobra. Learn to bind configuration keys to flags, read from environment variables, and manage settings via config files to enhance your CLI tool's adaptability.
We'll cover the following...
When we use the Cobra generator to create the boilerplate code for our application, it automatically enables Viper. Viper is a configuration management solution for Go applications that allows us to specify configuration options for our application in several ways, including configuration files, environment variables, and command-line flags.
Defining the initConfig() function
Cobra enables Viper by running the function initConfig() when initializing the
application. This function is defined in the cmd/root.go file:
If the user specifies a config file using the flag --config, Viper sets it as the
configuration file for the application. If not, it sets the configuration file as
the file $HOME/.pScan.yaml. Then it uses the function viper.AutomaticEnv() to read
the configuration from environment ...