1. 前言
一个项目使用配置,可以方便修改、可扩展性强,对一些安全数据更好。
2. 配置工具
因为获取配置会经常用到,所以我把代码放到工具项目里了my-gin/toolkit/config,方便调用
package config
import (
"fmt"
"github.com/fsnotify/fsnotify"
"github.com/spf13/viper"
)
func Configure() *viper.Viper {
v := viper.New()
v.SetConfigName("config") // 设置文件名称(无后缀)
v.SetConfigType("toml") // 设置后缀名 {"1.6以后的版本可以不设置该后缀"}
v.AddConfigPath("./configs") // 设置文件所在路径
v.Set("verbose", true) // 设置默认参数
if err := v.ReadInConfig(); err != nil {
if _, ok := err.(viper.ConfigFileNotFoundError); ok {
panic(" Config file not found; ignore error if desired")
} else {
panic(err)
}
}
// 监控配置和重新获取配置
v.WatchConfig()
v.OnConfigChange(func(e fsnotify.Event) {
fmt.Println("Config file changed:", e.Name)
})
return v
}
使用的时候只需引用获取配置的工具,就可以愉快地使用了
import (
"my-gin/toolkit/config"
)
如main.go中设置端口
conf := config.Configure()
// 默认8080端口
if err := r.Run(conf.GetString("http.listen")); err != nil {
fmt.Println("startup service failed, err:%v\n", err)
}
为了方便页面的显示也在my-gin/routers/base.go 写了个获取配置的例子
package routers
import (
"fmt"
"github.com/gin-gonic/gin"
"net/http"
)
// 基础
package routers
import (
"github.com/gin-gonic/gin"
"my-gin/toolkit/config"
)
// 基础
func BaseRouter(e *gin.Engine) {
// 使用路由组
r := e.Group("/base")
r.GET("/config", getConfig)
}
// 获取配置
// 复制 configs/config.toml.default 为config.toml
func getConfig(c *gin.Context) {
conf := config.Configure()
conf.Set("redis.port", 6381)
c.JSON(200, gin.H{
"listen": conf.GetString("http.listen"),
"app_name": conf.Get("app_name"),
"ip": conf.Get("mysql.ip"),
"config": conf.AllSettings(),
})
}