framework_v2/internal/providers/gin.go

61 lines
1.2 KiB
Go
Raw Normal View History

2024-06-13 06:32:33 +00:00
package providers
2024-06-13 07:08:55 +00:00
import (
"framework_v2/internal/access"
2024-06-13 08:36:10 +00:00
"framework_v2/internal/consts"
2024-06-13 07:36:51 +00:00
ginzap "github.com/gin-contrib/zap"
2024-06-13 07:08:55 +00:00
"github.com/gin-gonic/gin"
2024-06-13 07:36:51 +00:00
"time"
2024-06-13 07:08:55 +00:00
)
func InitGin() {
2024-06-13 07:36:51 +00:00
gin.SetMode(gin.ReleaseMode)
2024-06-13 07:08:55 +00:00
2024-06-13 07:36:51 +00:00
access.Router = gin.New()
2024-06-13 07:17:53 +00:00
2024-06-13 08:36:10 +00:00
access.Router.Use(ginzap.Ginzap(access.Logger, time.RFC3339, true))
//access.Router.Use(gin.Recovery())
//access.Router.Use(ginzap.RecoveryWithZap(access.Logger, true))
}
type httpMethod int
var httpMethodStr = []string{"GET", "POST", "PUT", "DELETE", "PATCH", "HEAD", "OPTIONS"}
func (h httpMethod) String() string {
return httpMethodStr[h-1]
}
const (
GET httpMethod = iota + 1
POST
PUT
DELETE
PATCH
HEAD
OPTIONS
)
type HandlerFunc func(metadata *consts.Request)
func HandleRoute(method httpMethod, relativePath string, controller HandlerFunc, middlewares ...gin.HandlerFunc) {
access.Router.Handle(method.String(), relativePath, func(c *gin.Context) {
for _, middleware := range middlewares {
middleware(c)
}
if !c.IsAborted() {
handleWithMetadata(c, controller)
}
})
}
func handleWithMetadata(c *gin.Context, controller HandlerFunc) {
var metadata = &consts.Request{
Http: c,
User: GetAuthFromCtx(c),
}
controller(metadata)
2024-06-13 07:08:55 +00:00
}