search
HomeBackend DevelopmentGolangShare a useful viper configuration module in 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

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. If there is any infringement, please contact admin@php.cn delete
Building Scalable Systems with the Go Programming LanguageBuilding Scalable Systems with the Go Programming LanguageApr 25, 2025 am 12:19 AM

Goisidealforbuildingscalablesystemsduetoitssimplicity,efficiency,andbuilt-inconcurrencysupport.1)Go'scleansyntaxandminimalisticdesignenhanceproductivityandreduceerrors.2)Itsgoroutinesandchannelsenableefficientconcurrentprogramming,distributingworkloa

Best Practices for Using init Functions Effectively in GoBest Practices for Using init Functions Effectively in GoApr 25, 2025 am 12:18 AM

InitfunctionsinGorunautomaticallybeforemain()andareusefulforsettingupenvironmentsandinitializingvariables.Usethemforsimpletasks,avoidsideeffects,andbecautiouswithtestingandloggingtomaintaincodeclarityandtestability.

The Execution Order of init Functions in Go PackagesThe Execution Order of init Functions in Go PackagesApr 25, 2025 am 12:14 AM

Goinitializespackagesintheordertheyareimported,thenexecutesinitfunctionswithinapackageintheirdefinitionorder,andfilenamesdeterminetheorderacrossmultiplefiles.Thisprocesscanbeinfluencedbydependenciesbetweenpackages,whichmayleadtocomplexinitializations

Defining and Using Custom Interfaces in GoDefining and Using Custom Interfaces in GoApr 25, 2025 am 12:09 AM

CustominterfacesinGoarecrucialforwritingflexible,maintainable,andtestablecode.Theyenabledeveloperstofocusonbehavioroverimplementation,enhancingmodularityandrobustness.Bydefiningmethodsignaturesthattypesmustimplement,interfacesallowforcodereusabilitya

Using Interfaces for Mocking and Testing in GoUsing Interfaces for Mocking and Testing in GoApr 25, 2025 am 12:07 AM

The reason for using interfaces for simulation and testing is that the interface allows the definition of contracts without specifying implementations, making the tests more isolated and easy to maintain. 1) Implicit implementation of the interface makes it simple to create mock objects, which can replace real implementations in testing. 2) Using interfaces can easily replace the real implementation of the service in unit tests, reducing test complexity and time. 3) The flexibility provided by the interface allows for changes in simulated behavior for different test cases. 4) Interfaces help design testable code from the beginning, improving the modularity and maintainability of the code.

Using init for Package Initialization in GoUsing init for Package Initialization in GoApr 24, 2025 pm 06:25 PM

In Go, the init function is used for package initialization. 1) The init function is automatically called when package initialization, and is suitable for initializing global variables, setting connections and loading configuration files. 2) There can be multiple init functions that can be executed in file order. 3) When using it, the execution order, test difficulty and performance impact should be considered. 4) It is recommended to reduce side effects, use dependency injection and delay initialization to optimize the use of init functions.

Go's Select Statement: Multiplexing Concurrent OperationsGo's Select Statement: Multiplexing Concurrent OperationsApr 24, 2025 pm 05:21 PM

Go'sselectstatementstreamlinesconcurrentprogrammingbymultiplexingoperations.1)Itallowswaitingonmultiplechanneloperations,executingthefirstreadyone.2)Thedefaultcasepreventsdeadlocksbyallowingtheprogramtoproceedifnooperationisready.3)Itcanbeusedforsend

Advanced Concurrency Techniques in Go: Context and WaitGroupsAdvanced Concurrency Techniques in Go: Context and WaitGroupsApr 24, 2025 pm 05:09 PM

ContextandWaitGroupsarecrucialinGoformanaginggoroutineseffectively.1)ContextallowssignalingcancellationanddeadlinesacrossAPIboundaries,ensuringgoroutinescanbestoppedgracefully.2)WaitGroupssynchronizegoroutines,ensuringallcompletebeforeproceeding,prev

See all articles

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

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor