[go-每日一库] golang viper实现动态配置更新
viper库下载:
go get -u github.com/spf13/viper
代码结构:
. +--- config | +--- config.go | +--- config.yaml +--- go.mod +--- go.sum +--- main.go
config.yaml
app: app1: timeout: 120 rpc: true compatible: true mysql: host: localhost port: 3306 user: root password: root database: test redis: host: localhost port: 6379 dbname: 0
config.go
package config import ( "fmt" "github.com/fsnotify/fsnotify" "github.com/spf13/viper" ) type Config struct { App App MySQL MySQL Redis Redis } type App struct { App1 App1 } type App1 struct { Timeout int Rpc bool Compatible bool } type MySQL struct { Host string User string Password string Port int Database string } type Redis struct { Host string Port int Dbname int } var AppConfig Config func init() { viperCfg := viper.New() viperCfg.SetConfigName("config") viperCfg.SetConfigType("yaml") viperCfg.AddConfigPath("D:\\demo1\\src\\demo\\demo06\\go-viper-http-watch\\config\\") viperCfg.ReadInConfig() err := viperCfg.Unmarshal(&AppConfig) if err != nil { fmt.Println(err) } viperCfg.WatchConfig() viperCfg.OnConfigChange(func(e fsnotify.Event) { fmt.Println("Config file changed:", e.Name) if err = viperCfg.Unmarshal(&AppConfig); err != nil { fmt.Println(err) } }) } func GetConfig() Config { return AppConfig }
main
package main import ( "github.com/gin-gonic/gin" . "go-viper-http-watch/config" "net/http" ) func main() { router := gin.Default() router.GET("/info", func(ctx *gin.Context) { ctx.JSON(http.StatusOK, gin.H{ "code": 0, "msg": AppConfig.MySQL.Host, }) }) router.Run(":8080") }
go.mod
module go-viper-http-watch go 1.16 require ( github.com/fsnotify/fsnotify v1.5.4 github.com/gin-gonic/gin v1.8.1 github.com/spf13/viper v1.12.0 ) replace go-viper-http-watch => ../go-viper-http-watch
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?
2021-06-10 linux tar包追加问题