-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathroutermux.go
432 lines (398 loc) · 10.3 KB
/
routermux.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
424
425
426
427
428
429
430
431
432
package eudore
// Implementing a full-featured [RouterCore] based on radix tree
import (
"context"
"fmt"
"strings"
)
// routerCoreMux is implemented based on the radix tree to realize registration
// and matching of all routers.
type routerCoreMux struct {
Root *nodeMux
AnyMethods []string
AllMethods []string
Params404 Params
Params405 Params
Handler404 []HandlerFunc
Handler405 []HandlerFunc
funcCreator FuncCreator
}
type nodeMux struct {
path string
name string
route string
childc []*nodeMux
childpv []*nodeMux
childp []*nodeMux
childwv []*nodeMux
childw *nodeMux
check func(string) bool
// handlers
handlers []nodeMuxHandler
anyHandler []HandlerFunc
anyParams Params
}
type nodeMuxHandler struct {
method string
params Params
funcs []HandlerFunc
}
// The NewRouterCoreMux function creates the [RouterCore] implemented by radix.
//
// The [DefaultRouterAnyMethod] [DefaultRouterAllMethod] data will be copied
// when created.
func NewRouterCoreMux() RouterCore {
return &routerCoreMux{
Root: &nodeMux{},
AnyMethods: append([]string{}, DefaultRouterAnyMethod...),
AllMethods: append([]string{}, DefaultRouterAllMethod...),
Handler404: []HandlerFunc{HandlerRouter404},
Handler405: []HandlerFunc{HandlerRouter405},
funcCreator: DefaultFuncCreator,
}
}
// The Mount method get [ContextKeyFuncCreator] from [context.Context] to
// create a verification function.
//
// You can make the validation constructor implement the CreateFunc method
// of [FuncCreator].
func (mux *routerCoreMux) Mount(ctx context.Context) {
fc, ok := ctx.Value(ContextKeyFuncCreator).(FuncCreator)
if ok {
mux.funcCreator = fc
}
}
// HandleFunc method register a new route to the router
//
// The router matches the handlers available to the current path from
// the middleware tree and adds them to the front of the handler.
func (mux *routerCoreMux) HandleFunc(method string, path string,
handler []HandlerFunc,
) {
// Keep the handler as nil behavior,
// ignore and do not recommend using nil hander.
if handler == nil {
return
}
switch method {
case "NOTFOUND", "404":
mux.Params404 = NewParamsRoute(path)[2:]
mux.Handler404 = handler
case "METHODNOTALLOWED", "405":
mux.Params405 = NewParamsRoute(path)[2:]
mux.Handler405 = handler
case MethodAny:
mux.insertRoute(method, path, handler)
default:
for _, m := range mux.AllMethods {
if method == m {
mux.insertRoute(method, path, handler)
return
}
}
}
}
// Match a request, if the method does not allow direct return to node405,
// no match returns node404.
func (mux *routerCoreMux) Match(method, path string, params *Params,
) []HandlerFunc {
node := mux.Root.lookNode(path, params)
// 404
if node == nil {
*params = params.Add(mux.Params404...)
return mux.Handler404
}
// no-any method
params.Set(ParamRoute, node.route)
for _, h := range node.handlers {
if h.method == method {
*params = params.Add(h.params...)
return h.funcs
}
}
// any method
if node.anyHandler != nil {
for _, m := range mux.AnyMethods {
if m == method {
*params = params.Add(node.anyParams...)
return node.anyHandler
}
}
}
// 405
allow := strings.Join(mux.getAllows(node), ", ")
*params = params.Add(ParamAllow, allow).Add(mux.Params405...)
return mux.Handler405
}
func (mux *routerCoreMux) getAllows(node *nodeMux) []string {
if node.handlers == nil {
return mux.AnyMethods
}
methods := make([]string, len(node.handlers))
for i, h := range node.handlers {
methods[i] = h.method
}
return methods
}
// Add a new route Node.
func (mux *routerCoreMux) insertRoute(method, path string, val []HandlerFunc) {
node := mux.Root
params := NewParamsRoute(path)
paths := getSplitPath(params.Get(ParamRoute))
// create a node
for _, route := range paths {
next := &nodeMux{path: route}
switch route[0] {
case ':', '*':
next.name, next.check = mux.loadNameAndCheck(route)
}
node = node.insertNode(next)
if route[0] == '*' {
break
}
}
node.route = strings.Join(paths, "")
node.setHandler(method, params[2:], val)
}
// Load the checksum function by name.
func (mux *routerCoreMux) loadNameAndCheck(path string) (string,
func(string) bool,
) {
if len(path) == 1 {
return path, nil
}
path = path[1:]
// Cutting verification function name and parameter
name, fname, _ := strings.Cut(path, "|")
if name == "" || fname == "" {
return path, nil
}
// If the prefix is '^', add the regular check function name
if fname[0] == '^' && fname[len(fname)-1] == '$' {
fname = "regexp:" + fname
}
// use [FuncCreator] to create a check function
fn, err := mux.funcCreator.CreateFunc(FuncCreateString, fname)
if err != nil {
panic(fmt.Errorf(ErrRouterMuxLoadInvalidFunc, path, err))
}
return name, fn.(func(string) bool)
}
func (node *nodeMux) setHandler(method string, params Params,
handler []HandlerFunc,
) {
if method == MethodAny {
node.anyHandler = handler
node.anyParams = params
return
}
for i, h := range node.handlers {
if h.method == method {
node.handlers[i].params = params
node.handlers[i].funcs = handler
return
}
}
node.handlers = append(node.handlers, nodeMuxHandler{
method, params, handler,
})
}
// insertNode add a child node to the node.
func (node *nodeMux) insertNode(next *nodeMux) *nodeMux {
switch {
case next.name == "": // const
return node.insertNodeConst(next)
case next.path[0] == ':': // param
if next.check == nil { // param verification
node.childp, next = nodeMuxSetNext(node.childp, next)
} else {
node.childpv, next = nodeMuxSetNext(node.childpv, next)
// If node.childp is empty,
// the variable phase will be skipped lookNode.
if node.childp == nil {
node.childp = make([]*nodeMux, 0)
}
}
case next.path[0] == '*': // wildcard
if next.check != nil { // wildcard verification
node.childwv, next = nodeMuxSetNext(node.childwv, next)
return next
}
// Copy next data and keep the original child info of node.childw.
if node.childw != nil {
node.childw.path = next.path
node.childw.name = next.name
return node.childw
}
node.childw = next
}
return next
}
func nodeMuxSetNext(nodes []*nodeMux, next *nodeMux) ([]*nodeMux, *nodeMux) {
path := next.path
// check if the current node exists.
for _, node := range nodes {
if node.path == path {
return nodes, node
}
}
return append(nodes, next), next
}
// The insertNodeConst method handles adding constant nodes.
func (node *nodeMux) insertNodeConst(next *nodeMux) *nodeMux {
for i := range node.childc {
prefix, find := getSubsetPrefix(next.path, node.childc[i].path)
if find {
// Split node path
if len(prefix) != len(node.childc[i].path) {
node.childc[i].path = node.childc[i].path[len(prefix):]
node.childc[i] = &nodeMux{
path: prefix,
childc: []*nodeMux{node.childc[i]},
}
}
next.path = next.path[len(prefix):]
if next.path == "" {
return node.childc[i]
}
return node.childc[i].insertNode(next)
}
}
node.childc = append(node.childc, next)
// Constant node is sorted by first char.
for i := len(node.childc) - 1; i > 0; i-- {
if node.childc[i].path[0] < node.childc[i-1].path[0] {
node.childc[i], node.childc[i-1] = node.childc[i-1], node.childc[i]
}
}
return next
}
//nolint:cyclop,gocyclo,gocognit
func (node *nodeMux) lookNode(path string, params *Params) *nodeMux {
if path != "" {
// constant Node match
for _, child := range node.childc {
if child.path[0] >= path[0] {
length := len(child.path)
if len(path) >= length && path[:length] == child.path {
if n := child.lookNode(path[length:], params); n != nil {
return n
}
}
break
}
}
// parameter matching, Check if there is a parameter match
if node.childp != nil {
pos := strings.IndexByte(path, '/')
if pos == -1 {
pos = len(path)
}
current, next := path[:pos], path[pos:]
// check parameter matching
for _, child := range node.childpv {
if child.check(current) {
if n := child.lookNode(next, params); n != nil {
*params = params.Add(child.name, current)
return n
}
}
}
for _, child := range node.childp {
if n := child.lookNode(next, params); n != nil {
*params = params.Add(child.name, current)
return n
}
}
}
} else if node.route != "" {
// constant match, return data
return node
}
// wildcard valid node
for _, child := range node.childwv {
if child.check(path) {
*params = params.Add(child.name, path)
return child
}
}
// wildcard node
if node.childw != nil {
*params = params.Add(node.childw.name, path)
return node.childw
}
// can't match, return nil
return nil
}
/*
The string is cut according to the Node type, String path cutting example:
/ [/]
/api/note/ [/api/note/]
//api/* [//api/ *]
//api/*name [//api/ *name]
/api/get/ [/api/get/]
/api/get [/api/get]
/api/:get [/api/ :get]
/api/:get/* [/api/ :get / *]
{/api/**{}:get/*} [/api/**{ :get / *}]
/api/:name/info/* [/api/ :name /info/ *]
/api/:name|^\\d+$/info [/api/ :name|^\d+$ /info]
/api/*|{^0/api\\S+$} [/api/ *|^0/api\S+$]
/api/*|^\\$\\d+$ [/api/ *|^\$\d+$]
*/
func getSplitPath(path string) []string {
var strs []string
bytes := make([]byte, 0, 64)
var isblock, isconst bool
for _, b := range path {
// block pattern
if isblock {
if b == '}' {
if len(bytes) != 0 && bytes[len(bytes)-1] != '\\' {
isblock = false
continue
}
// escaping }
bytes = bytes[:len(bytes)-1]
}
bytes = append(bytes, string(b)...)
continue
}
switch b {
case '/':
// constant mode, creates a new string in non-constant mode
if !isconst {
isconst = true
strs = append(strs, string(bytes))
bytes = bytes[:0]
}
case ':', '*':
// variable pattern or wildcard pattern
isconst = false
strs = append(strs, string(bytes))
bytes = bytes[:0]
case '{':
isblock = true
continue
}
bytes = append(bytes, string(b)...)
}
strs = append(strs, string(bytes))
if strs[0] == "" {
strs = strs[1:]
}
return strs
}
// Get the largest common prefix of the two strings,
// return the largest common prefix and have the largest common prefix.
func getSubsetPrefix(str2, str1 string) (string, bool) {
if len(str2) < len(str1) {
str1, str2 = str2, str1
}
for i := range str1 {
if str1[i] != str2[i] {
return str1[:i], i > 0
}
}
return str1, true
}