Introduction to the
Viper is a framework for reading and writing configuration files. It supports JSON, YAML, INI, and other formats. You can also read the monitoring remote configuration file.
Viper: Indicates the address of the Github repository
The installation
go get github.com/spf13/viper
Copy the code
configuration
// You need to add a suffix to the full path and do not read other configurations after setting
viper.SetConfigFile("/user/xxx/xxx/config.yaml")
// Configuration file path
viper.AddConfigPath("conf")
// The name of the configuration file. No suffix is required
viper.SetConfigName("config")
// Type of the configuration file
viper.SetConfigType("yaml")
Copy the code
If the full path is set, you do not need to set the path, name, or type.
read
Read the entire file first with ReadInConfig()
If the key does not exist, a value of type 0 is returned.
// Start reading the configuration file and determine err
iferr := viper.ReadInConfig(); err ! =nil {
fmt.Println("Read error")}// Read the value according to the key, regardless of the value type
viper.Get("name")
/ / return a string
viper.GetString("name")
/ / returns a bool
viper.GetBool("isTest")
// Read the multi-level key and call it like a class
viper.GetString("people.child.work")
// Check whether the key exists
if viper.IsSet("school") {
viper.GetString("school")}Copy the code
Listening for Configuration Changes
Function: During hot update, the configuration file may be changed to facilitate reread.
In. name is the full path of the configuration file.
// Listen for configuration changes
viper.WatchConfig()
// Callback when configuration changes
viper.OnConfigChange(func(in fsnotify.Event) {
switch in.Op {
case fsnotify.Create:
fmt.Println("Listen to Create")
case fsnotify.Remove:
fmt.Println("Listen to Remove")
case fsnotify.Rename:
fmt.Println("Listen to Rename")
case fsnotify.Write:
fmt.Println("Listen to Write")
case fsnotify.Chmod:
fmt.Println("Listen to Chmod")}})Copy the code
write
/ / modify
viper.Set("host"."http://www.baidu.com")
// If the file already exists, it will not be written. Cannot be used with SetConfigFile
viper.SafeWriteConfig()
// Overwrite the original data whether the file exists or not
viper.WriteConfig()
Copy the code
Read system environment variables
Environment variables must be prefixed with an underscore “”. Such as APISERVER
// Read the system environment variables
viper.AutomaticEnv()
// Set the prefix of the environment variable to be read
viper.SetEnvPrefix("APISERVER")
// When no environment variable is matched, the corresponding character is replaced. Replaced by _
replacer := strings.NewReplacer("."."_")
viper.SetEnvKeyReplacer(replacer)
Copy the code
Read environment variables and configuration files simultaneously
If both exist, Viper will take the environment variable Settings as the standard.