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: falseRead 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!
Golang vs. Python: Concurrency and MultithreadingApr 17, 2025 am 12:20 AMGolang is more suitable for high concurrency tasks, while Python has more advantages in flexibility. 1.Golang efficiently handles concurrency through goroutine and channel. 2. Python relies on threading and asyncio, which is affected by GIL, but provides multiple concurrency methods. The choice should be based on specific needs.
Golang and C : The Trade-offs in PerformanceApr 17, 2025 am 12:18 AMThe performance differences between Golang and C are mainly reflected in memory management, compilation optimization and runtime efficiency. 1) Golang's garbage collection mechanism is convenient but may affect performance, 2) C's manual memory management and compiler optimization are more efficient in recursive computing.
Golang vs. Python: Applications and Use CasesApr 17, 2025 am 12:17 AMChooseGolangforhighperformanceandconcurrency,idealforbackendservicesandnetworkprogramming;selectPythonforrapiddevelopment,datascience,andmachinelearningduetoitsversatilityandextensivelibraries.
Golang vs. Python: Key Differences and SimilaritiesApr 17, 2025 am 12:15 AMGolang and Python each have their own advantages: Golang is suitable for high performance and concurrent programming, while Python is suitable for data science and web development. Golang is known for its concurrency model and efficient performance, while Python is known for its concise syntax and rich library ecosystem.
Golang vs. Python: Ease of Use and Learning CurveApr 17, 2025 am 12:12 AMIn what aspects are Golang and Python easier to use and have a smoother learning curve? Golang is more suitable for high concurrency and high performance needs, and the learning curve is relatively gentle for developers with C language background. Python is more suitable for data science and rapid prototyping, and the learning curve is very smooth for beginners.
The Performance Race: Golang vs. CApr 16, 2025 am 12:07 AMGolang and C each have their own advantages in performance competitions: 1) Golang is suitable for high concurrency and rapid development, and 2) C provides higher performance and fine-grained control. The selection should be based on project requirements and team technology stack.
Golang vs. C : Code Examples and Performance AnalysisApr 15, 2025 am 12:03 AMGolang is suitable for rapid development and concurrent programming, while C is more suitable for projects that require extreme performance and underlying control. 1) Golang's concurrency model simplifies concurrency programming through goroutine and channel. 2) C's template programming provides generic code and performance optimization. 3) Golang's garbage collection is convenient but may affect performance. C's memory management is complex but the control is fine.
Golang's Impact: Speed, Efficiency, and SimplicityApr 14, 2025 am 12:11 AMGoimpactsdevelopmentpositivelythroughspeed,efficiency,andsimplicity.1)Speed:Gocompilesquicklyandrunsefficiently,idealforlargeprojects.2)Efficiency:Itscomprehensivestandardlibraryreducesexternaldependencies,enhancingdevelopmentefficiency.3)Simplicity:


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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Zend Studio 13.0.1
Powerful PHP integrated development environment

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

WebStorm Mac version
Useful JavaScript development tools







