router.go 1.0 KB

123456789101112131415161718192021222324252627282930313233343536
  1. /*
  2. * @desc:路由处理
  3. * @company:云南奇讯科技有限公司
  4. * @Author: yixiaohu<yxh669@qq.com>
  5. * @Date: 2022/11/16 11:09
  6. */
  7. package libRouter
  8. import (
  9. "context"
  10. "github.com/gogf/gf/v2/errors/gerror"
  11. "github.com/gogf/gf/v2/net/ghttp"
  12. "github.com/gogf/gf/v2/text/gregex"
  13. "reflect"
  14. )
  15. // RouterAutoBind 收集需要被绑定的控制器,自动绑定
  16. // 路由的方法命名规则必须为:BindXXXController
  17. func RouterAutoBind(ctx context.Context, R interface{}, group *ghttp.RouterGroup) (err error) {
  18. //TypeOf会返回目标数据的类型,比如int/float/struct/指针等
  19. typ := reflect.TypeOf(R)
  20. //ValueOf返回目标数据的的值
  21. val := reflect.ValueOf(R)
  22. if val.Elem().Kind() != reflect.Struct {
  23. err = gerror.New("expect struct but a " + val.Elem().Kind().String())
  24. return
  25. }
  26. for i := 0; i < typ.NumMethod(); i++ {
  27. if match := gregex.IsMatchString(`^Bind(.+)Controller$`, typ.Method(i).Name); match {
  28. //调用绑定方法
  29. val.Method(i).Call([]reflect.Value{reflect.ValueOf(ctx), reflect.ValueOf(group)})
  30. }
  31. }
  32. return
  33. }