Configuration management of Golang project -- Viper easy start configuration
What is Viper?
From: https://github.com/spf13/viper
Viper is a complete configuration solution for Go applications including 12-Factor apps.
(VIPER is implementation compliance) 12-Factor Complete configuration solution for GO applications)
It supports:
-
Support configuration files in JSON/TOML/YAML/HCL/envfile/Java properties and other formats
-
Real time monitoring and reload configuration file (optional)
-
Read the configuration from environment variables, command line tags and cache;
-
Read and listen for modifications from the remote configuration system, such as etcd / consult;
-
Set key values explicitly.
Why Viper?
When building a modern application, you don't want to worry about configuration file formats; you want to focus on building awesome software. Viper is here to help with that.
(when building modern applications, you don't want to pay more attention to the format of configuration files. You want to focus on building better software. Viper can help you.)
Install
go get github.com/spf13/viper
Example
initialization:
package settings import ( "fmt" "github.com/fsnotify/fsnotify" "github.com/spf13/viper" ) //Initialize a viper configuration func Init() (err error) { //Specify the path to the configuration file viper.SetConfigFile("conf/config.yaml") // Read configuration information err = viper.ReadInConfig() if err != nil { // Failed to read configuration information fmt.Printf("viper.ReadInConfig()failed,err:%v\n", err) return } //Listening modification viper.WatchConfig() //Add a callback function for configuration modification viper.OnConfigChange(func(in fsnotify.Event) { fmt.Println("The configuration file has been modified...") }) return }
Sample profile (yaml):
mysql: host: "127.0.0.1" port: 3306 user: "root" password: "123456" dbname: "web_app" max_open_conns: 200 max_idle_conns: 50 redis: host: "127.0.0.1" port: 6379 db: 0 password: "" pool_size: 100
Fetch configuration:
package mysql //Omit package func Init() (err error) { dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=True", viper.GetString("mysql.user"), viper.GetString("mysql.password"), viper.GetString("mysql.host"), viper.GetInt("mysql.port"), viper.GetString("mysql.dbname"), ) db, err = sqlx.Connect("mysql", dsn) db.SetMaxOpenConns(viper.GetInt("mysql.max_open_conns")) db.SetMaxIdleConns(viper.GetInt("mysql.max_idle_conns")) return } // @version 1.0
Display declaration configuration in the program:
If a key passes viper If set is set to a value, this value has the highest priority. For example:
viper.Set("redis.port", 9000)
At this time, the redis interface is not 6379 set in the configuration file, but 9000 configured later
Command line options:
func init() { pflag.Int("redis.port", 9001, "Redis port to connect") // Bind command line viper.BindPFlags(pflag.CommandLine) }
Parameters passed in when the code runs: $/ main.exe --redis.port 9001
At this time, the redis port configured by the program is 9001.
If we do not pass in parameters, execute $/ main.exe
At this time, the redis port configured by the program is 6379 in the configuration file (viper. Set ("redis. Port", 9000) when the declared configuration is not displayed in the program).
Environment variables:
func init() { // Binding environment variables viper.AutomaticEnv() }
If the configuration is not obtained from the previous method, the environment variable will be bound.
You can also specify the environment variable corresponding to the binding:
func init() { // Binding environment variables viper.BindEnv("redis.port") viper.BindEnv("go.path", "GOPATH") }
BindEnv() if only one parameter is passed in, this parameter represents both the key name and the environment variable name. If two parameters are passed in, the first parameter represents the key name and the second parameter represents the environment variable name.
You can also use viper Setenvprefix() sets the prefix of the environment variable. After setting, the previous method will add the variable to the incoming value and then find the environment variable.
- The default value can call viper SetDefault settings.
Summary priority:
Call the > command line option Set explicitly, and the passed in > environment variables > configuration file > default value;
summary
initialization:
- Set the configuration file path viper SetConfigFile()
- Read configuration viper ReadInConfig()
- Listen and modify viper WatchConfig()
- Set the modified callback viper OnConfigChange(func())
Call:
Take configuration viper Get*()
Set priority:
Declare > environment variable > configuration file > default value passed in by calling the > command line option explicitly Set by Set;
My personal station: mrxuexi.com