Golang - viper读取配置文件【解析配置,热更新】
一、介绍
github.com/spf13/viper
Viper是一个方便Go语言应用程序处理配置信息的库,可以处理多种格式的配置。其支持的特性有:
- 设置默认值
- 从JSON、TOML、YAML、HCL和Java properties文件中读取配置数据
- 可以监视配置文件的变动、重新读取配置文件【热更新配置文件】
- 从环境变量中读取配置数据
- 从远端配置系统中读取数据,并监视它们(比如etcd、Consul)
- 从命令参数中读物配置
- 从buffer中读取
- 调用函数设置配置信息
监视配置文件,重新读取配置数据
1 2 3 4 5 6 7 8 9 10 11 12 | package main import ( "fmt" "github.com/fsnotify/fsnotify" "github.com/spf13/viper" ) viper:=viper.New() viper.WatchConfig() viper.OnConfigChange( func (e fsnotify.Event) { fmt.Println( "Config file changed:" , e.Name) }) |
二、使用(读取json文件)
#文件路径 ./config/demo.json { "appId": "123456789", "secret": "maple123456", "host": { "address": "localhost", "port": 5799 } }
package main import (
"fmt"
"github.com/spf13/viper
) //定义config结构体 type Config struct { AppId string Secret string Host Host } //json中的嵌套对应结构体的嵌套 type Host struct { Address string Port int } func main() { config := viper.New() config.AddConfigPath("./config") //设置读取的文件路径
config.SetConfigName("demo") //设置读取的文件名
config.SetConfigType("json") //设置文件的类型 //配置读取 if err := config.ReadInConfig(); err != nil { panic(err) } fmt.Println(config.GetString("appId")) fmt.Println(config.GetString("secret")) fmt.Println(config.GetString("host.address")) fmt.Println(config.GetString("host.port")) //直接反序列化为Struct var configjson Config if err :=config.Unmarshal(&configjson);err !=nil{ fmt.Println(err) } fmt.Println(configjson.Host) fmt.Println(configjson.AppId) fmt.Println(configjson.Secret) }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· DeepSeek 开源周回顾「GitHub 热点速览」
2022-05-18 数据结构 - Linux中的僵尸进程和孤儿进程