-
-
Notifications
You must be signed in to change notification settings - Fork 72
/
router.go
445 lines (360 loc) · 12.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
package atreugo
import (
"io/fs"
"net/http"
"sort"
"strings"
fastrouter "github.com/fasthttp/router"
gstrings "github.com/savsgio/gotils/strings"
"github.com/valyala/fasthttp"
"github.com/valyala/fasthttp/fasthttpadaptor"
)
func defaultErrorView(ctx *RequestCtx, err error, statusCode int) {
ctx.Error(err.Error(), statusCode)
}
func emptyView(_ *RequestCtx) error {
return nil
}
func buildOptionsView(url string, fn View, paths map[string][]string) View {
allow := make([]string, 0)
for method, urls := range paths {
if method == fasthttp.MethodOptions || !gstrings.Include(urls, url) {
continue
}
allow = append(allow, method)
}
if len(allow) == 0 {
allow = append(allow, fasthttp.MethodOptions)
}
sort.Strings(allow)
allowValue := strings.Join(allow, ", ")
return func(ctx *RequestCtx) error {
ctx.Response.Header.Set(fasthttp.HeaderAllow, allowValue)
return fn(ctx)
}
}
func newRouter(cfg Config) *Router {
router := fastrouter.New()
router.HandleOPTIONS = false
return &Router{
router: router,
errorView: cfg.ErrorView,
handleOPTIONS: true,
}
}
func (r *Router) mutable(v bool) {
if v != r.routerMutable {
r.routerMutable = v
r.router.Mutable(v)
}
}
func (r *Router) buildMiddlewares(m Middlewares) Middlewares {
m2 := Middlewares{}
m2.Before = append(m2.Before, r.middlewares.Before...)
m2.Before = append(m2.Before, m.Before...)
m2.After = append(m2.After, m.After...)
m2.After = append(m2.After, r.middlewares.After...)
m2.Skip = append(m2.Skip, m.Skip...)
m2.Skip = append(m2.Skip, r.middlewares.Skip...)
m2.Final = append(m2.Final, m.Final...)
m2.Final = append(m2.Final, r.middlewares.Final...)
if r.parent != nil {
return r.parent.buildMiddlewares(m2)
}
m2.Before = appendMiddlewares(m2.Before[:0], m2.Before, m2.Skip...)
m2.After = appendMiddlewares(m2.After[:0], m2.After, m2.Skip...)
return m2
}
func (r *Router) getGroupFullPath(path string) string {
if r.parent != nil {
path = r.parent.getGroupFullPath(r.prefix + path)
}
return path
}
func (r *Router) handler(fn View, middle Middlewares) fasthttp.RequestHandler {
middle = r.buildMiddlewares(middle)
chain := make([]Middleware, 0)
chain = append(chain, middle.Before...)
chain = append(chain, func(ctx *RequestCtx) error {
if !ctx.skipView {
if err := fn(ctx); err != nil {
return err
}
}
return ctx.Next()
})
chain = append(chain, middle.After...)
chainLen := len(chain)
return func(ctx *fasthttp.RequestCtx) {
actx := AcquireRequestCtx(ctx)
for i := 0; i < chainLen; i++ {
if err := chain[i](actx); err != nil {
r.handleMiddlewareError(actx, err)
break
} else if !actx.next {
break
}
actx.next = false
}
for _, final := range middle.Final {
final(actx)
}
ReleaseRequestCtx(actx)
}
}
func (r *Router) handleMiddlewareError(ctx *RequestCtx, err error) {
statusCode := ctx.Response.Header.StatusCode()
if statusCode == fasthttp.StatusOK {
statusCode = fasthttp.StatusInternalServerError
}
r.errorView(ctx, err, statusCode)
}
func (r *Router) handlePath(p *Path) {
isOPTIONS := p.method == fasthttp.MethodOptions
switch {
case p.registered:
r.mutable(true)
case isOPTIONS:
mutable := !gstrings.Include(r.customOPTIONS, p.fullURL)
r.mutable(mutable)
case r.routerMutable:
r.mutable(false)
}
view := p.view
if isOPTIONS {
view = buildOptionsView(p.fullURL, view, r.ListPaths())
r.customOPTIONS = gstrings.UniqueAppend(r.customOPTIONS, p.fullURL)
}
handler := r.handler(view, p.middlewares)
if p.withTimeout {
handler = fasthttp.TimeoutWithCodeHandler(handler, p.timeout, p.timeoutMsg, p.timeoutCode)
}
handleFunc := r.router.Handle
if r.group != nil {
handleFunc = r.group.Handle
}
handleFunc(p.method, p.url, handler)
if r.handleOPTIONS && !p.registered && !isOPTIONS {
view = buildOptionsView(p.fullURL, emptyView, r.ListPaths())
handler = r.handler(view, p.middlewares)
r.mutable(true)
handleFunc(fasthttp.MethodOptions, p.url, handler)
}
}
// NewGroupPath returns a new router to group paths.
func (r *Router) NewGroupPath(path string) *Router {
groupFunc := r.router.Group
if r.group != nil {
groupFunc = r.group.Group
}
return &Router{
parent: r,
router: r.router,
routerMutable: r.routerMutable,
errorView: r.errorView,
prefix: path,
group: groupFunc(path),
handleOPTIONS: r.handleOPTIONS,
}
}
// ListPaths returns all registered routes grouped by method.
func (r *Router) ListPaths() map[string][]string {
return r.router.List()
}
// Middlewares defines the middlewares (before, after and skip) in the order in which you want to execute them
// for the view or group
//
// WARNING: The previous middlewares configuration could be overridden.
func (r *Router) Middlewares(middlewares Middlewares) *Router {
r.middlewares = middlewares
return r
}
// UseBefore registers the middlewares in the order in which you want to execute them
// before the execution of the view or group.
func (r *Router) UseBefore(fns ...Middleware) *Router {
r.middlewares.Before = append(r.middlewares.Before, fns...)
return r
}
// UseAfter registers the middlewares in the order in which you want to execute them
// after the execution of the view or group.
func (r *Router) UseAfter(fns ...Middleware) *Router {
r.middlewares.After = append(r.middlewares.After, fns...)
return r
}
// UseFinal registers the given middlewares to be executed in the order in which they are added,
// after the view or group has been executed. These middlewares will always be executed,
// even if a previous middleware or the view/group returned a response.
func (r *Router) UseFinal(fns ...FinalMiddleware) *Router {
r.middlewares.Final = append(r.middlewares.Final, fns...)
return r
}
// SkipMiddlewares registers the middlewares that you want to skip when executing the view or group.
func (r *Router) SkipMiddlewares(fns ...Middleware) *Router {
r.middlewares.Skip = append(r.middlewares.Skip, fns...)
return r
}
// GET shortcut for router.Path("GET", url, viewFn).
func (r *Router) GET(url string, viewFn View) *Path {
return r.Path(fasthttp.MethodGet, url, viewFn)
}
// HEAD shortcut for router.Path("HEAD", url, viewFn).
func (r *Router) HEAD(url string, viewFn View) *Path {
return r.Path(fasthttp.MethodHead, url, viewFn)
}
// OPTIONS shortcut for router.Path("OPTIONS", url, viewFn).
func (r *Router) OPTIONS(url string, viewFn View) *Path {
return r.Path(fasthttp.MethodOptions, url, viewFn)
}
// POST shortcut for router.Path("POST", url, viewFn).
func (r *Router) POST(url string, viewFn View) *Path {
return r.Path(fasthttp.MethodPost, url, viewFn)
}
// PUT shortcut for router.Path("PUT", url, viewFn).
func (r *Router) PUT(url string, viewFn View) *Path {
return r.Path(fasthttp.MethodPut, url, viewFn)
}
// PATCH shortcut for router.Path("PATCH", url, viewFn).
func (r *Router) PATCH(url string, viewFn View) *Path {
return r.Path(fasthttp.MethodPatch, url, viewFn)
}
// DELETE shortcut for router.Path("DELETE", url, viewFn).
func (r *Router) DELETE(url string, viewFn View) *Path {
return r.Path(fasthttp.MethodDelete, url, viewFn)
}
// ANY shortcut for router.Path("*", url, viewFn)
//
// WARNING: Use only for routes where the request method is not important.
func (r *Router) ANY(url string, viewFn View) *Path {
return r.Path(fastrouter.MethodWild, url, viewFn)
}
// RequestHandlerPath wraps fasthttp request handler to atreugo view and registers it to
// the given path and method.
func (r *Router) RequestHandlerPath(method, url string, handler fasthttp.RequestHandler) *Path {
viewFn := func(ctx *RequestCtx) error {
handler(ctx.RequestCtx)
return nil
}
return r.Path(method, url, viewFn)
}
// NetHTTPPath wraps net/http handler to atreugo view and registers it to
// the given path and method.
//
// While this function may be used for easy switching from net/http to fasthttp/atreugo,
// it has the following drawbacks comparing to using manually written fasthttp/atreugo,
// request handler:
//
// - A lot of useful functionality provided by fasthttp/atreugo is missing
// from net/http handler.
// - net/http -> fasthttp/atreugo handler conversion has some overhead,
// so the returned handler will be always slower than manually written
// fasthttp/atreugo handler.
//
// So it is advisable using this function only for quick net/http -> fasthttp
// switching. Then manually convert net/http handlers to fasthttp handlers.
// according to https://github.com/valyala/fasthttp#switching-from-nethttp-to-fasthttp.
func (r *Router) NetHTTPPath(method, url string, handler http.Handler) *Path {
h := fasthttpadaptor.NewFastHTTPHandler(handler)
return r.RequestHandlerPath(method, url, h)
}
// Static serves static files from the given file system root path.
//
// Make sure your program has enough 'max open files' limit aka
// 'ulimit -n' if root folder contains many files.
func (r *Router) Static(url, rootPath string) *Path {
return r.StaticCustom(url, &StaticFS{
Root: rootPath,
IndexNames: []string{"index.html"},
GenerateIndexPages: true,
AcceptByteRange: true,
})
}
// StaticFS serves static files from the given file system.
//
// Make sure your program has enough 'max open files' limit aka
// 'ulimit -n' if filesystem contains many files.
func (r *Router) StaticFS(url string, filesystem fs.FS) *Path {
return r.StaticCustom(url, &StaticFS{
FS: filesystem,
Root: "",
AllowEmptyRoot: true,
GenerateIndexPages: true,
Compress: true,
CompressBrotli: true,
AcceptByteRange: true,
})
}
// StaticCustom serves static files from the given file system settings
//
// Make sure your program has enough 'max open files' limit aka
// 'ulimit -n' if root folder contains many files.
func (r *Router) StaticCustom(url string, fs *StaticFS) *Path {
url = strings.TrimSuffix(url, "/")
ffs := &fasthttp.FS{
FS: fs.FS,
Root: fs.Root,
AllowEmptyRoot: fs.AllowEmptyRoot,
IndexNames: fs.IndexNames,
GenerateIndexPages: fs.GenerateIndexPages,
Compress: fs.Compress,
CompressBrotli: fs.CompressBrotli,
CompressRoot: fs.CompressRoot,
AcceptByteRange: fs.AcceptByteRange,
SkipCache: fs.SkipCache,
CacheDuration: fs.CacheDuration,
CompressedFileSuffix: fs.CompressedFileSuffix,
CompressedFileSuffixes: fs.CompressedFileSuffixes,
CleanStop: fs.CleanStop,
}
if fs.PathRewrite != nil {
ffs.PathRewrite = func(ctx *fasthttp.RequestCtx) []byte {
actx := AcquireRequestCtx(ctx)
result := fs.PathRewrite(actx)
ReleaseRequestCtx(actx)
return result
}
}
if fs.PathNotFound != nil {
ffs.PathNotFound = viewToHandler(fs.PathNotFound, r.errorView)
}
stripSlashes := strings.Count(r.getGroupFullPath(url), "/")
if ffs.PathRewrite == nil && stripSlashes > 0 {
ffs.PathRewrite = fasthttp.NewPathSlashesStripper(stripSlashes)
}
return r.RequestHandlerPath(fasthttp.MethodGet, url+"/{filepath:*}", ffs.NewRequestHandler())
}
// ServeFile returns HTTP response containing compressed file contents
// from the given path
//
// HTTP response may contain uncompressed file contents in the following cases:
//
// - Missing 'Accept-Encoding: gzip' request header.
// - No write access to directory containing the file.
//
// Directory contents is returned if path points to directory.
func (r *Router) ServeFile(url, filePath string) *Path {
viewFn := func(ctx *RequestCtx) error {
fasthttp.ServeFile(ctx.RequestCtx, filePath)
return nil
}
return r.Path(fasthttp.MethodGet, url, viewFn)
}
// Path registers a new view with the given path and method
//
// 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) Path(method, url string, viewFn View) *Path {
if method != strings.ToUpper(method) {
panicf("http method '%s' must be in uppercase", method)
}
p := &Path{
router: r,
method: method,
url: url,
fullURL: r.getGroupFullPath(url),
view: viewFn,
}
r.handlePath(p)
p.registered = true
return p
}