package gin import ( "fmt" "framework_v2/internal/app/auth" "framework_v2/internal/app/facade" "framework_v2/internal/app/helper" http2 "framework_v2/internal/middleware/http" "github.com/gin-gonic/gin" "net/http" "reflect" ) func GET(relativePath string, handlers ...interface{}) { facade.Router.GET(relativePath, func(c *gin.Context) { doHandler(c, handlers...) }) } func POST(relativePath string, handlers ...interface{}) { facade.Router.POST(relativePath, func(c *gin.Context) { doHandler(c, handlers...) }) } func PUT(relativePath string, handlers ...interface{}) { facade.Router.PUT(relativePath, func(c *gin.Context) { doHandler(c, handlers...) }) } func PATCH(relativePath string, handlers ...interface{}) { facade.Router.PATCH(relativePath, func(c *gin.Context) { doHandler(c, handlers...) }) } func DELETE(relativePath string, handlers ...interface{}) { facade.Router.DELETE(relativePath, func(c *gin.Context) { doHandler(c, handlers...) }) } func doHandler(c *gin.Context, handlers ...interface{}) { for _, handler := range handlers { if c.IsAborted() { // 是否已经响应 if c.Writer.Written() { return } else { helper.ResponseError(c, http.StatusBadRequest, http2.ErrEmptyResponse) } return } wrapHandler(c, handler) } } func wrapHandler(c *gin.Context, f interface{}) { fnValue := reflect.ValueOf(f) fnType := fnValue.Type() var args []reflect.Value for i := 0; i < fnType.NumIn(); i++ { argType := fnType.In(i) var argValue reflect.Value switch argType { case reflect.TypeOf((*gin.Context)(nil)): argValue = reflect.ValueOf(c) case reflect.TypeOf((*auth.User)(nil)): userInfo := http2.DIJWTAuth(c) if userInfo == nil { helper.ResponseError(c, http.StatusUnauthorized, http2.ErrNotValidToken) return } argValue = reflect.ValueOf(userInfo) default: helper.ResponseError(c, http.StatusBadRequest, fmt.Errorf("invalid argument type: %s", argType.String())) return } args = append(args, argValue) } fnValue.Call(args) }