-
Notifications
You must be signed in to change notification settings - Fork 1
/
util.go
324 lines (275 loc) · 7.36 KB
/
util.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
package ginplus
import (
"fmt"
"path"
"reflect"
"strings"
"github.com/gin-gonic/gin"
)
const (
GinHandleFunc = "gin.HandlerFunc"
)
// 判断该方法返回值是否为 gin.HandlerFunc类型
func isHandlerFunc(t reflect.Type) bool {
if t.Kind() != reflect.Func {
return false
}
if t.NumOut() != 1 {
return false
}
return t.Out(0).String() == GinHandleFunc
}
// isCallBack 判断是否为CallBack类型
func isCallBack(t reflect.Type) (reflect.Type, reflect.Type, bool) {
// 通过反射获取方法的返回值类型
if t.Kind() != reflect.Func {
return nil, nil, false
}
if t.NumIn() != 3 || t.NumOut() != 2 {
return nil, nil, false
}
if t.Out(1).String() != "error" {
return nil, nil, false
}
if t.In(1).String() != "context.Context" {
return nil, nil, false
}
// new一个out 0的实例和in 2的实例
req := t.In(2)
resp := t.Out(0)
return req, resp, true
}
func isNil(value interface{}) bool {
// 使用反射获取值的类型和值
val := reflect.ValueOf(value)
// 检查值的类型
switch val.Kind() {
case reflect.Ptr, reflect.Interface, reflect.Slice, reflect.Map, reflect.Chan, reflect.Func:
// 对于指针、接口、切片、映射、通道和函数类型,使用IsNil()方法来检查是否为nil
return val.IsNil()
default:
// 对于其他类型,无法直接检查是否为nil
return false
}
}
func (l *GinEngine) GenRoute(parentGroup *gin.RouterGroup, controller any) *GinEngine {
if isNil(controller) {
logger.Warn("controller is nil")
return l
}
l.genRoute(parentGroup, controller, false)
return l
}
func (l *GinEngine) genRoute(parentGroup *gin.RouterGroup, controller any, skipAnonymous bool) {
if isNil(controller) {
return
}
t := reflect.TypeOf(controller)
tmp := t
for tmp.Kind() == reflect.Ptr {
if tmp == nil {
return
}
tmp = tmp.Elem()
}
if !isPublic(tmp.Name()) {
return
}
var middlewares []gin.HandlerFunc
mid, isMid := isMiddleware(controller)
if isMid {
//Middlewares方法返回的是gin.HandlerFunc类型的切片, 中间件
middlewares = mid.Middlewares()
}
basePath := l.routeNamingRuleFunc(tmp.Name())
ctrl, isCtrl := isController(controller)
if isCtrl {
basePath = ctrl.BasePath()
}
parentRouteGroup := parentGroup
if parentRouteGroup == nil {
parentRouteGroup = l.Group("/")
}
routeGroup := parentRouteGroup.Group(path.Join(basePath), middlewares...)
methodMiddlewaresMap := make(map[string][]gin.HandlerFunc)
methodMid, privateMidOk := isMethodMiddleware(controller)
if privateMidOk {
methodMiddlewaresMap = methodMid.MethodeMiddlewares()
}
if !skipAnonymous {
for i := 0; i < t.NumMethod(); i++ {
methodName := t.Method(i).Name
if !isPublic(methodName) {
continue
}
route := l.parseRoute(methodName)
if route == nil {
continue
}
privateMid := methodMiddlewaresMap[methodName]
// 接口私有中间件
route.Handles = append(route.Handles, privateMid...)
if isHandlerFunc(t.Method(i).Type) {
// 具体的action
handleFunc := t.Method(i).Func.Call([]reflect.Value{reflect.ValueOf(controller)})[0].Interface().(gin.HandlerFunc)
route.Handles = append(route.Handles, handleFunc)
routeGroup.Handle(strings.ToUpper(route.HttpMethod), route.Path, route.Handles...)
continue
}
// 判断是否为CallBack类型
req, resp, isCb := isCallBack(t.Method(i).Type)
if isCb {
// 生成路由openAPI数据
l.genOpenAPI(routeGroup, req, resp, route, methodName)
// 注册路由回调函数
handleFunc := l.defaultHandler(controller, t.Method(i), req)
l.registerCallHandler(route, routeGroup, handleFunc)
continue
}
}
}
l.genStructRoute(routeGroup, controller)
}
// 生成openAPI数据
func (l *GinEngine) genOpenAPI(group *gin.RouterGroup, req, resp reflect.Type, route *Route, methodName string) {
reqName := req.Name()
respName := resp.Name()
reqTagInfo := getTag(req)
apiRoute := ApiRoute{
Path: route.Path,
HttpMethod: strings.ToLower(route.HttpMethod),
MethodName: methodName,
ReqParams: Field{
Name: reqName,
Info: reqTagInfo,
},
RespParams: Field{
Name: respName,
Info: getTag(resp),
},
}
// 处理Uri参数
for _, tagInfo := range reqTagInfo {
uriKey := tagInfo.Tags.UriKey
skip := tagInfo.Tags.Skip
if uriKey != "" && uriKey != "-" && skip != "true" {
route.Path = path.Join(route.Path, fmt.Sprintf(":%s", uriKey))
}
}
apiPath := path.Join(group.BasePath(), route.Path)
apiRoute.Path = apiPath
if _, ok := l.apiRoutes[apiPath]; !ok {
l.apiRoutes[apiPath] = make([]ApiRoute, 0, 1)
}
l.apiRoutes[apiPath] = append(l.apiRoutes[apiPath], apiRoute)
}
// registerCallHandler 注册回调函数
func (l *GinEngine) registerCallHandler(route *Route, routeGroup *gin.RouterGroup, handleFunc gin.HandlerFunc) {
// 具体的action
route.Handles = append(route.Handles, handleFunc)
routeGroup.Handle(strings.ToUpper(route.HttpMethod), route.Path, route.Handles...)
}
// genStructRoute 递归注册结构体路由
func (l *GinEngine) genStructRoute(parentGroup *gin.RouterGroup, controller any) {
if isNil(controller) {
return
}
tmp := reflect.TypeOf(controller)
for tmp.Kind() == reflect.Ptr {
if tmp == nil {
return
}
tmp = tmp.Elem()
}
if isStruct(tmp) {
// 递归获取内部的controller
for i := 0; i < tmp.NumField(); i++ {
field := tmp.Field(i)
for field.Type.Kind() == reflect.Ptr {
field.Type = field.Type.Elem()
}
if !isStruct(field.Type) {
continue
}
if !isPublic(field.Name) {
continue
}
newController := reflect.ValueOf(controller).Elem().Field(i).Interface()
// 判断field值是否为nil
if isNil(newController) {
continue
}
l.genRoute(parentGroup, newController, field.Anonymous)
}
}
}
// isPublic 判断是否为公共方法
func isPublic(name string) bool {
if len(name) == 0 {
return false
}
first := name[0]
if first < 'A' || first > 'Z' {
return false
}
return true
}
// parseRoute 从方法名称中解析出路由和请求方式
func (l *GinEngine) parseRoute(methodName string) *Route {
method := ""
routePath := ""
for prefix, httpMethodKey := range l.httpMethodPrefixes {
if strings.HasPrefix(methodName, prefix) {
method = strings.ToLower(httpMethodKey.key)
routePath = strings.TrimPrefix(methodName, prefix)
if routePath == "" {
routePath = strings.ToLower(methodName)
}
break
}
}
if method == "" || routePath == "" {
return nil
}
return &Route{
Path: path.Join("/", l.routeNamingRuleFunc(routePath)),
HttpMethod: method,
}
}
// routeToCamel 将路由转换为驼峰命名
func routeToCamel(route string) string {
if route == "" {
return ""
}
// 首字母小写
if route[0] >= 'A' && route[0] <= 'Z' {
route = string(route[0]+32) + route[1:]
}
return route
}
// isMiddleware 判断是否为Controller类型
func isMiddleware(c any) (IMiddleware, bool) {
mid, ok := c.(IMiddleware)
return mid, ok
}
// isController 判断是否为Controller类型
func isController(c any) (Controller, bool) {
ctrl, ok := c.(Controller)
return ctrl, ok
}
// isMethodMiddleware 判断是否为MethodMiddleware类型
func isMethodMiddleware(c any) (MethodeMiddleware, bool) {
mid, ok := c.(MethodeMiddleware)
return mid, ok
}
// isStruct 判断是否为struct类型
func isStruct(t reflect.Type) bool {
tmp := t
for tmp.Kind() == reflect.Ptr {
if tmp == nil {
return false
}
tmp = tmp.Elem()
}
return tmp.Kind() == reflect.Struct
}