-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcontroller.go
423 lines (383 loc) · 11.1 KB
/
controller.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
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
package eudore
import (
"fmt"
"reflect"
"sort"
"strings"
)
// Controller defines the controller interface and implements
// custom [Router] registration.
type Controller interface {
Inject(ctl Controller, router Router) error
}
type controllerGroup interface {
ControllerGroup(pkg string, name string) string
}
// controllerRoute defines the interface for get route and method mapping.
type controllerRoute interface {
ControllerRoute() map[string]string
}
// controllerParam defines the interface for get route [Params],
// using the route [Params] returned by pkg, controllername, and methodname.
type controllerParam interface {
ControllerParam(pkg string, name string, method string) string
}
// The ControllerAutoRoute implements the routing mapping controller
// to register the corresponding router method according to the method.
//
// If the controller is composed of other objects,
// the method name suffixed with the 'Controller' object will be
// used to generate the route.
type ControllerAutoRoute struct{}
// ControllerAutoType additionally registers the [HandlerExtender] corresponding
// to type T.
//
// refer [ControllerAutoRoute].
type ControllerAutoType[T any] struct{}
type controllerError struct {
Controller
Error error
}
// NewControllerError function returns a [controllerError],
// and the corresponding error is returned when the [Controller] Inject.
func NewControllerError(ctl Controller, err error) Controller {
return &controllerError{
Controller: ctl,
Error: err,
}
}
// The Inject method returns a controller error when injecting routing rules.
func (ctl controllerError) Inject(Controller, Router) error {
return ctl.Error
}
func (ctl controllerError) Unwrap() Controller {
return ctl.Controller
}
// Inject method implements the method of injecting the [Controller]
// into the [Router], and the [ControllerAutoRoute] controller calls the
// [ControllerInjectAutoRoute] method to inject.
//
// The first word of the controller method must be in the title format,
// defined in DefaultRouterAllMethod;
//
// ByName is converted to variable matching /:name;
// the last word is By and is converted to /*;
// other words are converted to constant matching.
//
// ANY => ANY /*
// GetByID => GET /:id
// PostGroupsByIDBy => POST /groups/:id/*
func (ctl ControllerAutoRoute) Inject(controller Controller, router Router,
) error {
return ControllerInjectAutoRoute(controller, router)
}
// The ControllerGroup method returns the [Router.Group] registered by
// the [Controller]. If it returns null string, it is ignored.
//
// refer [getContrllerGroup].
func (ctl ControllerAutoRoute) ControllerGroup(pkg, name string) string {
return controllerDefaultGroup(pkg, name)
}
// The ControllerRoute method can specify the route generated by the method,
// or append route [Params].
//
// The map key is the controller method, the value is the route,
// and the method is ignored when the value is '-',
// value format: '{method} path {[Params]}'.
//
// /index
// /index action=GetIndex
// GET /index
// GET /index action=GetIndex
// name=GetIndex
func (ctl ControllerAutoRoute) ControllerRoute() map[string]string {
return nil
}
// The ControllerParam method returns the [Params] used when each method
// is converted into a route.
//
// The default format is: [DefaultControllerParam].
func (ctl ControllerAutoRoute) ControllerParam(pkg, name, method string,
) string {
return controllerDefaultGroupParam(pkg, name, method)
}
func controllerDefaultGroup(_, name string) string {
name = strings.TrimSuffix(name, "Controller")
buf := make([]rune, 0, len(name)*2)
for _, b := range name {
if 64 < b && b < 91 {
buf = append(buf, '/', b+0x20)
} else {
buf = append(buf, b)
}
}
return string(buf)
}
// The controllerDefaultGroupParam function defines the
// default controller [Params],
// which can be overridden by implementing [controllerParam].
func controllerDefaultGroupParam(pkg, name, method string) string {
param := DefaultControllerParam
param = strings.ReplaceAll(param, "{{Package}}", pkg)
param = strings.ReplaceAll(param, "{{Name}}", name)
param = strings.ReplaceAll(param, "{{Method}}", method)
return param
}
// Inject method calls the [ControllerInjectAutoRoute] method to inject,
// And register the [HandlerExtender] of typeParam T.
//
// refer [ControllerInjectAutoRoute].
func (ctl ControllerAutoType[T]) Inject(controller Controller, router Router,
) error {
router = router.Group(fmt.Sprintf(" %s=~extend", ParamLoggerKind))
_ = router.AddHandlerExtend(
NewHandlerFuncContextType[*T],
NewHandlerFuncContextTypeAny[*T],
NewHandlerFuncContextTypeError[*T],
NewHandlerFuncContextTypeAnyError[*T],
NewHandlerFuncContextType[[]T],
NewHandlerFuncContextTypeAny[[]T],
NewHandlerFuncContextTypeError[[]T],
NewHandlerFuncContextTypeAnyError[[]T],
)
return ControllerInjectAutoRoute(controller, router)
}
// ControllerInjectAutoRoute implements controller method injection routes.
//
// refer: [ControllerAutoRoute] [ControllerAutoRoute.Inject]
// [ControllerAutoRoute.ControllerGroup]
// [ControllerAutoRoute.ControllerRoute]
// [ControllerAutoRoute.ControllerParam].
func ControllerInjectAutoRoute(controller Controller, router Router) error {
iType := reflect.TypeOf(controller)
v := reflect.ValueOf(controller)
// Add the controller group.
cname := getControllerName(v)
cpkg := reflect.Indirect(v).Type().PkgPath()
router = getContrllerGroup(router, controller, cpkg, cname)
// Get route parameter function
pfn := controllerDefaultGroupParam
p, ok := controller.(controllerParam)
if ok {
pfn = p.ControllerParam
}
// Router registration controller method
names, paths := getSortRoutes(getControllerRoutes(controller))
for i, name := range names {
m, ok := iType.MethodByName(name)
if !ok || paths[i] == "-" {
continue
}
h := v.Method(m.Index).Interface()
SetHandlerAliasName(h, fmt.Sprintf("%s.%s.%s", cpkg, cname, name))
method := getMethodByName(name)
if method == "" {
method = MethodAny
}
err := router.AddHandler(method, paths[i]+" "+pfn(cpkg, cname, name), h)
if err != nil {
return err
}
}
return nil
}
func getContrllerGroup(router Router, controller Controller,
pkg, name string,
) Router {
var group string
ctl, ok := controller.(controllerGroup)
switch {
case router.Params().Get(ParamControllerGroup) != "":
group = router.Params().Get(ParamControllerGroup)
router.Params().Del(ParamControllerGroup)
case ok:
group = ctl.ControllerGroup(pkg, name)
default:
group = controllerDefaultGroup(pkg, name)
}
if group == "" {
return router
}
if group[0] != '/' {
return router.Group("/" + group)
}
return router.Group(group)
}
func getSortRoutes(data map[string]string) ([]string, []string) {
keys := make([]string, 0, len(data))
vals := make([]string, len(data))
for key := range data {
keys = append(keys, key)
}
sort.Slice(keys, func(i, j int) bool {
ri, rj := data[keys[i]], data[keys[j]]
if ri == rj {
return getSortMethodIndex(keys[i]) < getSortMethodIndex(keys[j])
}
return ri < rj
})
for i, key := range keys {
vals[i] = data[key]
}
return keys, vals
}
func getSortMethodIndex(method string) int {
method = getMethodByName(method)
if method == MethodAny {
return 0
}
return sliceIndex(DefaultRouterAllMethod, method) + 1
}
// The getControllerRoutes function gets a mapping of all names and routes from
// a [Controller] type.
func getControllerRoutes(controller Controller) map[string]string {
routes := getContrllerAllowMethos(reflect.ValueOf(controller))
for name := range routes {
if getMethodByName(name) != "" {
routes[name] = getRouteByName(name)
} else {
delete(routes, name)
}
}
// If the controller implements the [ControllerRoute] interface,
// load additional routes.
controllerRoute, isRoute := controller.(controllerRoute)
if isRoute {
for name, path := range controllerRoute.ControllerRoute() {
if len(path) > 0 && path[0] == ' ' {
// The path by ControllerRoute starts with a space,
// indicating a route [Params].
routes[name] += path
} else {
routes[name] = path
}
}
}
return routes
}
func getContrllerAllowMethos(v reflect.Value) map[string]string {
names := make(map[string]string)
for _, name := range getContrllerAllMethos(v) {
names[name] = ""
}
v = reflect.Indirect(v)
iType := v.Type()
if v.Kind() == reflect.Struct {
// Remove non-embedded controller methods
for i := 0; i < v.NumField(); i++ {
if iType.Field(i).Anonymous {
name := getControllerName(v.Field(i))
if !strings.HasSuffix(name, "Controller") {
for _, name := range getContrllerAllMethos(v.Field(i)) {
delete(names, name)
}
}
}
}
// Add embedded controller method
for i := 0; i < iType.NumField(); i++ {
if iType.Field(i).Anonymous {
name := getControllerName(v.Field(i))
if strings.HasSuffix(name, "Controller") {
for _, name := range getContrllerAllMethos(v.Field(i)) {
names[name] = ""
}
}
}
}
}
return names
}
// The getContrllerAllMethos function get the names of all methods whose types
// include pointer types.
func getContrllerAllMethos(v reflect.Value) []string {
iType := v.Type()
if iType.Kind() != reflect.Ptr {
iType = reflect.New(iType).Type()
}
names := make([]string, iType.NumMethod())
for i := 0; i < iType.NumMethod(); i++ {
names[i] = iType.Method(i).Name
}
return names
}
func getControllerName(v reflect.Value) string {
if v.Kind() == reflect.Ptr && v.IsNil() {
v = reflect.New(v.Type().Elem())
}
name := reflect.Indirect(v).Type().Name()
// typeParam name
pos := strings.IndexByte(name, '[')
if pos != -1 {
name = name[:pos]
}
return name
}
// The getRouteByName function generates a route using the function name.
func getRouteByName(name string) string {
names := splitTitleName(name)
if getMethodByName(names[0]) != "" {
names = names[1:]
}
name = ""
for i := 0; i < len(names); i++ {
if names[i] == "By" {
i++
if i == len(names) {
name += "/" + "*"
} else {
name = name + "/:" + names[i]
}
} else {
name = name + "/" + names[i]
}
}
if name == "" {
name = "/" + "*"
}
return strings.ToLower(name)
}
func getMethodByName(name string) string {
name = strings.ToUpper(getFirstUp(name))
if name == "ANY" {
return MethodAny
}
for _, method := range DefaultRouterAllMethod {
if method == name {
return name
}
}
return ""
}
func getFirstUp(name string) string {
for i, c := range name {
if 0x40 < c && c < 0x5B && i != 0 {
return name[:i]
}
}
return name
}
// The splitTitleName method splits the path based on the capitalization of
// the first character.
func splitTitleName(str string) []string {
var body []byte
for i := range str {
switch {
case i != 0 && byteIn(str[i], 0x40) && byteIn(str[i-1], 0x60):
body = append(body, ' ')
body = append(body, str[i])
case i != 0 && i != len(str)-1 && byteIn(str[i], 0x40) &&
byteIn(str[i-1], 0x40) && byteIn(str[i+1], 0x60):
body = append(body, ' ')
body = append(body, str[i])
case byteIn(str[i], 0x40) && i != 0:
body = append(body, str[i]+0x20)
default:
body = append(body, str[i])
}
}
return strings.Split(string(body), " ")
}
func byteIn(b byte, r byte) bool {
return r < b && b < r+0x1B
}