What is Viper
Viper is a library that facilitates Go language applications to process configuration information. It can handle configurations in multiple formats. Features it supports:
- Set default values
- Read configuration data from JSON, TOML, YAML, HCL, and Java properties files
- You can monitor changes in configuration files and reread configuration files
- Read configuration data from environment variables
- Read data from remote configuration systems and monitor them (such as etcd, Consul)
- Reading configuration from command parameters
- Read from buffer
- Call function to set configuration information
Why use Viper
When building modern applications, you don't have to worry about the configuration file format; you can focus on building great software.
Viper can do the following:
- Load and parse configuration files in JSON, TOML, YAML, HCL, or Java properties formats
- You can set default values for various configuration items
- You can specify configuration items on the command line to override configuration values
- Aliases are provided, so that parameter renaming can be implemented without breaking existing code
- It is easy to distinguish the same difference between the user-provided command line parameters or configuration files as default
The priority order of Viper to read configuration information, from high to low, as follows:
- Explicitly call Set function
- Command line parameters
- Environment variables
- Configuration File
- key/value storage system
- default value
The key of the Viper configuration item is case-insensitive.
Project address:/spf13/viper
use
Set default values
The default value is not required. If the configuration file, environment variable, remote configuration system, command line parameters, and Set function are not specified, the default value will work.
("name", "xiaoming") ("age", "12") ("notifyList", []string{"xiaohong","xiaoli","xiaowang"})
Read configuration files
Viper supports JSON, TOML, YAML, HCL and Java properties files.
Viper can search for multiple paths.But currently, a single Viper instance only supports a single configuration file。
Viper does not search for any paths by default.
Here is an example of how to search and read configuration files using Viper.
The path is not required, but it is best to provide at least one path in order to find a configuration file.
("dbConfig") // Set the configuration file name (without suffix)("/workspace/appName/") // The first search path("/workspace/appName1") // You can call multiple times to add paths(".") // For example, add the current directoryerr := () // Search the path and read the configuration dataif err != nil { panic(("Fatal error config file: %s \n", err)) }
Monitor configuration files and reread configuration data
Viper supports allowing your application to read configuration files at runtime.
You only need to call the WatchConfig function of the viper instance, and you can also specify a callback function to get notifications of changes.
() (func(e ) { ("Config file changed:", ) })
Read configuration from
Viper predefined many configuration sources, such as files, environment variables, command line parameters, and remote K/V storage systems. You can also implement your own configuration source and provide it to viper.
Now there is the following yaml file:
userName: "xiaoming" address: "Guangzhou City XXX" sex: 1 company: name: "xxx" employeeId: 1000 department: - "Technology Department"
The code for reading the file is as follows:
package main import ( "fmt" "/spf13/viper" ) type UserInfo struct { UserName string Address string Sex byte Company Company } type Company struct { Name string EmployeeId int Department []interface{} } func main() { //Read yaml file v := () //Set the read configuration file name ("userInfo") //%GOPATH in windows environment, $GOPATH in linux environment ("/Users/yangyue/workspace/go/src/webDemo/") //Set configuration file type ("yaml") if err := ();err != nil { ("err:%s\n",err) } ("userName:%s sex:%s :%s \n", ("userName"), ("sex"), ("")) //It can also be deserialized directly into Struct var userInfo UserInfo if err := (&userInfo) ; err != nil{ ("err:%s",err) } (userInfo) }
The above code uses two ways to obtain configuration files: the first is to directly parse it as a key and value; the second is to deserialize it to Struct manually.
Read from command line parameters
package main import ( "fmt" "/spf13/pflag" "/spf13/viper" ) func main() { ("ip", "127.0.0.1", "Server running address") pflag.Int64("port", 8080, "Server running port") () () ("ip :%s , port:%s", ("ip"), ("port")) }
The command line executes the above program:
# go run --ip=192.168.7.3 --port=3306
You can see that the output is our customized parameters.
Read environment variable parameters
Generally, use environment variablesos
Package, for example:
getenv := ("JAVA_HOME") (getenv)
Viper also provides a way:
// means that the matching environment variable is preloaded first() //Read the environment variables that have been loaded into the defaultif env := ("JAVA_HOME"); env == nil { println("error!") } else { ("%#v\n", env) }
By obtaining environment variables, can we think of multi-environment parameter configuration? For online environments, the development environment loads parameters in different ymls separately.
func initConfig() (err error) { env := ("GO_ENV") (env) ("./configs") ("yml") err = () return }
Because whether it is an online environment or a test environment, there must be some parameters that are public and unchanged, so can this part of the parameters be extracted as a separate configuration file? So this configuration file can be divided into two parts:
"/gobuffalo/packr" func initConfig() (err error) { box := ("./configs") configType := "yml" defaultConfig, _ := ("") v := () (configType) err = ((defaultConfig)) if err != nil { return } configs := () // Write all configurations in default to the default configuration for k, v := range configs { (k, v) } env := ("GO_ENV") // Read the corresponding configuration information according to the configured env if env != "" { envConfig, _ := (env + ".yml") (configType) err = ((envConfig)) if err != nil { return } } return }
First read the parameters in it and write them to the default. Then read the parameters in different environments according to the environment variables.
The package is used here. The function of the package is to package static resources into the application.
The above is the detailed content of the tutorial on using Viper, a one-stop configuration management tool. For more information about Go Viper, please follow my other related articles!