-
Notifications
You must be signed in to change notification settings - Fork 47
/
router.go
494 lines (419 loc) · 13.4 KB
/
router.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
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
package router
import (
"fmt"
"io/fs"
"strings"
"github.com/fasthttp/router/radix"
"github.com/savsgio/gotils/bytes"
"github.com/savsgio/gotils/strconv"
"github.com/valyala/bytebufferpool"
"github.com/valyala/fasthttp"
)
// MethodWild wild HTTP method
const MethodWild = "*"
var (
questionMark = byte('?')
// MatchedRoutePathParam is the param name under which the path of the matched
// route is stored, if Router.SaveMatchedRoutePath is set.
MatchedRoutePathParam = fmt.Sprintf("__matchedRoutePath::%s__", bytes.Rand(make([]byte, 15)))
)
// New returns a new router.
// Path auto-correction, including trailing slashes, is enabled by default.
func New() *Router {
return &Router{
trees: make([]*radix.Tree, 10),
customMethodsIndex: make(map[string]int),
registeredPaths: make(map[string][]string),
RedirectTrailingSlash: true,
RedirectFixedPath: true,
HandleMethodNotAllowed: true,
HandleOPTIONS: true,
}
}
// Group returns a new group.
// Path auto-correction, including trailing slashes, is enabled by default.
func (r *Router) Group(path string) *Group {
validatePath(path)
if path != "/" && strings.HasSuffix(path, "/") {
panic("group path must not end with a trailing slash")
}
return &Group{
router: r,
prefix: path,
}
}
func (r *Router) saveMatchedRoutePath(path string, handler fasthttp.RequestHandler) fasthttp.RequestHandler {
return func(ctx *fasthttp.RequestCtx) {
ctx.SetUserValue(MatchedRoutePathParam, path)
handler(ctx)
}
}
func (r *Router) methodIndexOf(method string) int {
switch method {
case fasthttp.MethodGet:
return 0
case fasthttp.MethodHead:
return 1
case fasthttp.MethodPost:
return 2
case fasthttp.MethodPut:
return 3
case fasthttp.MethodPatch:
return 4
case fasthttp.MethodDelete:
return 5
case fasthttp.MethodConnect:
return 6
case fasthttp.MethodOptions:
return 7
case fasthttp.MethodTrace:
return 8
case MethodWild:
return 9
}
if i, ok := r.customMethodsIndex[method]; ok {
return i
}
return -1
}
// Mutable allows updating the route handler
//
// # It's disabled by default
//
// WARNING: Use with care. It could generate unexpected behaviours
func (r *Router) Mutable(v bool) {
r.treeMutable = v
for i := range r.trees {
tree := r.trees[i]
if tree != nil {
tree.Mutable = v
}
}
}
// List returns all registered routes grouped by method
func (r *Router) List() map[string][]string {
return r.registeredPaths
}
// GET is a shortcut for router.Handle(fasthttp.MethodGet, path, handler)
func (r *Router) GET(path string, handler fasthttp.RequestHandler) {
r.Handle(fasthttp.MethodGet, path, handler)
}
// HEAD is a shortcut for router.Handle(fasthttp.MethodHead, path, handler)
func (r *Router) HEAD(path string, handler fasthttp.RequestHandler) {
r.Handle(fasthttp.MethodHead, path, handler)
}
// POST is a shortcut for router.Handle(fasthttp.MethodPost, path, handler)
func (r *Router) POST(path string, handler fasthttp.RequestHandler) {
r.Handle(fasthttp.MethodPost, path, handler)
}
// PUT is a shortcut for router.Handle(fasthttp.MethodPut, path, handler)
func (r *Router) PUT(path string, handler fasthttp.RequestHandler) {
r.Handle(fasthttp.MethodPut, path, handler)
}
// PATCH is a shortcut for router.Handle(fasthttp.MethodPatch, path, handler)
func (r *Router) PATCH(path string, handler fasthttp.RequestHandler) {
r.Handle(fasthttp.MethodPatch, path, handler)
}
// DELETE is a shortcut for router.Handle(fasthttp.MethodDelete, path, handler)
func (r *Router) DELETE(path string, handler fasthttp.RequestHandler) {
r.Handle(fasthttp.MethodDelete, path, handler)
}
// CONNECT is a shortcut for router.Handle(fasthttp.MethodConnect, path, handler)
func (r *Router) CONNECT(path string, handler fasthttp.RequestHandler) {
r.Handle(fasthttp.MethodConnect, path, handler)
}
// OPTIONS is a shortcut for router.Handle(fasthttp.MethodOptions, path, handler)
func (r *Router) OPTIONS(path string, handler fasthttp.RequestHandler) {
r.Handle(fasthttp.MethodOptions, path, handler)
}
// TRACE is a shortcut for router.Handle(fasthttp.MethodTrace, path, handler)
func (r *Router) TRACE(path string, handler fasthttp.RequestHandler) {
r.Handle(fasthttp.MethodTrace, path, handler)
}
// ANY is a shortcut for router.Handle(router.MethodWild, path, handler)
//
// WARNING: Use only for routes where the request method is not important
func (r *Router) ANY(path string, handler fasthttp.RequestHandler) {
r.Handle(MethodWild, path, handler)
}
// ServeFiles serves files from the given file system root path.
// The path must end with "/{filepath:*}", files are then served from the local
// path /defined/root/dir/{filepath:*}.
// For example if root is "/etc" and {filepath:*} is "passwd", the local file
// "/etc/passwd" would be served.
// Internally a fasthttp.FSHandler is used, therefore fasthttp.NotFound is used instead
// Use:
//
// router.ServeFiles("/src/{filepath:*}", "./")
func (r *Router) ServeFiles(path string, rootPath string) {
r.ServeFilesCustom(path, &fasthttp.FS{
Root: rootPath,
IndexNames: []string{"index.html"},
GenerateIndexPages: true,
AcceptByteRange: true,
})
}
// ServeFS serves files from the given file system.
// The path must end with "/{filepath:*}", files are then served from the local
// path /defined/root/dir/{filepath:*}.
// For example if root is "/etc" and {filepath:*} is "passwd", the local file
// "/etc/passwd" would be served.
// Internally a fasthttp.FSHandler is used, therefore fasthttp.NotFound is used instead
// Use:
//
// router.ServeFS("/src/{filepath:*}", myFilesystem)
func (r *Router) ServeFS(path string, filesystem fs.FS) {
r.ServeFilesCustom(path, &fasthttp.FS{
FS: filesystem,
Root: "",
AllowEmptyRoot: true,
GenerateIndexPages: true,
AcceptByteRange: true,
Compress: true,
CompressBrotli: true,
})
}
// ServeFilesCustom serves files from the given file system settings.
// The path must end with "/{filepath:*}", files are then served from the local
// path /defined/root/dir/{filepath:*}.
// For example if root is "/etc" and {filepath:*} is "passwd", the local file
// "/etc/passwd" would be served.
// Internally a fasthttp.FSHandler is used, therefore http.NotFound is used instead
// of the Router's NotFound handler.
// Use:
//
// router.ServeFilesCustom("/src/{filepath:*}", *customFS)
func (r *Router) ServeFilesCustom(path string, fs *fasthttp.FS) {
const suffix = "/{filepath:*}"
if !strings.HasSuffix(path, suffix) {
panic("path must end with " + suffix + " in path '" + path + "'")
}
prefix := path[:len(path)-len(suffix)]
stripSlashes := strings.Count(prefix, "/")
if fs.PathRewrite == nil && stripSlashes > 0 {
fs.PathRewrite = fasthttp.NewPathSlashesStripper(stripSlashes)
}
fileHandler := fs.NewRequestHandler()
r.GET(path, fileHandler)
}
// Handle registers a new request handler with the given path and method.
//
// For GET, POST, PUT, PATCH and DELETE requests the respective shortcut
// functions can be used.
//
// This function is intended for bulk loading and to allow the usage of less
// frequently used, non-standardized or custom methods (e.g. for internal
// communication with a proxy).
func (r *Router) Handle(method, path string, handler fasthttp.RequestHandler) {
switch {
case len(method) == 0:
panic("method must not be empty")
case handler == nil:
panic("handler must not be nil")
default:
validatePath(path)
}
r.registeredPaths[method] = append(r.registeredPaths[method], path)
methodIndex := r.methodIndexOf(method)
if methodIndex == -1 {
tree := radix.New()
tree.Mutable = r.treeMutable
r.trees = append(r.trees, tree)
methodIndex = len(r.trees) - 1
r.customMethodsIndex[method] = methodIndex
}
tree := r.trees[methodIndex]
if tree == nil {
tree = radix.New()
tree.Mutable = r.treeMutable
r.trees[methodIndex] = tree
r.globalAllowed = r.allowed("*", "")
}
if r.SaveMatchedRoutePath {
handler = r.saveMatchedRoutePath(path, handler)
}
optionalPaths := getOptionalPaths(path)
// if not has optional paths, adds the original
if len(optionalPaths) == 0 {
tree.Add(path, handler)
} else {
for _, p := range optionalPaths {
tree.Add(p, handler)
}
}
}
// Lookup allows the manual lookup of a method + path combo.
// This is e.g. useful to build a framework around this router.
// If the path was found, it returns the handler function.
// Otherwise the second return value indicates whether a redirection to
// the same path with an extra / without the trailing slash should be performed.
func (r *Router) Lookup(method, path string, ctx *fasthttp.RequestCtx) (fasthttp.RequestHandler, bool) {
methodIndex := r.methodIndexOf(method)
if methodIndex == -1 {
return nil, false
}
if tree := r.trees[methodIndex]; tree != nil {
handler, tsr := tree.Get(path, ctx)
if handler != nil || tsr {
return handler, tsr
}
}
if tree := r.trees[r.methodIndexOf(MethodWild)]; tree != nil {
return tree.Get(path, ctx)
}
return nil, false
}
func (r *Router) recv(ctx *fasthttp.RequestCtx) {
if rcv := recover(); rcv != nil {
r.PanicHandler(ctx, rcv)
}
}
func (r *Router) allowed(path, reqMethod string) (allow string) {
allowed := make([]string, 0, 9)
if path == "*" || path == "/*" { // server-wide{ // server-wide
// empty method is used for internal calls to refresh the cache
if reqMethod == "" {
for method := range r.registeredPaths {
if method == fasthttp.MethodOptions {
continue
}
// Add request method to list of allowed methods
allowed = append(allowed, method)
}
} else {
return r.globalAllowed
}
} else { // specific path
for method := range r.registeredPaths {
// Skip the requested method - we already tried this one
if method == reqMethod || method == fasthttp.MethodOptions {
continue
}
handle, _ := r.trees[r.methodIndexOf(method)].Get(path, nil)
if handle != nil {
// Add request method to list of allowed methods
allowed = append(allowed, method)
}
}
}
if len(allowed) > 0 {
// Add request method to list of allowed methods
allowed = append(allowed, fasthttp.MethodOptions)
// Sort allowed methods.
// sort.Strings(allowed) unfortunately causes unnecessary allocations
// due to allowed being moved to the heap and interface conversion
for i, l := 1, len(allowed); i < l; i++ {
for j := i; j > 0 && allowed[j] < allowed[j-1]; j-- {
allowed[j], allowed[j-1] = allowed[j-1], allowed[j]
}
}
// return as comma separated list
return strings.Join(allowed, ", ")
}
return
}
func (r *Router) tryRedirect(ctx *fasthttp.RequestCtx, tree *radix.Tree, tsr bool, method, path string) bool {
// Moved Permanently, request with GET method
code := fasthttp.StatusMovedPermanently
if method != fasthttp.MethodGet {
// Permanent Redirect, request with same method
code = fasthttp.StatusPermanentRedirect
}
if tsr && r.RedirectTrailingSlash {
uri := bytebufferpool.Get()
if len(path) > 1 && path[len(path)-1] == '/' {
uri.SetString(path[:len(path)-1])
} else {
uri.SetString(path)
uri.WriteByte('/')
}
if queryBuf := ctx.URI().QueryString(); len(queryBuf) > 0 {
uri.WriteByte(questionMark)
uri.Write(queryBuf)
}
ctx.Redirect(uri.String(), code)
bytebufferpool.Put(uri)
return true
}
// Try to fix the request path
if r.RedirectFixedPath {
path2 := strconv.B2S(ctx.Request.URI().Path())
uri := bytebufferpool.Get()
found := tree.FindCaseInsensitivePath(
cleanPath(path2),
r.RedirectTrailingSlash,
uri,
)
if found {
if queryBuf := ctx.URI().QueryString(); len(queryBuf) > 0 {
uri.WriteByte(questionMark)
uri.Write(queryBuf)
}
ctx.Redirect(uri.String(), code)
bytebufferpool.Put(uri)
return true
}
bytebufferpool.Put(uri)
}
return false
}
// Handler makes the router implement the http.Handler interface.
func (r *Router) Handler(ctx *fasthttp.RequestCtx) {
if r.PanicHandler != nil {
defer r.recv(ctx)
}
path := strconv.B2S(ctx.Request.URI().PathOriginal())
method := strconv.B2S(ctx.Request.Header.Method())
methodIndex := r.methodIndexOf(method)
if methodIndex > -1 {
if tree := r.trees[methodIndex]; tree != nil {
if handler, tsr := tree.Get(path, ctx); handler != nil {
handler(ctx)
return
} else if method != fasthttp.MethodConnect && path != "/" {
if ok := r.tryRedirect(ctx, tree, tsr, method, path); ok {
return
}
}
}
}
// Try to search in the wild method tree
if tree := r.trees[r.methodIndexOf(MethodWild)]; tree != nil {
if handler, tsr := tree.Get(path, ctx); handler != nil {
handler(ctx)
return
} else if method != fasthttp.MethodConnect && path != "/" {
if ok := r.tryRedirect(ctx, tree, tsr, method, path); ok {
return
}
}
}
if r.HandleOPTIONS && method == fasthttp.MethodOptions {
// Handle OPTIONS requests
if allow := r.allowed(path, fasthttp.MethodOptions); allow != "" {
ctx.Response.Header.Set("Allow", allow)
if r.GlobalOPTIONS != nil {
r.GlobalOPTIONS(ctx)
}
return
}
} else if r.HandleMethodNotAllowed {
// Handle 405
if allow := r.allowed(path, method); allow != "" {
ctx.Response.Header.Set("Allow", allow)
if r.MethodNotAllowed != nil {
r.MethodNotAllowed(ctx)
} else {
ctx.SetStatusCode(fasthttp.StatusMethodNotAllowed)
ctx.SetBodyString(fasthttp.StatusMessage(fasthttp.StatusMethodNotAllowed))
}
return
}
}
// Handle 404
if r.NotFound != nil {
r.NotFound(ctx)
} else {
ctx.Error(fasthttp.StatusMessage(fasthttp.StatusNotFound), fasthttp.StatusNotFound)
}
}