Official website address:
GitHub - spf13/viper: Go configuration with fangs
Common operations:
Viper will follow the following priority. Each project has a higher priority than the following items:
- Show call
Set
Set value - Command line parameters (flag)
- Environment variables
- Configuration File
- key/value storage
- default value
Configuration File (In the current directory)
host: "0.0.0.0" mysql: host: "127.0.0.1" port: 3306 cache: cache1: max-items: 100 item-size: 64 cache2: max-items: 200 item-size: 80
Configuration
("", "localhost:6379") // ("./") // Configuration file path, this line has the same effect as the following two lines ("config") // Configuration file name ("yaml") // Configuration file type ("./") // Configuration file path err := () // Find and read configuration files if err != nil { panic(("fatal error config file: %w", err)) // Handle errors }
Get value from Viper
In Viper, there are several ways to get values based on the type of values. The following functions and methods exist:
- Get(key string) : interface{}
- GetBool(key string) : bool
- GetFloat64(key string) : float64
- GetInt(key string) : int
- GetIntSlice(key string) : []int
- GetString(key string) : string
- GetStringMap(key string) : map[string]interface{}
- GetStringMapString(key string) : map[string]string
- GetStringSlice(key string) : []string
- GetTime(key string) :
- GetDuration(key string) :
- IsSet(key string) : bool
- AllSettings() : map[string]interface{}
Delimited paths by passing in.
// Viper can access nested fields through incoming .delimited paths: mysqlHost := ("") // Access mysql's host field ("Mysql Host:", mysqlHost) mysqlPort := ("") // Access mysql port field ("Mysql Port:", mysqlPort)
Extract subtree
// Extract subtree appConfig := ("app") // Extract app subtree ("App Config:", ()) // Print all settings of the app subtree cache1 := ("cache1") // Extract the cache1 field of the app subtree cache2 := ("app.cache2") // Extract the cache2 field of the app subtree ("Cache1:", cache1) // Print the cache field of the app subtree ("Cache2:", ()) // PrintappSubtreecache2All settings of fields
Deserialization
// Deserialization var conf Config err = (&conf) // Deserialize to structure if err != nil { panic(("unable to decode into struct, %v", err)) // Handle errors } ("Config Struct:", conf) // Print the deserialized structure
This is all about this article about the go configuration management framework viper. For more related go configuration management content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!