搜索
首页后端开发Golang分享Golang中一个好用的viper配置模块

前言

       viper 支持Yaml、Json、 TOML、HCL 等格式,读取非常的方便。

安装

       go get github.com/spf13/viper

       如果提示找不到golang.org/x/text/这个库,是因为golang.org/x/text/这个库在GitHub上托管的路径不一致。

       解决办法:

       可以从https://github.com/golang/text下载源码下来,然后到$GOPATH/src下面创建golang.org/x/文件夹(已存在的忽略),把压缩包的文件解压到golang.org/x/文件夹之下。

       然后执行  go install -x  golang.org/x/text  即可解决:

正文

      初始结构目录如下:

       

       准备测试使用的yaml文件,注意yaml的格式十分严格,主要是每个冒号后面必须要有空格,数组前要加“-”号表示连续(注意减号后面也有空格),内容如下:

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

       读取yaml文件: 

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

	
}

    也可以直接反序列化为Struct,非常的方便:

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也提供了读取Command Line参数的功能:

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)

	*/

}

       很多时候,我们服务器启动之后,如果临时想修改某些配置参数,需要重启服务器才能生效,但是viper提供了监听函数,可以免重启修改配置参数,非常的实用:

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

完结

    viper还有许多好用的功能,此文章只是举例说明了很小的部分,欢迎留言,多提提意见,感谢大家。 

更多golang相关技术文章,请访问golang教程栏目!

 

以上是分享Golang中一个好用的viper配置模块的详细内容。更多信息请关注PHP中文网其他相关文章!

声明
本文转载于:csdn。如有侵权,请联系admin@php.cn删除
在GO中使用init进行包装初始化在GO中使用init进行包装初始化Apr 24, 2025 pm 06:25 PM

在Go中,init函数用于包初始化。1)init函数在包初始化时自动调用,适用于初始化全局变量、设置连接和加载配置文件。2)可以有多个init函数,按文件顺序执行。3)使用时需考虑执行顺序、测试难度和性能影响。4)建议减少副作用、使用依赖注入和延迟初始化以优化init函数的使用。

GO的选择语句:多路复用并发操作GO的选择语句:多路复用并发操作Apr 24, 2025 pm 05:21 PM

go'SselectStatementTreamLinesConcurrentProgrambyMultiplexingOperations.1)itallowSwaitingOnMultipleChannEloperations,执行thefirstreadyone.2)theDefirstreadyone.2)thedefefcasepreventlocksbysbysbysbysbysbythoplocktrograpraproxrograpraprocrecrecectefnoopeready.3)

GO中的高级并发技术:上下文和候补组GO中的高级并发技术:上下文和候补组Apr 24, 2025 pm 05:09 PM

contextancandwaitgroupsarecrucialingoformanaginggoroutineseflect.1)context contextsallowsAllowsAllowsAllowsAllowsAllingCancellationAndDeadLinesAcrossapibiboundaries,确保GoroutinesCanbestoppedGrace.2)WaitGroupsSynChronizeGoroutines,确保Allimizegoroutines,确保AllizeNizeGoROutines,确保AllimizeGoroutines

使用微服务体系结构的好处使用微服务体系结构的好处Apr 24, 2025 pm 04:29 PM

goisbeneformervicesduetoitssimplicity,效率,androbustConcurrencySupport.1)go'sdesignemphasemphasizessimplicity and效率,Idealformicroservices.2))其ConcconcurnCurnInesSandChannelsOdinesSallessallessallessAlloSalosalOsalOsalOsalOndlingConconcConccompi.3)

Golang vs. Python:利弊Golang vs. Python:利弊Apr 21, 2025 am 12:17 AM

Golangisidealforbuildingscalablesystemsduetoitsefficiencyandconcurrency,whilePythonexcelsinquickscriptinganddataanalysisduetoitssimplicityandvastecosystem.Golang'sdesignencouragesclean,readablecodeanditsgoroutinesenableefficientconcurrentoperations,t

Golang和C:并发与原始速度Golang和C:并发与原始速度Apr 21, 2025 am 12:16 AM

Golang在并发性上优于C ,而C 在原始速度上优于Golang。1)Golang通过goroutine和channel实现高效并发,适合处理大量并发任务。2)C 通过编译器优化和标准库,提供接近硬件的高性能,适合需要极致优化的应用。

为什么要使用Golang?解释的好处和优势为什么要使用Golang?解释的好处和优势Apr 21, 2025 am 12:15 AM

选择Golang的原因包括:1)高并发性能,2)静态类型系统,3)垃圾回收机制,4)丰富的标准库和生态系统,这些特性使其成为开发高效、可靠软件的理想选择。

Golang vs.C:性能和速度比较Golang vs.C:性能和速度比较Apr 21, 2025 am 12:13 AM

Golang适合快速开发和并发场景,C 适用于需要极致性能和低级控制的场景。1)Golang通过垃圾回收和并发机制提升性能,适合高并发Web服务开发。2)C 通过手动内存管理和编译器优化达到极致性能,适用于嵌入式系统开发。

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热工具

SecLists

SecLists

SecLists是最终安全测试人员的伙伴。它是一个包含各种类型列表的集合,这些列表在安全评估过程中经常使用,都在一个地方。SecLists通过方便地提供安全测试人员可能需要的所有列表,帮助提高安全测试的效率和生产力。列表类型包括用户名、密码、URL、模糊测试有效载荷、敏感数据模式、Web shell等等。测试人员只需将此存储库拉到新的测试机上,他就可以访问到所需的每种类型的列表。

PhpStorm Mac 版本

PhpStorm Mac 版本

最新(2018.2.1 )专业的PHP集成开发工具

WebStorm Mac版

WebStorm Mac版

好用的JavaScript开发工具

记事本++7.3.1

记事本++7.3.1

好用且免费的代码编辑器

DVWA

DVWA

Damn Vulnerable Web App (DVWA) 是一个PHP/MySQL的Web应用程序,非常容易受到攻击。它的主要目标是成为安全专业人员在合法环境中测试自己的技能和工具的辅助工具,帮助Web开发人员更好地理解保护Web应用程序的过程,并帮助教师/学生在课堂环境中教授/学习Web应用程序安全。DVWA的目标是通过简单直接的界面练习一些最常见的Web漏洞,难度各不相同。请注意,该软件中