Share 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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

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 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.

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.

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.

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].

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,...

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.

Which libraries in Go are developed by large companies or well-known open source projects? When programming in Go, developers often encounter some common needs, ...
