Table of Contents
Preface" >Preface
Installation" >Installation
Text" >Text
End" >End
Home Backend Development Golang Share a useful viper configuration module in Golang

Share a useful viper configuration module in Golang

Jul 09, 2021 pm 02:58 PM
golang

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
Copy after login

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]
	*/

	
}
Copy after login

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}}
	*/
}
Copy after login

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)

	*/

}
Copy after login

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
	*/
}
Copy after login

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 of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to safely read and write files using Golang? How to safely read and write files using Golang? Jun 06, 2024 pm 05:14 PM

Reading and writing files safely in Go is crucial. Guidelines include: Checking file permissions Closing files using defer Validating file paths Using context timeouts Following these guidelines ensures the security of your data and the robustness of your application.

How to configure connection pool for Golang database connection? How to configure connection pool for Golang database connection? Jun 06, 2024 am 11:21 AM

How to configure connection pooling for Go database connections? Use the DB type in the database/sql package to create a database connection; set MaxOpenConns to control the maximum number of concurrent connections; set MaxIdleConns to set the maximum number of idle connections; set ConnMaxLifetime to control the maximum life cycle of the connection.

How to save JSON data to database in Golang? How to save JSON data to database in Golang? Jun 06, 2024 am 11:24 AM

JSON data can be saved into a MySQL database by using the gjson library or the json.Unmarshal function. The gjson library provides convenience methods to parse JSON fields, and the json.Unmarshal function requires a target type pointer to unmarshal JSON data. Both methods require preparing SQL statements and performing insert operations to persist the data into the database.

Golang framework vs. Go framework: Comparison of internal architecture and external features Golang framework vs. Go framework: Comparison of internal architecture and external features Jun 06, 2024 pm 12:37 PM

The difference between the GoLang framework and the Go framework is reflected in the internal architecture and external features. The GoLang framework is based on the Go standard library and extends its functionality, while the Go framework consists of independent libraries to achieve specific purposes. The GoLang framework is more flexible and the Go framework is easier to use. The GoLang framework has a slight advantage in performance, and the Go framework is more scalable. Case: gin-gonic (Go framework) is used to build REST API, while Echo (GoLang framework) is used to build web applications.

Transforming from front-end to back-end development, is it more promising to learn Java or Golang? Transforming from front-end to back-end development, is it more promising to learn Java or Golang? Apr 02, 2025 am 09:12 AM

Backend learning path: The exploration journey from front-end to back-end As a back-end beginner who transforms from front-end development, you already have the foundation of nodejs,...

How to find the first substring matched by a Golang regular expression? How to find the first substring matched by a Golang regular expression? Jun 06, 2024 am 10:51 AM

The FindStringSubmatch function finds the first substring matched by a regular expression: the function returns a slice containing the matching substring, with the first element being the entire matched string and subsequent elements being individual substrings. Code example: regexp.FindStringSubmatch(text,pattern) returns a slice of matching substrings. Practical case: It can be used to match the domain name in the email address, for example: email:="user@example.com", pattern:=@([^\s]+)$ to get the domain name match[1].

Golang framework development practical tutorial: FAQs Golang framework development practical tutorial: FAQs Jun 06, 2024 am 11:02 AM

Go framework development FAQ: Framework selection: Depends on application requirements and developer preferences, such as Gin (API), Echo (extensible), Beego (ORM), Iris (performance). Installation and use: Use the gomod command to install, import the framework and use it. Database interaction: Use ORM libraries, such as gorm, to establish database connections and operations. Authentication and authorization: Use session management and authentication middleware such as gin-contrib/sessions. Practical case: Use the Gin framework to build a simple blog API that provides POST, GET and other functions.

How to use predefined time zone with Golang? How to use predefined time zone with Golang? Jun 06, 2024 pm 01:02 PM

Using predefined time zones in Go includes the following steps: Import the "time" package. Load a specific time zone through the LoadLocation function. Use the loaded time zone in operations such as creating Time objects, parsing time strings, and performing date and time conversions. Compare dates using different time zones to illustrate the application of the predefined time zone feature.

See all articles