参考链接:https://studygolang.com/articles/26215?fr=sidebar
viper 是一个配置解决方案,拥有丰富的特性:
- 支持 JSON/TOML/YAML/HCL/envfile/Java properties 等多种格式的配置文件;
- 可以设置监听配置文件的修改,修改时自动加载新的配置;
- 从环境变量、命令行选项和
io.Reader
中读取配置; - 从远程配置系统中读取和监听修改,如 etcd/Consul;
- 代码逻辑中显示设置键值。
demo:
package main import ( "fmt" "log" "github.com/spf13/viper" ) func main() { viper.SetConfigName("config") viper.SetConfigType("toml") viper.AddConfigPath(".") viper.SetDefault("redis.port", 6381) err := viper.ReadInConfig() if err != nil { log.Fatal("read config failed: %v", err) } fmt.Println(viper.Get("app_name")) fmt.Println(viper.Get("log_level")) fmt.Println("mysql ip: ", viper.Get("mysql.ip")) fmt.Println("mysql port: ", viper.Get("mysql.port")) fmt.Println("mysql user: ", viper.Get("mysql.user")) fmt.Println("mysql password: ", viper.Get("mysql.password")) fmt.Println("mysql database: ", viper.Get("mysql.database")) fmt.Println("redis ip: ", viper.Get("redis.ip")) fmt.Println("redis port: ", viper.Get("redis.port")) }
配置文件:(toml格式)
app_name = "awesome web" # possible values: DEBUG, INFO, WARNING, ERROR, FATAL log_level = "DEBUG" [mysql] ip = "127.0.0.1" port = 3306 user = "dj" password = 123456 database = "awesome" [redis] ip = "127.0.0.1" port = 7381