[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

posted on   进击的davis  阅读(939)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?
历史上的今天:
2021-06-10 linux tar包追加问题

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示