gin/router/register.go

78 lines
2.2 KiB
Go
Raw Normal View History

2023-03-03 16:52:18 +08:00
// Package router ...
//
2024-07-20 23:39:25 +08:00
// Description : router ...
2023-03-03 16:52:18 +08:00
//
// Author : go_developer@163.com<白茶清欢>
//
2024-07-20 23:39:25 +08:00
// Date : 2024-07-20 21:39
2023-03-03 16:52:18 +08:00
package router
import (
2024-07-20 23:39:25 +08:00
"fmt"
2023-03-03 16:52:18 +08:00
"reflect"
"github.com/gin-gonic/gin"
)
var (
2024-07-20 23:39:25 +08:00
ginRouter = gin.Default()
2023-03-03 16:52:18 +08:00
)
2024-07-20 23:39:25 +08:00
func init() {
2023-03-03 16:52:18 +08:00
}
2024-07-20 23:39:25 +08:00
// Register 注册路由
2023-03-03 16:52:18 +08:00
//
// Author : go_developer@163.com<白茶清欢>
//
2024-07-20 23:39:25 +08:00
// Date : 21:40 2024/7/20
func Register(port int, controllerList ...any) {
for _, controller := range controllerList {
if nil == controller {
// 忽略空指针
2023-03-03 16:52:18 +08:00
continue
}
}
}
2024-07-20 23:39:25 +08:00
// parseController 解析controller
2023-03-03 16:52:18 +08:00
//
// Author : go_developer@163.com<白茶清欢>
//
2024-07-20 23:39:25 +08:00
// Date : 22:10 2024/7/20
func parseController(controller any) {
controllerType := reflect.TypeOf(controller)
controllerValue := reflect.ValueOf(controller)
routerPrefix := "/"
// 解析路由前缀函数
// routerPrefix 不能有任何入参, 并且只能有一个返回值,
// 返回值类型为字符串, 为具体路由前缀
routerPrefixFunc, routerPrefixFuncExist := controllerType.MethodByName(PrefixFuncName)
if routerPrefixFuncExist {
routerPrefixFuncType := routerPrefixFunc.Type
if routerPrefixFuncType.NumIn() == 1 && // 无任何入参, 正在没有如何入参情况下, 第一个参数是结构体指针
routerPrefixFuncType.NumOut() == 1 && // 只能有一个返回值
routerPrefixFuncType.Out(0).Kind() == reflect.String { // 返回值必须是字符串
routerPrefix = routerPrefixFunc.Func.Call([]reflect.Value{controllerValue})[0].String()
}
2024-07-21 12:19:23 +08:00
}
// 请求组的中间件
middlewareList := make([]gin.HandlerFunc, 0)
routerMiddlewareFunc, routerMiddlewareFuncExist := controllerType.MethodByName(MiddlewareFuncName)
if routerMiddlewareFuncExist {
routerMiddlewareFuncType := routerMiddlewareFunc.Type
if routerMiddlewareFuncType.NumIn() == 1 && // 无需任何参数
2024-07-20 23:39:25 +08:00
routerMiddlewareFuncType.NumOut() == 1 && // 只能有一个返回值
routerMiddlewareFuncType.Out(0).String() == "[]gin.HandlerFunc" { // 返回值必须是gin.HandlerFunc
2024-07-21 12:19:23 +08:00
res := routerMiddlewareFunc.Func.Call([]reflect.Value{controllerValue})
if !res[0].IsNil() {
middlewareList = res[0].Interface().([]gin.HandlerFunc)
}
}
fmt.Println(111, middlewareList)
2023-03-03 16:52:18 +08:00
}
2024-07-21 12:19:23 +08:00
2024-07-20 23:39:25 +08:00
fmt.Println(routerPrefix)
2023-03-03 16:52:18 +08:00
}