From 64a4d8ac56f2c7632167c9f69172ae0fa5cf3c05 Mon Sep 17 00:00:00 2001 From: yxh Date: Mon, 8 Apr 2024 09:43:49 +0800 Subject: [PATCH] =?UTF-8?q?fix=20=E8=B7=AF=E7=94=B1=E8=87=AA=E5=8A=A8?= =?UTF-8?q?=E7=BB=91=E5=AE=9A=E4=BC=98=E5=8C=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- library/libRouter/router.go | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) diff --git a/library/libRouter/router.go b/library/libRouter/router.go index 77963ab..2bce042 100644 --- a/library/libRouter/router.go +++ b/library/libRouter/router.go @@ -15,9 +15,25 @@ import ( "reflect" ) +// RouterAutoBindBefore 收集需要被绑定的不验证用户登录状态的控制器,自动绑定 +// 路由的方法命名规则必须为:BeforeBindXXXController +func RouterAutoBindBefore(ctx context.Context, R interface{}, group *ghttp.RouterGroup) (err error) { + return bind(ctx, R, group, "before") +} + // RouterAutoBind 收集需要被绑定的控制器,自动绑定 // 路由的方法命名规则必须为:BindXXXController func RouterAutoBind(ctx context.Context, R interface{}, group *ghttp.RouterGroup) (err error) { + return bind(ctx, R, group) +} + +func bind(ctx context.Context, R interface{}, group *ghttp.RouterGroup, option ...string) (err error) { + var rule string + if len(option) > 0 && option[0] == "before" { + rule = `^BeforeBind(.+)Controller$` + } else { + rule = `^Bind(.+)Controller$` + } //TypeOf会返回目标数据的类型,比如int/float/struct/指针等 typ := reflect.TypeOf(R) //ValueOf返回目标数据的的值 @@ -27,7 +43,7 @@ func RouterAutoBind(ctx context.Context, R interface{}, group *ghttp.RouterGroup return } for i := 0; i < typ.NumMethod(); i++ { - if match := gregex.IsMatchString(`^Bind(.+)Controller$`, typ.Method(i).Name); match { + if match := gregex.IsMatchString(rule, typ.Method(i).Name); match { //调用绑定方法 val.Method(i).Call([]reflect.Value{reflect.ValueOf(ctx), reflect.ValueOf(group)}) }