From 08a8a8015cc51e51e13d49d4817d7fe2b31b18e3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=BC=A0=E5=BE=B7=E6=BB=A1?= Date: Fri, 26 Mar 2021 18:01:34 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BB=BB=E6=84=8F=E7=BB=93=E6=9E=84=E4=BD=93,?= =?UTF-8?q?=E5=A2=9E=E5=8A=A0RouterFunc=E8=AF=86=E5=88=AB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- gin/api/register.go | 17 +++++++++++++---- gin/api/register_router_test.go | 6 ++++++ 2 files changed, 19 insertions(+), 4 deletions(-) diff --git a/gin/api/register.go b/gin/api/register.go index aa4e2ab..dc9b12b 100644 --- a/gin/api/register.go +++ b/gin/api/register.go @@ -55,10 +55,20 @@ func RegisterRouter(router *gin.Engine, apiInstanceList ...interface{}) error { } continue } - routerLog(val.String() + " 注册的路由既不是 IApi 也不是 RouterFunc, 自动识别函数是否包含RouterFunc") + routerLog(val.String() + "结构体或者结构体指针, 自动识别函数是否包含RouterFunc") // 不是IApi接口,自动识别函数列表 RouterFunc 函数自动注册 methodCnt := val.NumMethod() for i := 0; i < methodCnt; i++ { + // TODO : 识别函数本身是不是 RouterFunc + af, o := val.Method(i).Interface().(func() (string, string, gin.HandlerFunc, []gin.HandlerFunc)) + if o { + method, uri, handler, middlewareList := af() + if err := util.RegisterRouter(router, method, uri, handler, middlewareList); nil != err { + routerLog(err.Error()) + return err + } + continue + } apiFuncList := val.Method(i).Call(nil) for _, apiFuncVal := range apiFuncList { apiFunc, ok := apiFuncVal.Interface().(RouterFunc) @@ -70,14 +80,13 @@ func RegisterRouter(router *gin.Engine, apiInstanceList ...interface{}) error { routerLog(err.Error()) return err } - routerLog(apiFuncVal.String() + " 自动注册路由成功") } } case reflect.Func: api, ok := apiInstance.(RouterFunc) if !ok { - err := errors.New("注册的路由必须是 IApi 或者 RouterFunc") + err := errors.New("函数方式注册路由必须是 RouterFunc") routerLog(err.Error()) return err } @@ -87,7 +96,7 @@ func RegisterRouter(router *gin.Engine, apiInstanceList ...interface{}) error { return err } default: - err := errors.New("注册的路由必须是 IApi 或者 RouterFunc") + err := errors.New("注册的路由必须是 IApi 或者 RouterFunc 或者 包含 RouterFunc 的结构体") routerLog(err.Error()) return err } diff --git a/gin/api/register_router_test.go b/gin/api/register_router_test.go index 1694023..f194a5d 100644 --- a/gin/api/register_router_test.go +++ b/gin/api/register_router_test.go @@ -70,3 +70,9 @@ func (oa *otherApi) DemoApiFunc() RouterFunc { func (oa *otherApi) Lala() { } + +func (oa *otherApi) SelfApi() (method string, uri string, handlerFunc gin.HandlerFunc, middlewareList []gin.HandlerFunc) { + return http.MethodGet, "/api/other/self/test", func(context *gin.Context) { + + }, nil +}