forked from savsgio/atreugo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
router.go
402 lines (325 loc) · 10.8 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
package atreugo
import (
"net/http"
"sort"
"strings"
fastrouter "github.com/fasthttp/router"
logger "github.com/savsgio/go-logger/v2"
"github.com/savsgio/gotils"
"github.com/valyala/fasthttp"
"github.com/valyala/fasthttp/fasthttpadaptor"
)
func defaultErrorView(ctx *RequestCtx, err error, statusCode int) {
ctx.Error(err.Error(), statusCode)
}
func emptyView(ctx *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 || !gotils.StringSliceInclude(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(log *logger.Logger, errorView ErrorView) *Router {
if errorView == nil {
errorView = defaultErrorView
}
router := fastrouter.New()
router.HandleOPTIONS = false
return &Router{
router: router,
handleOPTIONS: true,
errorView: errorView,
log: log,
}
}
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...)
switch {
case r.parent != nil:
return r.parent.buildMiddlewares(m2)
case r.log.DebugEnabled():
debugMiddleware := func(ctx *RequestCtx) error {
r.log.Debugf("%s %s", ctx.Method(), ctx.URI())
return ctx.Next()
}
m2.Before = append([]Middleware{debugMiddleware}, m2.Before...)
}
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 := append(middle.Before, func(ctx *RequestCtx) error {
if !ctx.skipView {
if err := fn(ctx); err != nil {
return err
}
}
return ctx.Next()
})
chain = append(chain, middle.After...)
return func(ctx *fasthttp.RequestCtx) {
actx := AcquireRequestCtx(ctx)
for i := range chain {
if err := chain[i](actx); err != nil {
statusCode := actx.Response.StatusCode()
if statusCode == fasthttp.StatusOK {
statusCode = fasthttp.StatusInternalServerError
}
r.log.Error(err)
r.errorView(actx, err, statusCode)
break
} else if !actx.next {
break
}
actx.next = false
}
ReleaseRequestCtx(actx)
}
}
func (r *Router) handlePath(p *Path) {
isOPTIONS := p.method == fasthttp.MethodOptions
switch {
case p.registered:
r.mutable(true)
case isOPTIONS:
mutable := !gotils.StringSliceInclude(r.customOPTIONS, p.url)
r.mutable(mutable)
case r.routerMutable:
r.mutable(false)
}
view := p.view
if isOPTIONS {
view = buildOptionsView(p.url, view, r.ListPaths())
r.customOPTIONS = gotils.StringUniqueAppend(r.customOPTIONS, p.url)
}
handler := r.handler(view, p.middlewares)
if p.withTimeout {
handler = fasthttp.TimeoutWithCodeHandler(handler, p.timeout, p.timeoutMsg, p.timeoutCode)
}
r.router.Handle(p.method, p.url, handler)
if r.handleOPTIONS && !p.registered && !isOPTIONS {
view = buildOptionsView(p.url, emptyView, r.ListPaths())
handler = r.handler(view, p.middlewares)
r.mutable(true)
r.router.Handle(fasthttp.MethodOptions, p.url, handler)
}
}
// NewGroupPath returns a new router to group paths.
func (r *Router) NewGroupPath(path string) *Router {
return &Router{
parent: r,
prefix: path,
router: r.router,
routerMutable: r.routerMutable,
handleOPTIONS: r.handleOPTIONS,
errorView: r.errorView,
log: r.log,
}
}
// 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
}
// 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
//
// 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,
})
}
// 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 {
if strings.HasSuffix(url, "/") {
url = url[:len(url)-1]
}
ffs := &fasthttp.FS{
Root: fs.Root,
IndexNames: fs.IndexNames,
GenerateIndexPages: fs.GenerateIndexPages,
Compress: fs.Compress,
AcceptByteRange: fs.AcceptByteRange,
CacheDuration: fs.CacheDuration,
CompressedFileSuffix: fs.CompressedFileSuffix,
}
if fs.PathNotFound != nil {
ffs.PathNotFound = viewToHandler(fs.PathNotFound, r.errorView)
}
if fs.PathRewrite != nil {
ffs.PathRewrite = func(ctx *fasthttp.RequestCtx) []byte {
actx := AcquireRequestCtx(ctx)
result := fs.PathRewrite(actx)
ReleaseRequestCtx(actx)
return result
}
}
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) {
panic("The http method '" + method + "' must be in uppercase")
}
p := &Path{
router: r,
method: method,
url: r.getGroupFullPath(url),
view: viewFn,
}
r.handlePath(p)
p.registered = true
return p
}