Home >Backend Development >Golang >Share a useful viper configuration module in Golang

Share a useful viper configuration module in Golang

藏色散人
藏色散人forward
2021-07-09 14:58:192757browse

Preface

viper supports Yaml, Json, TOML, HCL and other formats, which is very convenient to read.

Installation

go get github.com/spf13/viper

If the prompt cannot find the golang.org/x/text/ library, it is because the path of the golang.org/x/text/ library hosted on GitHub is inconsistent.

Solution:

You can download the source code from https://github.com/golang/text, and then go to $GOPATH/src Next, create the golang.org/x/ folder (ignore existing ones), and extract the compressed package files to the golang.org/x/ folder.

Then execute go install -x golang.org/x/text to solve:

Text

Initial structure The directory is as follows:

Prepare the yaml file for testing. Note that the format of yaml is very strict. The main thing is that there must be a space after each colon, and "-" must be added before the array. sign means continuous (note that there is a space after the minus sign), the content is as follows:

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

Read the yaml file:

package main

import (
	"github.com/spf13/viper"
	"fmt"
)

func main() {
	//读取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"),
	)

	/*
	result:
	TimeStamp:2018-10-18 10:09:23
	CompanyInfomation.Name:Sunny
	CompanyInfomation.Department:[Finance Design Program Sales]
	*/

	
}

You can also directly deserialize it into a Struct, which is very convenient:

package main

import (
	"github.com/spf13/viper"
	"fmt"
)

func main() {
	//读取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"),
	)

	/*
	result:
	TimeStamp:2018-10-18 10:09:23
	CompanyInfomation.Name:Sunny
	CompanyInfomation.Department:[Finance Design Program Sales]
	*/

	//反序列化
	parseYaml(v)

}

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)
	/*
	result:
	{2018-10-18 10:09:23 Shenzhen 518000 {Sunny 50000000 200 [Finance Design Program Sales] false}}
	*/
}

viper also provides the function of reading Command Line parameters:

package main

import (
	"github.com/spf13/pflag"
	"github.com/spf13/viper"
	"fmt"
)

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"))
	/*
	example:
	go run main2.go --hostAddress=192.192.1.10 --port=9000
	help:
	Usage of /tmp/go-build183981952/b001/exe/main:
     --hostAddress string   Server running address (default "127.0.0.1")
     --port int             Server running port (default 8080)

	*/

}

Many times, after our server is started, if we temporarily want to modify some configuration parameters, we need to restart the server to take effect, but viper provides The listening function can modify the configuration parameters without restarting, which is very practical:

package main

import (
	"github.com/spf13/viper"
	"fmt"
	"golang.org/x/net/context"
	"github.com/fsnotify/fsnotify"
)

func main() {
	//读取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)
	}

	//创建一个信道等待关闭(模拟服务器环境)
	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())
		//cancel()
	})
	//开始监听
	v.WatchConfig()
	//信道不会主动关闭,可以主动调用cancel关闭
	<-ctx.Done()

	/*
	result:
	config is change :"/home/share/go/Viper/config/linux_config.yaml": CREATE 
	config is change :"/home/share/go/Viper/config/linux_config.yaml": CREATE
	*/
}

End

viper also has many useful functions. This article only illustrates many of them with examples. It’s a small part, please leave a message and provide more comments, thank you all.

For more golang related technical articles, please visit the golang tutorial column!

The above is the detailed content of Share a useful viper configuration module in Golang. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete