golib/gweb/context.go

117 lines
2.3 KiB
Go
Raw Normal View History

//
// context.go
// Copyright (C) 2023 tiglog <me@tiglog.com>
//
// Distributed under terms of the MIT license.
//
package gweb
import "github.com/gin-gonic/gin"
type IToken interface {
GetToken() string
IsExpired() string
}
type IClient interface {
GetAppId() string
GetAppSecret() string
}
type IUser interface {
GetUserId() int64
GetUserName() string
}
type Context struct {
*gin.Context
VarInt int
VarStr string
Token IToken
Client IClient
User IUser
}
2023-10-17 17:38:04 +08:00
type Engine struct {
*gin.Engine
}
type Router struct {
*gin.RouterGroup
}
2023-10-17 17:38:04 +08:00
func New() *Engine {
return &Engine{
Engine: gin.New(),
}
}
2023-10-17 17:38:04 +08:00
func Default() *Engine {
return &Engine{
Engine: gin.Default(),
}
}
2023-10-17 17:42:04 +08:00
type HandlerFunc func(c *Context)
func handleFunc(hd func(c *Context)) func(ctx *gin.Context) {
return func(c *gin.Context) {
hd(&Context{
Context: c,
})
}
}
// 重写路由组注册
2023-10-17 17:42:04 +08:00
func (app *Engine) Group(relativePath string, handlers ...HandlerFunc) *Router {
hds := make([]gin.HandlerFunc, 0)
for _, hd := range handlers {
hds = append(hds, handleFunc(hd))
}
return &Router{
app.Engine.Group(relativePath, hds...),
}
}
// 重写根GET请求
2023-10-17 17:42:04 +08:00
func (app *Engine) GET(relativePath string, handlers ...HandlerFunc) gin.IRoutes {
hds := make([]gin.HandlerFunc, 0)
for _, hd := range handlers {
hds = append(hds, handleFunc(hd))
}
return app.Engine.GET(relativePath, hds...)
}
// 重写根POST请求
2023-10-17 17:42:04 +08:00
func (app *Engine) POST(relativePath string, handlers ...HandlerFunc) gin.IRoutes {
hds := make([]gin.HandlerFunc, 0)
for _, hd := range handlers {
hds = append(hds, handleFunc(hd))
}
return app.Engine.POST(relativePath, hds...)
}
// 重写子GET请求
2023-10-17 17:42:04 +08:00
func (r *Router) GET(relativePath string, handlers ...HandlerFunc) gin.IRoutes {
hds := make([]gin.HandlerFunc, 0)
for _, hd := range handlers {
hds = append(hds, handleFunc(hd))
}
return r.RouterGroup.GET(relativePath, hds...)
}
// 重写子 POST 请求
2023-10-17 17:42:04 +08:00
func (r *Router) POST(relativePath string, handlers ...HandlerFunc) gin.IRoutes {
hds := make([]gin.HandlerFunc, 0)
for _, hd := range handlers {
hds = append(hds, handleFunc(hd))
}
return r.RouterGroup.POST(relativePath, hds...)
}
// 重写中间件注册
2023-10-17 17:42:04 +08:00
func (r *Router) Use(mws ...HandlerFunc) gin.IRoutes {
hds := make([]gin.HandlerFunc, 0)
for _, mw := range mws {
hds = append(hds, handleFunc(mw))
}
return r.RouterGroup.Use(hds...)
}