viperyesgo
The library used in the project to read configuration files, supports readingyaml
、toml
、json
、hcl
、env
Configuration files in other formats
Read environment variables
viper
Can read the terminal's environment variables
If you're usingzsh
exist~/.zshrc
Set in, ifbash
exist~/.bashrc
Settings in
When writing environment variables, there cannot be spaces on both sides of the equal sign, otherwise an error will be reported.
export APP_DEBUG=true
After writing it, remembersource
Once, or restart the terminal
source ~/.zshrc
useRead all environment variables to
viper
middle
Then it can be used("APP_DEBUG")
Get environment variables
func GetEnvInfo(env string) bool { () return (env) } app_debug := GetEnvInfo("APP_DEBUG") (app_debug) // true
Read local configuration files
Create a new oneThe file, the content is as follows:
host: "127.0.0.1" port: 50051
Then useviper
Read,setConfigFile
The path to be filled in is relative toThe path
useTo read the configuration file
("./") if err := (); err != nil { panic(err) } (("host")) // "127.0.0.1"
useTo set the file name,
To set the file type, you can read configuration files more flexibly
-
Set file name without suffix
-
Set file type
-
Set file path
("config-debug") ("yaml") ("./") if err := (); err != nil { panic(err) } (("host")) // "127.0.0.1"
Map configurations in configuration files into structures
Each timeTo obtain the configuration in the configuration file, you will write a lot of duplicate code, and you can map the configuration in the configuration file to the structure.
Create a new structure. The field name of the structure must be consistent with the field name in the configuration file.mapstructure
Tags to map
type Server struct { Host string `mapstructure:"host"` Port int `mapstructure:"port"` }
useMap configurations in configuration files into structures
var server Server ("config-debug") ("yaml") ("./") if err := (); err != nil { panic(err) } if err := (&server); err != nil { panic(err) } () // "127.0.0.1"
Listen to changes in configuration information
If the configuration file changes,viper
Supports monitoring of configuration file changes at runtime
useTo listen for changes in configuration files, use
To listen for changes in configuration files
onConfigChange
The passed parameter is a function, and the parameter of the function is, reread the configuration file in the function, and then map the configuration in the configuration file to the structure
(func(e ) { _ = () _ = (&server) }) ()
This is the end of this article about using the Golang tool library viper. For more related Golang viper content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!