forked from gramework/gramework
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrouter.go
551 lines (490 loc) · 15.1 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
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
package gramework
import (
"fmt"
"time"
"github.com/valyala/fasthttp"
)
// JSON register internal handler that sets json content type
// and serves given handler with GET method
func (r *Router) JSON(route string, handler interface{}) *Router {
h := r.determineHandler(handler)
r.GET(route, jsonHandler(h))
return r
}
// GET registers a handler for a GET request to the given route
func (r *Router) GET(route string, handler interface{}) *Router {
r.Handle(MethodGET, route, handler)
return r
}
// Forbidden serves 403 on route it registered on
func (r *Router) Forbidden(ctx *Context) {
ctx.Forbidden()
}
// DELETE registers a handler for a DELETE request to the given route
func (r *Router) DELETE(route string, handler interface{}) *Router {
r.Handle(MethodDELETE, route, handler)
return r
}
// HEAD registers a handler for a HEAD request to the given route
func (r *Router) HEAD(route string, handler interface{}) *Router {
r.Handle(MethodHEAD, route, handler)
return r
}
// OPTIONS registers a handler for a OPTIONS request to the given route
func (r *Router) OPTIONS(route string, handler interface{}) *Router {
r.Handle(MethodOPTIONS, route, handler)
return r
}
// PUT registers a handler for a PUT request to the given route
func (r *Router) PUT(route string, handler interface{}) *Router {
r.Handle(MethodPUT, route, handler)
return r
}
// POST registers a handler for a POST request to the given route
func (r *Router) POST(route string, handler interface{}) *Router {
r.Handle(MethodPOST, route, handler)
return r
}
// PATCH registers a handler for a PATCH request to the given route
func (r *Router) PATCH(route string, handler interface{}) *Router {
r.Handle(MethodPATCH, route, handler)
return r
}
// ServeFile serves a file on a given route
func (r *Router) ServeFile(route, file string) *Router {
r.Handle(MethodGET, route, func(ctx *Context) {
ctx.SendFile(file)
})
return r
}
// SPAIndex serves an index file on any unregistered route
func (r *Router) SPAIndex(path string) *Router {
r.NotFound(func(ctx *Context) {
ctx.HTML()
ctx.SendFile(path)
})
return r
}
// Sub let you quickly register subroutes with given prefix
// like app.Sub("v1").GET("route", "hi"), that give you /v1/route
// registered
func (r *Router) Sub(path string) *SubRouter {
return &SubRouter{
prefix: path,
parent: r,
}
}
func (r *Router) handleReg(method, route string, handler interface{}) {
r.initRouter()
r.app.Logger.Debugf("registering %s %s", method, route)
r.router.Handle(method, route, r.determineHandler(handler))
}
func (r *Router) determineHandler(handler interface{}) func(*Context) {
switch h := handler.(type) {
case func(*Context):
return h
case RequestHandler:
return h
case func(*Context) error:
return r.getErrorHandler(h)
case func(*fasthttp.RequestCtx):
return r.getGrameHandler(h)
case func(*fasthttp.RequestCtx) error:
return r.getGrameErrorHandler(h)
case func() interface{}:
return r.getEfaceEncoder(h)
case func() (interface{}, error):
return r.getEfaceErrEncoder(h)
case func(*Context) interface{}:
return r.getEfaceCtxEncoder(h)
case func(*Context) (interface{}, error):
return r.getEfaceCtxErrEncoder(h)
case string:
return r.getStringServer(h)
case []byte:
return r.getBytesServer(h)
case int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64:
return r.getFmtDHandler(h)
case float32, float64:
return r.getFmtFHandler(h)
case func():
return r.getGrameDumbHandler(h)
case func() error:
return r.getGrameDumbErrorHandler(h)
case func() string:
return r.getEFuncStrHandler(h)
case func() map[string]interface{}:
return r.getHandlerEncoder(h)
case func(*Context) map[string]interface{}:
return r.getCtxHandlerEncoder(h)
case func() (map[string]interface{}, error):
return r.getHandlerEncoderErr(h)
case func(*Context) (map[string]interface{}, error):
return r.getCtxHandlerEncoderErr(h)
default:
r.app.Logger.Warnf("Unknown handler type: %T, serving fmt.Sprintf(%%v)", h)
return r.getFmtVHandler(h)
}
}
func (r *Router) getEFuncStrHandler(h func() string) func(*Context) {
return func(ctx *Context) {
ctx.WriteString(h())
}
}
// Handle registers a new request handle 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, route string, handler interface{}) *Router {
r.handleReg(method, route, handler)
return r
}
func (r *Router) getFmtVHandler(v interface{}) func(*Context) {
cache := []byte(fmt.Sprintf("%v", v))
return func(ctx *Context) {
ctx.Write(cache)
}
}
func (r *Router) getStringServer(str string) func(*Context) {
b := []byte(str)
return func(ctx *Context) {
ctx.Write(b)
}
}
func (r *Router) getBytesServer(b []byte) func(*Context) {
return func(ctx *Context) {
ctx.Write(b)
}
}
func (r *Router) getFmtDHandler(v interface{}) func(*Context) {
const fmtD = "%d"
return func(ctx *Context) {
fmt.Fprintf(ctx, fmtD, v)
}
}
func (r *Router) getFmtFHandler(v interface{}) func(*Context) {
const fmtF = "%f"
return func(ctx *Context) {
fmt.Fprintf(ctx, fmtF, v)
}
}
// PanicHandler set a handler for unhandled panics
func (r *Router) PanicHandler(panicHandler func(*Context, interface{})) {
r.initRouter()
r.router.PanicHandler = panicHandler
}
// NotFound set a handler which is called when no matching route is found
func (r *Router) NotFound(notFoundHandler func(*Context)) {
r.initRouter()
r.router.NotFound = notFoundHandler
}
// HandleMethodNotAllowed changes HandleMethodNotAllowed mode in the router
func (r *Router) HandleMethodNotAllowed(newValue bool) (oldValue bool) {
r.initRouter()
oldValue = r.router.HandleMethodNotAllowed
r.router.HandleMethodNotAllowed = newValue
return
}
// HandleOPTIONS changes HandleOPTIONS mode in the router
func (r *Router) HandleOPTIONS(newValue bool) (oldValue bool) {
r.initRouter()
oldValue = r.router.HandleOPTIONS
r.router.HandleOPTIONS = newValue
return
}
// ServeDir from a given path
func (app *App) ServeDir(path string) func(*Context) {
return app.ServeDirCustom(path, 0, true, false, []string{"index.html", "index.htm"})
}
// ServeDirCustom gives you ability to serve a dir with custom settings
func (app *App) ServeDirCustom(path string, stripSlashes int, compress bool, generateIndexPages bool, indexNames []string) func(*Context) {
if indexNames == nil {
indexNames = []string{}
}
fs := &fasthttp.FS{
Root: path,
IndexNames: indexNames,
GenerateIndexPages: generateIndexPages,
Compress: compress,
CacheDuration: 5 * time.Minute,
CompressedFileSuffix: ".gz",
}
if stripSlashes > 0 {
fs.PathRewrite = fasthttp.NewPathSlashesStripper(stripSlashes)
}
h := fs.NewRequestHandler()
return func(ctx *Context) {
h(ctx.RequestCtx)
}
}
// ServeDirNoCache gives you ability to serve a dir without caching
func (app *App) ServeDirNoCache(path string) func(*Context) {
return app.ServeDirNoCacheCustom(path, 0, true, false, nil)
}
// ServeDirNoCacheCustom gives you ability to serve a dir with custom settings without caching
func (app *App) ServeDirNoCacheCustom(path string, stripSlashes int, compress bool, generateIndexPages bool, indexNames []string) func(*Context) {
if indexNames == nil {
indexNames = []string{}
}
fs := &fasthttp.FS{
Root: path,
IndexNames: indexNames,
GenerateIndexPages: generateIndexPages,
Compress: compress,
CacheDuration: time.Millisecond,
CompressedFileSuffix: ".gz",
}
if stripSlashes > 0 {
fs.PathRewrite = fasthttp.NewPathSlashesStripper(stripSlashes)
}
h := fs.NewRequestHandler()
pragmaH := "Pragma"
pragmaV := "no-cache"
expiresH := "Expires"
expiresV := "0"
ccH := "Cache-Control"
ccV := "no-cache, no-store, must-revalidate"
return func(ctx *Context) {
ctx.Response.Header.Add(pragmaH, pragmaV)
ctx.Response.Header.Add(expiresH, expiresV)
ctx.Response.Header.Add(ccH, ccV)
h(ctx.RequestCtx)
}
}
// HTTP router returns a router instance that work only on HTTP requests
func (r *Router) HTTP() *Router {
if r.root != nil {
return r.root.HTTP()
}
r.mu.Lock()
if r.httprouter == nil {
r.httprouter = &Router{
router: newRouter(),
app: r.app,
root: r,
}
}
r.mu.Unlock()
return r.httprouter
}
// HTTPS router returns a router instance that work only on HTTPS requests
func (r *Router) HTTPS() *Router {
if r.root != nil {
return r.root.HTTPS()
}
r.mu.Lock()
if r.httpsrouter == nil {
r.httpsrouter = &Router{
router: newRouter(),
app: r.app,
root: r,
}
}
r.mu.Unlock()
return r.httpsrouter
}
// ServeFiles serves files from the given file system root.
// 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 http.FileServer is used, therefore http.NotFound is used instead
// of the Router's NotFound handler.
// router.ServeFiles("/src/*filepath", "/var/www")
func (r *Router) ServeFiles(path string, rootPath string) {
r.router.ServeFiles(path, rootPath)
}
// 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 handle function and the path parameter
// values. Otherwise the third 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 *Context) (RequestHandler, bool) {
return r.router.Lookup(method, path, ctx)
}
// MethodNotAllowed sets MethodNotAllowed handler
func (r *Router) MethodNotAllowed(c func(ctx *Context)) {
r.router.MethodNotAllowed = c
}
// Allowed returns Allow header's value used in OPTIONS responses
func (r *Router) Allowed(path, reqMethod string) (allow string) {
return r.router.Allowed(path, reqMethod)
}
// Handler makes the router implement the fasthttp.ListenAndServe interface.
func (r *Router) Handler() func(*Context) {
return func(ctx *Context) {
path := string(ctx.Path())
method := string(ctx.Method())
switch ctx.IsTLS() {
case true:
if r.httpsrouter != nil {
handler, rts := r.httpsrouter.router.Lookup(method, path, ctx)
if handler != nil && r.httpsrouter.handle(path, method, ctx, handler, rts, false) {
return
}
if r.httpsrouter.router.RedirectFixedPath {
if root, ok := r.httpsrouter.router.Trees[method]; ok && root != nil {
fixedPath, found := root.FindCaseInsensitivePath(
CleanPath(path),
r.httpsrouter.router.RedirectTrailingSlash,
)
if found {
code := redirectCode
if method != GET {
code = temporaryRedirectCode
}
ctx.SetStatusCode(code)
ctx.Response.Header.AddBytesV("Location", fixedPath)
return
}
}
}
if r.httpsrouter.router.NotFound != nil {
r.httpsrouter.router.NotFound(ctx)
return
}
}
case false:
if r.httprouter != nil {
handler, rts := r.httprouter.router.Lookup(method, path, ctx)
if handler != nil && r.httprouter.handle(path, method, ctx, handler, rts, false) {
return
}
if r.httprouter.router.RedirectFixedPath {
if root, ok := r.httprouter.router.Trees[method]; ok && root != nil {
fixedPath, found := root.FindCaseInsensitivePath(
CleanPath(path),
r.httprouter.router.RedirectTrailingSlash,
)
if found {
code := redirectCode
if method != GET {
code = temporaryRedirectCode
}
ctx.SetStatusCode(code)
ctx.Response.Header.AddBytesV("Location", fixedPath)
return
}
}
}
if r.httprouter.router.NotFound != nil {
r.httprouter.router.NotFound(ctx)
return
}
}
}
handler, rts := r.router.Lookup(method, path, ctx)
if r.handle(path, method, ctx, handler, rts, true) {
return
}
if r.router.RedirectFixedPath {
if root, ok := r.router.Trees[method]; ok && root != nil {
fixedPath, found := root.FindCaseInsensitivePath(
CleanPath(path),
r.router.RedirectTrailingSlash,
)
if found && len(fixedPath) > 0 {
code := redirectCode
if method != GET {
code = temporaryRedirectCode
}
ctx.SetStatusCode(code)
ctx.Response.Header.AddBytesV("Location", fixedPath)
return
}
}
}
if r.router.NotFound != nil {
r.router.NotFound(ctx)
return
}
ctx.Error(fasthttp.StatusMessage(fasthttp.StatusNotFound), fasthttp.StatusNotFound)
}
}
func (r *Router) handle(path, method string, ctx *Context, handler func(ctx *Context), redirectTrailingSlashs bool, isRootRouter bool) (handlerFound bool) {
if r.router.PanicHandler != nil {
defer r.router.Recv(ctx)
}
if root := r.router.Trees[method]; root != nil {
if f, tsr := root.GetValue(path, ctx, string(ctx.Method())); f != nil {
f(ctx)
return true
} else if method != CONNECT && path != PathSlash {
code := redirectCode // Permanent redirect, request with GET method
if method != GET {
// Temporary redirect, request with same method
// As of Go 1.3, Go does not support status code 308.
code = temporaryRedirectCode
}
if tsr && r.router.RedirectTrailingSlash {
var uri string
if len(path) > one && path[len(path)-one] == SlashByte {
uri = path[:len(path)-one]
} else {
uri = path + PathSlash
}
if uri != emptyString {
ctx.SetStatusCode(code)
ctx.Response.Header.Add("Location", uri)
}
return false
}
// Try to fix the request path
if r.router.RedirectFixedPath {
fixedPath, found := root.FindCaseInsensitivePath(
CleanPath(path),
r.router.RedirectTrailingSlash,
)
if found && len(fixedPath) > 0 {
queryBuf := ctx.URI().QueryString()
if len(queryBuf) > zero {
fixedPath = append(fixedPath, QuestionMark...)
fixedPath = append(fixedPath, queryBuf...)
}
uri := string(fixedPath)
ctx.SetStatusCode(code)
ctx.Response.Header.Add("Location", uri)
return true
}
}
}
}
if !isRootRouter {
return false
}
if method == OPTIONS {
// Handle OPTIONS requests
if r.router.HandleOPTIONS {
if allow := r.router.Allowed(path, method); len(allow) > zero {
ctx.Response.Header.Set(HeaderAllow, allow)
return true
}
}
} else {
// Handle 405
if r.router.HandleMethodNotAllowed {
if allow := r.router.Allowed(path, method); len(allow) > zero {
ctx.Response.Header.Set(HeaderAllow, allow)
if r.router.MethodNotAllowed != nil {
r.router.MethodNotAllowed(ctx)
} else {
ctx.SetStatusCode(fasthttp.StatusMethodNotAllowed)
ctx.SetContentTypeBytes(DefaultContentType)
ctx.SetBodyString(fasthttp.StatusMessage(fasthttp.StatusMethodNotAllowed))
}
return true
}
}
}
return false
}
// Redir sends 301 redirect to the given url
//
// it's equivalent to
//
// ctx.Redirect(url, 301)
func (r *Router) Redir(route, url string) {
r.GET(route, func(ctx *Context) {
ctx.Redirect(route, redirectCode)
})
}