Golang配置库viper配置

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 支持的文件格式有
	json,toml,yaml,yml,properties,props,prop,env,dotenv
	*/
	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") // (returns "127.0.0.1")
yaml
database:
  host: 127.0.0.1
  username: root
  dbname: test
  password: root
viper.Get("database.host") // "127.0.0.1"
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)
    //将viper解析到结构体
	err = config.Unmarshal(s)
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println(s)
	fmt.Println(s.Redis.Port)
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值