栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Go语言

分享Golang中一个好用的viper配置模块

Go语言 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

分享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: 518000CompanyInfomation:  Name: "Sunny"  MarketCapitalization: 50000000  EmployeeNum: 200  Department:    - "Finance"    - "Design"    - "Program"    - "Sales"  IsOpen: false

读取yaml文件:

package mainimport ("github.com/spf13/viper""fmt")func main() {//读取yaml文件v := viper.New()//设置读取的配置文件v.SetConfigName("linux_config")//添加读取的配置文件路径v.AddConfigPath("./config/")//windows环境下为%GOPATH,linux环境下为$GOPATHv.AddConfigPath("$GOPATH/src/")//设置配置文件类型v.SetConfigType("yaml")if err := v.ReadInConfig();err != nil {fmt.Printf("err:%sn",err)}fmt.Printf(`TimeStamp:%sCompanyInfomation.Name:%sCompanyInfomation.Department:%s `,v.Get("TimeStamp"),v.Get("CompanyInfomation.Name"),v.Get("CompanyInfomation.Department"),)}

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

package mainimport ("github.com/spf13/viper""fmt")func main() {//读取yaml文件v := viper.New()//设置读取的配置文件v.SetConfigName("linux_config")//添加读取的配置文件路径v.AddConfigPath("./config/")//windows环境下为%GOPATH,linux环境下为$GOPATHv.AddConfigPath("$GOPATH/src/")//设置配置文件类型v.SetConfigType("yaml")if err := v.ReadInConfig();err != nil {fmt.Printf("err:%sn",err)}fmt.Printf(`TimeStamp:%sCompanyInfomation.Name:%sCompanyInfomation.Department:%s `,v.Get("TimeStamp"),v.Get("CompanyInfomation.Name"),v.Get("CompanyInfomation.Department"),)//反序列化parseYaml(v)}type CompanyInfomation struct{Name stringMarketCapitalization int64EmployeeNum int64Department []interface{}IsOpen bool}type YamlSetting struct{TimeStamp stringAddress stringPostcode int64CompanyInfomation CompanyInfomation}func parseYaml(v *viper.Viper){var yamlObj YamlSetting;if err := v.Unmarshal(&yamlObj) ; err != nil{fmt.Printf("err:%s",err)}fmt.Println(yamlObj)}

viper也提供了读取Command Line参数的功能:

package mainimport ("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"))}

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

package mainimport ("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环境下为$GOPATHv.AddConfigPath("$GOPATH/src/")//设置配置文件类型v.SetConfigType("yaml")if err := v.ReadInConfig(); err != nil {fmt.Printf("err:%sn", 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()}

完结

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

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

以上就是分享Golang中一个好用的viper配置模块的详细内容,更多请关注考高分网其它相关文章!

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/793762.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号