gin框架读取配置文件的两种方法 ④
在一个项目中,为了方便后期上线,一般会将需要改动的条件存放在配置文件中,比如监听的端口号,连接数据的语句等,下面介绍一下本人使用过的两种读取配置文件的方法:
文件结构如下:
controller->index.go
package controller import ( "fmt" "project/controller/second" "github.com/gin-gonic/gin" ) func GinRouter(r *gin.Engine) *gin.Engine { rr := r.Group("/") rr.GET("/first", func(c *gin.Context) { fmt.Println("first .........") }) rr = r.Group("/a") second.Routers(rr) return r }
controller->second->index.go
package second import ( "fmt" "net/http" ms "project/model/second" ss "project/services/second" "github.com/gin-gonic/gin" ) func Routers(r *gin.RouterGroup) { rr := r.Group("") rr.POST("/second", Function) return } func Function(c *gin.Context) { var input ms.Input if err := c.BindJSON(&input); err != nil { fmt.Println(err) } if output, err := ss.Function(c, input); err != nil { c.JSON(http.StatusBadRequest, gin.H{ "code": http.StatusBadRequest, "msg": "获取数据失败", "data": output, }) } else { c.JSON(http.StatusOK, gin.H{ "code": http.StatusOK, "msg": "获取数据成功", "data": output, }) } return }
model->second->index.go
package second type Input struct { //view:用于注释 //json:json形式 //from:解释该字段来自哪里,比如那个表 //binding: required:必须字段 email:email形式 //grom:数据库中列名 Id int `view:"id号" json:"id" from:"id" binding:"required" gorm:"column:id"` } type Output struct { Database DatabaseConfig `json:"database"` Self SelfConfig `json:"self"` } type DatabaseConfig struct { Types string `json:"types"` Local string `json:"local"` Online string `json:"online"` } type SelfConfig struct { Port string `json:"port"` Flag int `json:"flag"` Tag int `json:"tag"` }
services->second->index.go
package second import ( "fmt" ms "project/model/second" u "project/utils" "github.com/gin-gonic/gin" ) func Function(c *gin.Context, input ms.Input) (output ms.Output, err error) { fmt.Println("second .........,input:", input.Id) if input.Id == 1 { output.Database.Types = u.Config().Database.Types output.Database.Local = u.Config().Database.Local output.Database.Online = u.Config().Database.Online output.Self.Flag = u.Config().Self.Flag output.Self.Port = u.Config().Self.Port output.Self.Tag = u.Config().Self.Tag } else if input.Id == 2 { output.Database.Types, output.Database.Local, output.Database.Online, err = u.GetDatabase() if err != nil { return output, err } output.Self.Port, output.Self.Flag, output.Self.Tag, err = u.GetSelf() if err != nil { return output, err } } return output, nil }
utils->read_config_ini.go //读取配置文件1
package utils import ( "fmt" "strconv" "github.com/Unknwon/goconfig" ) var cfg *goconfig.ConfigFile func GetConfigIni(filepath string) (err error) { config, err := goconfig.LoadConfigFile(filepath) if err != nil { fmt.Println("配置文件读取错误,找不到配置文件", err) return err } cfg = config return nil } func GetDatabase() (types, local, online string, err error) { if types, err = cfg.GetValue("database", "types"); err != nil { fmt.Println("配置文件中不存在types", err) return types, local, online, err } if local, err = cfg.GetValue("database", "local"); err != nil { fmt.Println("配置文件中不存在local", err) return types, local, online, err } if online, err = cfg.GetValue("database", "online"); err != nil { fmt.Println("配置文件中不存在online", err) return types, local, online, err } return types, local, online, nil } func GetSelf() (port string, flag, tag int, err error) { if port, err = cfg.GetValue("self", "port"); err != nil { fmt.Println("配置文件中不存在port", err) return port, flag, tag, err } flag_temp, err := cfg.GetValue("self", "flag") if err != nil { fmt.Println("配置文件中不存在flag", err) return port, flag, tag, err } flag, err = strconv.Atoi(flag_temp) if err != nil { fmt.Println("配置文件中flag类型有误", err) return port, flag, tag, err } tag_temp, err := cfg.GetValue("self", "tag") if err != nil { fmt.Println("配置文件中不存在tag", err) return port, flag, tag, err } tag, err = strconv.Atoi(tag_temp) if err != nil { fmt.Println("配置文件中tag类型有误", err) return port, flag, tag, err } return port, flag, tag, nil }
utils->read_config_json.go //读取配置文件2
package utils import ( "encoding/json" "fmt" "io/ioutil" "sync" ) type GlobalConfig struct { Database DatabaseConfig `json:"database"` Self SelfConfig `json:"self"` } type DatabaseConfig struct { Types string `json:"types"` Local string `json:"local"` Online string `json:"online"` } type SelfConfig struct { Port string `json:"port"` Flag int `json:"flag"` Tag int `json:"tag"` } var ( globalconfig *GlobalConfig configMux sync.RWMutex ) func Config() *GlobalConfig { return globalconfig } func InitConfigJson(fliepath string) error { var config GlobalConfig file, err := ioutil.ReadFile(fliepath) if err != nil { fmt.Println("配置文件读取错误,找不到配置文件", err) return err } if err = json.Unmarshal(file, &config); err != nil { fmt.Println("配置文件读取失败", err) return err } configMux.Lock() globalconfig = &config configMux.Unlock() return nil }
config.ini //配置文件1
#连接数据库 [database] types=mysql local=root:root@tcp(10.9.195.130:3306)/project?parseTime=true online=root:aaa@tcp(1.1.1:3306)/project?parseTime=true #监听端口、**、** [self] port=8080 flag=2 tag=2
config.json //配置文件2
{ "database":{ "types":"mysql", "local":"root:root@tcp(10.9.195.130:3306)/project?parseTime=true", "online":"root:aaa@tcp(1.1.1:3306)/project?parseTime=true" }, "self":{ "port":"8080", "flag":1, "tag":1 } }
index.go
package main import ( c "project/controller" u "project/utils" "github.com/gin-gonic/gin" ) func main() { r := gin.Default() rr := c.GinRouter(r) //初始化配置文件 err := u.InitConfigJson("config.json") if err != nil { panic(err) } err = u.GetConfigIni("config.ini") if err != nil { panic(err) } // 监听并在 0.0.0.0:8080 上启动服务 rr.Run(":8080") }
访问方式及结果