Go之viper配置

这个模块功能强大,读取配置,命令行,监听配置改变。

堪称多面手,在k8s,docker中,都多有应用。

这套应用,主要包括cobra,pflag,viper三件套。

了解得差不多啦。。。:)

package main

import (
	"context"
	"fmt"

	"github.com/fsnotify/fsnotify"

	"github.com/spf13/pflag"
	"github.com/spf13/viper"
)

type CompanyInfomation struct {
	Name                 string
	MarketCapitalization int64
	EmployeeNum          int64
	Department           []interface{}
	IsOpen               bool
}

type YamlSetting struct {
	TimeStamp         string
	Address           string
	Postcode          int64
	CompanyInfomation CompanyInfomation
}

func parseYaml(v *viper.Viper) {
	var yamlObj YamlSetting
	if err := v.Unmarshal(&yamlObj); err != nil {
		fmt.Printf("err:%s", err)
	}
	fmt.Println(yamlObj)
}

func main() {

	pflag.String("hostAddress", "127.0.0.1", "Server running address")
	pflag.Int64("port", 8080, "Server running port")
	pflag.Parse()
	viper.BindPFlags(pflag.CommandLine)

	fmt.Printf("hostAddress: %s, port: %s",
		viper.GetString("hostAddress"),
		viper.GetString("port"))
	// 读取yaml文件
	v := viper.New()
	//设置读取的配置文件
	v.SetConfigName("linux_config")
	//添加读取的配置文件路径
	v.AddConfigPath("./config/")
	//windows环境下%GOPATH,linux环境下为$GOPATH
	v.AddConfigPath("%GOPATH/src/")
	//设置文件类型
	v.SetConfigType("yaml")

	if err := v.ReadInConfig(); err != nil {
		fmt.Printf("err: %s\n", err)
	}

	fmt.Printf(
		`
		TimeStamp:%s
		CompanyInfomation.Name:%s
		CompanyInfomation.Department:%s
		`,
		v.Get("Timestamp"),
		v.Get("CompanyInfomation.Name"),
		v.Get("CompanyInfomation.Department"),
	)

	parseYaml(v)

	//创建一个信道等待关闭(模拟服务器环境)
	ctx, _ := context.WithCancel(context.Background())
	//cancel可以关闭信道
	//ctx, cancel := context.WithCancel(context.Background())
	//设置监听回调函数
	v.OnConfigChange(func(e fsnotify.Event) {
		fmt.Printf("config is change: %s \n", e.String())
	})
	//开始监听
	v.WatchConfig()
	//信道不会主动关闭,可以主动调用cancel关闭
	<-ctx.Done()

}

  

TimeStamp: "2019-03-10 10:09:23"
Address: "ShangHai"
Postcode: 518000
CompanyInfomation:
  Name: "Sunny"
  MarketCapitalization: 50000000
  EmployeeNum: 200
  Department:
    - "Finance"
    - "Design"
    - "Program"
    - "Sales"
  IsOpen: false

Go之viper配置

上一篇:Codeforces 798D Mike and distribution


下一篇:permutation求全排列