Handling configuration is a common requirement when developing Go applications. Configuration may come from configuration files, environment variables, command line parameters, etc. Viper is a powerful library that can help us handle these configurations.
What is Viper?
Viper is an application configuration solution for Go applications. It supports JSON, TOML, YAML, HCL, envfile and Java properties configuration file formats. It also supports environment variables, command line flags, remote configuration systems (such as etcd or Consul), and can directly monitor configuration file changes.
How to use Viper?
Read configuration files
First, we need to tell Viper where to find configuration files and how to read them. This can be achieved with the following code:
("config") // Configuration file name (without suffix)("yaml") // If the configuration file name does not have an extension, this item needs to be set("/etc/appname/") // Find the path where the configuration file is located("$HOME/.appname") // Multiple calls to add multiple search pathserr := () // Find and read configuration filesif err != nil { // Handle errors in reading configuration files panic(("Fatal error config file: %s \n", err)) }
Get the configuration value
Once Viper has read the configuration file, we can use itGet
Function to get configuration values:
port := ("port") databaseDriver := ("")
Set default values
Viper also allows us to set the default values of the configuration. This is very useful if the configuration item is not defined in the configuration file, but we need a default value again:
("ContentDir", "content") ("LayoutDir", "layouts")
Use environment variables
Viper can read environment variables:
() databaseUrl := ("DATABASE_URL")
Use command line flags
Viper can also be used with the standard libraryflag
Use packages together to handle command line flags:
var cfgFile string func init() { (&cfgFile, "c", "", "config file") () } func main() { if cfgFile != "" { // If a configuration file is specified, the specified configuration file is resolved (cfgFile) err := () if err != nil { ("Error reading config file, %s", err) } } // ... }
Monitor configuration changes and reload configuration
Viper can even monitor changes in configuration files and reload configurations when they change:
() (func(e ) { ("Config file changed:", ) })
This is the end of this article about using Viper to handle the configuration of Go applications. For more information about Viper to handle Go applications, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!