1 Star 0 Fork 0

伍凯歌 / GinFrame

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
init.go 2.45 KB
一键复制 编辑 原始数据 按行查看 历史
wukaige 提交于 2022-04-21 10:25 . init
package gf
import (
"fmt"
"gitee.com/kingsingnal/util/gconv"
"github.com/Unknwon/goconfig"
"github.com/gin-gonic/gin"
"github.com/go-redis/redis/v7"
_ "github.com/go-sql-driver/mysql"
"github.com/jinzhu/gorm"
log "github.com/sirupsen/logrus"
"sync"
"time"
)
const (
DEFAULT = "default"
successCode = 200
)
var gf *Gf
var configOne sync.Once
var contextPool *sync.Pool
var res404 = Response{
Code: "404",
Msg: "页面不存在",
Data: nil,
}
var resSuccess = Response{
Code: "200",
Msg: "错误信息",
Data: CodeMapping,
}
func GetContext(g *gin.Context) *Context {
c := contextPool.Get().(*Context)
c.Context = g
return c
}
func init() {
gf = &Gf{
Gin: gin.New(),
Log: *log.New(),
Config: &goconfig.ConfigFile{},
Db: make(map[string]*gorm.DB),
Redis: make(map[string]*redis.Client),
}
gf.Gin.NoRoute(func(context *gin.Context) {
context.JSON(successCode, res404)
})
gf.Gin.GET("/codes", func(context *gin.Context) {
context.JSON(successCode, resSuccess)
})
contextPool = &sync.Pool{New: func() interface{} {
return &Context{}
}}
}
func InitConfig(path string) {
configOne.Do(func() {
var err error
GetGf().Config, err = goconfig.LoadConfigFile(path)
if err != nil {
panic(fmt.Sprintf("unable to load config file:%s \n", err))
}
ServiceName, _ = gf.Config.GetValue("", "SERVICE_NAME")
gf.Gin.GET("/"+ServiceName+"/code", func(context *gin.Context) {
context.JSON(200, codeMapping{})
})
})
}
func InitDb() {
cf, err := gf.Config.GetValue("", "MYSQL_DSN")
if err == nil {
db, err := gorm.Open("mysql", cf)
if err == nil {
GetGf().Db[DEFAULT] = db
}
}
if err != nil {
log.Error("db init error: %s", err.Error())
}
}
func InitRedis() {
cf, err := GetGf().Config.GetSection("redis")
if err == nil {
c := redis.NewClient(&redis.Options{
Network: "tcp",
Addr: cf["host"] + ":" + cf["port"],
Dialer: nil,
OnConnect: nil,
Password: cf["password"],
DB: gconv.String2Int(cf["db"], 0),
MaxRetries: 3,
DialTimeout: 5 * time.Second,
ReadTimeout: 3 * time.Second,
WriteTimeout: 3 * time.Second,
PoolSize: gconv.String2Int(cf["poolSize"], 20),
MinIdleConns: gconv.String2Int(cf["minIdleConn"], 5),
MaxConnAge: 20,
PoolTimeout: 3 * time.Second,
IdleTimeout: 5 * time.Second,
})
if c.Ping().Err() == nil {
GetGf().Redis[DEFAULT] = c
}
}
if err != nil {
log.Error("redis init error: %s", err.Error())
}
}
Go
1
https://gitee.com/kingsingnal/go-gin-frame.git
git@gitee.com:kingsingnal/go-gin-frame.git
kingsingnal
go-gin-frame
GinFrame
0592110cac6f

搜索帮助