From e95061a1a8f36a47c93687887f94d45de3531f5e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=99=BD=E8=8C=B6=E6=B8=85=E6=AC=A2?= Date: Fri, 7 Feb 2025 16:57:15 +0800 Subject: [PATCH] =?UTF-8?q?=E5=AE=8C=E6=88=90=E5=9F=BA=E7=A1=80=E5=8F=8D?= =?UTF-8?q?=E5=B0=84=E8=B0=83=E7=94=A8=E6=8E=A5=E5=8F=A3=20+=20=E6=95=B0?= =?UTF-8?q?=E6=8D=AE=E5=93=8D=E5=BA=94?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- router/controller.go | 29 ++++++++++++++++++----------- router/define.go | 17 +++++++++-------- router/group.go | 2 +- router/handler.go | 4 +++- router/register.go | 16 ++++++++-------- router/register_test.go | 22 +++++----------------- 6 files changed, 44 insertions(+), 46 deletions(-) diff --git a/router/controller.go b/router/controller.go index bb2cd5b..ce96bbb 100644 --- a/router/controller.go +++ b/router/controller.go @@ -8,6 +8,7 @@ package router import ( + "fmt" "reflect" "strings" ) @@ -38,25 +39,26 @@ func (c controller) Parse(inputController any) map[string]UriConfig { } controllerType := reflect.TypeOf(inputController) controllerValue := reflect.ValueOf(inputController) - if controllerType.Kind() == reflect.Func { + /*if controllerType.Kind() == reflect.Func { // 直接函数注册 cfg, isNeedRegister := c.methodConfig(controllerType) if isNeedRegister { parseRes[cfg.Path] = cfg } return parseRes - } + }*/ if controllerType.Kind() == reflect.Ptr { controllerValue = controllerValue.Elem() } - if controllerValue.IsNil() { + /*if controllerValue.IsNil() { return parseRes - } + }*/ for methodIdx := 0; methodIdx < controllerType.NumMethod(); methodIdx++ { - uriCfg, needRegister := c.methodConfig(controllerType.Method(methodIdx).Type) + uriCfg, needRegister := c.methodConfig(controllerType.Method(methodIdx)) if !needRegister { continue } + uriCfg.ApiStructValue = controllerValue parseRes[uriCfg.Path] = uriCfg } return parseRes @@ -71,7 +73,8 @@ func (c controller) Parse(inputController any) map[string]UriConfig { // Author : go_developer@163.com<白茶清欢> // // Date : 16:05 2025/1/27 -func (c controller) methodConfig(methodType reflect.Type) (cfg UriConfig, needRegister bool) { +func (c controller) methodConfig(reflectMethod reflect.Method) (cfg UriConfig, needRegister bool) { + methodType := reflectMethod.Type // num0: 函数声明 // num1: 第一个参数 // num2: 第二个参数 @@ -89,6 +92,7 @@ func (c controller) methodConfig(methodType reflect.Type) (cfg UriConfig, needRe if formType.Kind() == reflect.Ptr { formType = methodType.In(2).Elem() } + cfg.FormDataType = formType metaField, metaFieldExist := formType.FieldByName(FieldNameMeta) if !metaFieldExist { needRegister = false @@ -96,34 +100,37 @@ func (c controller) methodConfig(methodType reflect.Type) (cfg UriConfig, needRe } // 解析第一个返回值, 要求必须是结构体或者是map - if methodType.Out(0).Kind() != reflect.Struct && methodType.Out(0).Kind() != reflect.Map { + /*if methodType.Out(0).Kind() != reflect.Struct && methodType.Out(0).Kind() != reflect.Map { needRegister = false return - } + }*/ if methodType.Out(1).Kind().String() != "error" { // 判断是否是实现 error接口的方法 outputErrParse := false for j := 0; j < methodType.Out(1).NumMethod(); j++ { if methodType.Out(1).Method(j).Name == "Error" && // 实现Error方法 - methodType.Out(1).Method(j).Type.NumIn() == 1 && // 没有任何参数 + methodType.Out(1).Method(j).Type.NumIn() == 0 && // 没有任何参数 methodType.Out(1).Method(j).Type.NumOut() == 1 && // 一个返回值 methodType.Out(1).Method(j).Type.Out(0).Kind().String() == reflect.String.String() { outputErrParse = true break } + fmt.Println(methodType.Out(1).Method(j).Name, methodType.Out(1).Method(j).Type.NumIn(), methodType.Out(1).Method(j).Type.NumOut(), methodType.Out(1).Method(j).Type.Out(0).Kind().String()) } if !outputErrParse { needRegister = false + return } - return } // 解析meta信息 cfg.Path = metaField.Tag.Get(TagNamePath) - cfg.Method = metaField.Tag.Get(TagNameMethod) + cfg.RequestMethod = metaField.Tag.Get(TagNameMethod) cfg.Desc = metaField.Tag.Get(TagNameDesc) cfg.TagList = strings.Split(metaField.Tag.Get(TagNameUriTag), ",") // 解析参数配置 cfg.ParamList = c.parseParamConfig(formType) + cfg.ApiLogicFunc = reflectMethod + needRegister = true return } diff --git a/router/define.go b/router/define.go index 76e3aae..74f1add 100644 --- a/router/define.go +++ b/router/define.go @@ -31,14 +31,15 @@ const ( // // Date : 15:41 2024/7/21 type UriConfig struct { - Path string `json:"path"` // 接口路由, 必须配置 - Method string `json:"method"` // 接口请求方法, 必须配置 - TagList []string `json:"tag_list"` // 接口分组 - Desc string `json:"desc"` // 接口描述 - Strict bool `json:"strict"` // 接口是否为严格模式 : 不配置, 则为严格模式.严格模式 : POST 仅解析 BODY , GET 仅解析 QUERY - ParamList []UriParam `json:"param_list"` // 参数信息表 - FormDataType reflect.Type `json:"-"` // 表单数据类型 - ApiLogicFunc reflect.Method `json:"-"` // 自定义的接口逻辑 + Path string `json:"path"` // 接口路由, 必须配置 + RequestMethod string `json:"request_method"` // 接口请求方法, 必须配置 + TagList []string `json:"tag_list"` // 接口分组 + Desc string `json:"desc"` // 接口描述 + Strict bool `json:"strict"` // 接口是否为严格模式 : 不配置, 则为严格模式.严格模式 : POST 仅解析 BODY , GET 仅解析 QUERY + ParamList []UriParam `json:"param_list"` // 参数信息表 + FormDataType reflect.Type `json:"-"` // 表单数据类型 + ApiStructValue reflect.Value `json:"-"` // 逻辑函数所属结构体取值 + ApiLogicFunc reflect.Method `json:"-"` // 自定义的接口逻辑 } // UriParam 接口参数配置 diff --git a/router/group.go b/router/group.go index d968676..1b39b67 100644 --- a/router/group.go +++ b/router/group.go @@ -26,7 +26,7 @@ func Group(router *gin.Engine, routerPrefix string, middlewareList []gin.Handler for _, c := range cList { urlTable := cParser.Parse(c) for _, itemUriCfg := range urlTable { - method := strings.ToUpper(itemUriCfg.Method) + method := strings.ToUpper(itemUriCfg.RequestMethod) switch method { case http.MethodGet: g.GET(itemUriCfg.Path, RequestHandler(itemUriCfg)) diff --git a/router/handler.go b/router/handler.go index b7aa2a1..bfd2a0c 100644 --- a/router/handler.go +++ b/router/handler.go @@ -31,10 +31,12 @@ func RequestHandler(uriCfg UriConfig) gin.HandlerFunc { formData := reflect.New(uriCfg.FormDataType).Interface() // 表单解析 if err = request.Form.Parse(ctx, formData); nil != err { + e = exception.NewFromError(400, err) + response.SendWithException(ctx, e, nil) return } // 执行逻辑 - resList := uriCfg.ApiLogicFunc.Func.Call([]reflect.Value{reflect.ValueOf(ctx), reflect.ValueOf(formData)}) + resList := uriCfg.ApiLogicFunc.Func.Call([]reflect.Value{uriCfg.ApiStructValue, reflect.ValueOf(ctx), reflect.ValueOf(formData)}) if resList[1].IsNil() { // 请求成功 response.Success(ctx, resList[0].Interface()) diff --git a/router/register.go b/router/register.go index 1ac03d3..d49844e 100644 --- a/router/register.go +++ b/router/register.go @@ -123,12 +123,12 @@ func parseUriConfig(methodType reflect.Type, routerPrefix string) (*UriConfig, e return nil, nil } uriConfig := &UriConfig{ - Path: strings.TrimRight(routerPrefix, "/") + "/" + strings.TrimLeft(metaField.Tag.Get(TagNamePath), "/"), - Method: strings.ToUpper(metaField.Tag.Get(TagNameMethod)), - TagList: strings.Split(metaField.Tag.Get(TagNameUriTag), "|"), - Desc: metaField.Tag.Get(TagNameDesc), - Strict: wrapper.ArrayType([]string{"", "true"}).Has(strings.ToLower(metaField.Tag.Get(TagNameStrict))) >= 0, - FormDataType: methodType.In(2).Elem(), + Path: strings.TrimRight(routerPrefix, "/") + "/" + strings.TrimLeft(metaField.Tag.Get(TagNamePath), "/"), + RequestMethod: strings.ToUpper(metaField.Tag.Get(TagNameMethod)), + TagList: strings.Split(metaField.Tag.Get(TagNameUriTag), "|"), + Desc: metaField.Tag.Get(TagNameDesc), + Strict: wrapper.ArrayType([]string{"", "true"}).Has(strings.ToLower(metaField.Tag.Get(TagNameStrict))) >= 0, + FormDataType: methodType.In(2).Elem(), } // 校验 FormDataType for fieldIdx := 0; fieldIdx < uriConfig.FormDataType.NumField(); fieldIdx++ { @@ -174,7 +174,7 @@ func registerUri(uriConfig *UriConfig, methodValue reflect.Value, middlewareList middlewareList = append([]gin.HandlerFunc{ middleware.InitRequest(), }, middlewareList...) - switch uriConfig.Method { + switch uriConfig.RequestMethod { case http.MethodGet: ginRouter.GET(uriConfig.Path, middlewareList...) case http.MethodHead: @@ -196,7 +196,7 @@ func registerUri(uriConfig *UriConfig, methodValue reflect.Value, middlewareList case "ANY": ginRouter.Any(uriConfig.Path, middlewareList...) default: - panic(uriConfig.Path + " : " + uriConfig.Method + " is not support") + panic(uriConfig.Path + " : " + uriConfig.RequestMethod + " is not support") } } diff --git a/router/register_test.go b/router/register_test.go index 4abc609..82a308f 100644 --- a/router/register_test.go +++ b/router/register_test.go @@ -15,24 +15,13 @@ import ( type TestController struct{} -func (t *TestController) RouterPrefix() string { - return "/uri/prefix" -} - -func (t *TestController) RouterMiddleware() []gin.HandlerFunc { - return []gin.HandlerFunc{ - func(ctx *gin.Context) { - - }, - } -} -func (t *TestController) Uri(ctx *gin.Context, formData *TestForm) (any, error) { +func (t TestController) Logic(ctx *gin.Context, formData *TestForm) (any, error) { return formData, nil } type TestForm struct { Meta `tag:"测试表单" path:"/a/b/c/d" desc:"测试接口" method:"get" strict:"true"` - Age int `json:"age" form:"age"` + Age int `json:"age" form:"age" binding:"min=20"` Name string `json:"name" form:"name"` Test *Test `json:"test" form:"test"` Num *int64 `json:"num" form:"num"` @@ -42,8 +31,7 @@ type Test struct { } func Test_parseController(t *testing.T) { - type args struct { - controller any - } - Register(8080, &TestController{}) + r := gin.Default() + Group(r, "test", nil, TestController{}) + r.Run(":8080") }