viper基本使用
1. 获取viper
go get github.com/spf13/viper
2. Demo
package main
import (
"github.com/spf13/viper"
"go.uber.org/zap"
)
func main() {
logger, _ := zap.NewProduction()
sugaredLogger := logger.Sugar()
err := InitViper()
if err != nil {
sugaredLogger.Panicf("err = %s", err.Error())
}
sugaredLogger.Infof("read configfile success!")
}
func InitViper() error {
viper.SetConfigName("config")
viper.SetConfigType("yaml")
viper.AddConfigPath("./viper/demo/")
return viper.ReadInConfig()
}
3. 设置默认值
viper.SetDefault("Hello", "World")
viper.SetDefault("kafka", map[string]interface{}{
"host": "127.0.0.1",
"port": 12345,
"topic": "viper",
})
4. 监控并重新读取配置文件
viper.WatchConfig()
viper.OnConfigChange(func(in fsnotify.Event) {
sugaredLogger.Infof("config file is changed %s", in.Name)
})
5. 读取环境变量
6. 从命令行读取参数
package main
import (
"flag"
"fmt"
"github.com/spf13/pflag"
"github.com/spf13/viper"
)
func main() {
flag.Int("n", 1, "please input n")
pflag.CommandLine.AddGoFlagSet(flag.CommandLine)
pflag.Parse()
viper.BindPFlags(pflag.CommandLine)
value := viper.GetInt("n")
fmt.Println(value)
}
7. 从远程配置仓库读取
etcd
func ReadByEtcd() {
viper.AddRemoteProvider("etcd", "http://127.0.0.1:4001", "/config/hugo.json")
viper.SetConfigType("json")
viper.ReadRemoteConfig()
}
consul
func ReadByConsul() {
viper.AddRemoteProvider("consul", "127.0.0.1:8500", "MY_CONSUL_KEY")
viper.SetConfigType("json")
viper.ReadRemoteConfig()
}
8. 从viper获取值
Get(key string) : interface{}
GetBool(key string) : bool
GetFloat64(key string) : float64
GetInt(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) : time.Time
GetDuration(key string) : time.Duration
IsSet(key string) : bool
AllSettings() : map[string]interface{}
8.1 访问嵌套数据
json
{
"host": {
"address": "localhost",
"port": 5799
},
"datastore": {
"metric": {
"host": "127.0.0.1",
"port": 3099
},
"warehouse": {
"host": "198.0.0.1",
"port": 2112
}
}
}
viper.GetString("datastore.metric.host")
yaml
database:
host: 127.0.0.1
username: root
dbname: test
password: root
viper.Get("database.host")
yaml多层嵌套
app:
name: "testapp"
mysql:
username: root
password: root
port: 3306
redis:
port: 6379
password: root
client:
name: "client"
port: 1234
func TestYaml2(t *testing.T) {
path, err := os.Getwd()
if err != nil {
fmt.Println(err)
}
config := viper.New()
config.SetConfigName("config")
config.SetConfigType("yaml")
config.AddConfigPath(path)
err = config.ReadInConfig()
if err != nil {
fmt.Println(err)
return
}
fmt.Println(config.Get("app.name"))
s := new(Server)
err = config.Unmarshal(s)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(s)
fmt.Println(s.Redis.Port)
}