forked from gofiber/fiber
-
Notifications
You must be signed in to change notification settings - Fork 0
/
router.go
286 lines (270 loc) · 6.76 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
// ⚡️ Fiber is an Express inspired web framework written in Go with ☕️
// 🤖 Github Repository: https://github.com/gofiber/fiber
// 📌 API Documentation: https://docs.gofiber.io
package fiber
import (
"log"
"strings"
"time"
fasthttp "github.com/valyala/fasthttp"
)
// Route metadata
type Route struct {
// Internal fields
use bool // USE matches path prefixes
star bool // Path equals '*' or '/*'
root bool // Path equals '/'
parsed parsedParams // parsed contains parsed params segments
// External fields for ctx.Route() method
Path string // Registered route path
Method string // HTTP method
Params []string // Slice containing the params names
Handler func(*Ctx) // Ctx handler
}
func (app *App) nextRoute(ctx *Ctx) {
mINT := methodINT[ctx.method]
// Get stack length
lenr := len(app.routes[mINT]) - 1
// Loop over stack starting from previous index
for ctx.index < lenr {
// Increment stack index
ctx.index++
// Get *Route
route := app.routes[mINT][ctx.index]
// Check if it matches the request path
match, values := route.matchRoute(ctx.path)
// No match, continue
if !match {
continue
}
// Match! Set route and param values to Ctx
ctx.route = route
ctx.values = values
// Execute handler
route.Handler(ctx)
// Generate ETag if enabled
if app.Settings.ETag {
setETag(ctx, false)
}
return
}
// Send a 404 by default if no route is matched
if len(ctx.Fasthttp.Response.Body()) == 0 {
ctx.SendStatus(404)
}
}
func (r *Route) matchRoute(path string) (match bool, values []string) {
// Middleware routes allow prefix matches
if r.use {
// Match any path if wildcard and pass path as param
if r.star {
return true, []string{path}
}
// Match any path if route equals '/'
if r.root {
return true, values
}
// Middleware matches path prefix
if strings.HasPrefix(path, r.Path) {
return true, values
}
// No prefix match, and we do not allow params in app.use
return false, values
}
// '*' wildcard matches any path
if r.star {
return true, []string{path}
}
// Check if a single '/' matches
if r.root && path == "/" {
return true, values
}
// Does this route have parameters
if len(r.Params) > 0 {
// Do we have a match?
params, ok := r.parsed.matchParams(path)
// We have a match!
if ok {
return true, params
}
}
// Check for a simple path match
if len(r.Path) == len(path) && r.Path == path {
return true, values
}
// Nothing match
return false, values
}
func (app *App) handler(fctx *fasthttp.RequestCtx) {
// get fiber context from sync pool
ctx := acquireCtx(fctx)
defer releaseCtx(ctx)
// Attach app poiner to access the routes
ctx.app = app
// Case sensitive routing
if !app.Settings.CaseSensitive {
ctx.path = strings.ToLower(ctx.path)
}
// Strict routing
if !app.Settings.StrictRouting && len(ctx.path) > 1 {
ctx.path = strings.TrimRight(ctx.path, "/")
}
// Find route
app.nextRoute(ctx)
}
func (app *App) registerMethod(method, path string, handlers ...func(*Ctx)) {
// Route requires atleast one handler
if len(handlers) == 0 {
log.Fatalf("Missing handler in route")
}
// Cannot have an empty path
if path == "" {
path = "/"
}
// Path always start with a '/' or '*'
if path[0] != '/' {
path = "/" + path
}
// Store original path to strip case sensitive params
original := path
// Case sensitive routing, all to lowercase
if !app.Settings.CaseSensitive {
path = strings.ToLower(path)
}
// Strict routing, remove last `/`
if !app.Settings.StrictRouting && len(path) > 1 {
path = strings.TrimRight(path, "/")
}
// Set route booleans
var isUse = method == "USE"
// Middleware / All allows all HTTP methods
if isUse || method == "ALL" {
method = "*"
}
var isStar = path == "/*"
// Middleware containing only a `/` equals wildcard
if isUse && path == "/" {
isStar = true
}
var isRoot = path == "/"
// Route properties
var isParsed = parseParams(original)
for i := range handlers {
route := &Route{
use: isUse,
star: isStar,
root: isRoot,
parsed: isParsed,
Path: path,
Method: method,
Params: isParsed.Keys,
Handler: handlers[i],
}
if method == "*" {
// Add handler to all HTTP methods
for m := range methodINT {
app.addRoute(m, route)
}
continue
}
// Add route to stack
app.addRoute(method, route)
// Add route to HEAD method if GET
if method == MethodGet {
app.addRoute(MethodHead, route)
}
}
}
func (app *App) registerStatic(prefix, root string, config ...Static) {
// Cannot have an empty prefix
if prefix == "" {
prefix = "/"
}
// Prefix always start with a '/' or '*'
if prefix[0] != '/' {
prefix = "/" + prefix
}
// Match anything
var wildcard = false
if prefix == "*" || prefix == "/*" {
wildcard = true
prefix = "/"
}
// Case sensitive routing, all to lowercase
if !app.Settings.CaseSensitive {
prefix = strings.ToLower(prefix)
}
// For security we want to restrict to the current work directory.
if len(root) == 0 {
root = "."
}
// Strip trailing slashes from the root path
if len(root) > 0 && root[len(root)-1] == '/' {
root = root[:len(root)-1]
}
// isSlash ?
var isRoot = prefix == "/"
if strings.Contains(prefix, "*") {
wildcard = true
prefix = strings.Split(prefix, "*")[0]
}
var stripper = len(prefix)
if isRoot {
stripper = 0
}
// Fileserver settings
fs := &fasthttp.FS{
Root: root,
GenerateIndexPages: false,
AcceptByteRange: false,
Compress: false,
CompressedFileSuffix: ".fiber.gz",
CacheDuration: 10 * time.Second,
IndexNames: []string{"index.html"},
PathRewrite: fasthttp.NewPathPrefixStripper(stripper),
PathNotFound: func(ctx *fasthttp.RequestCtx) {
ctx.Response.SetStatusCode(404)
ctx.Response.SetBodyString("Not Found")
},
}
// Set config if provided
if len(config) > 0 {
fs.Compress = config[0].Compress
fs.AcceptByteRange = config[0].ByteRange
fs.GenerateIndexPages = config[0].Browse
if config[0].Index != "" {
fs.IndexNames = []string{config[0].Index}
}
}
fileHandler := fs.NewRequestHandler()
route := &Route{
use: true,
root: isRoot,
Method: "*",
Path: prefix,
Handler: func(c *Ctx) {
// Do stuff
if wildcard {
c.Fasthttp.Request.SetRequestURI(prefix)
}
// Serve file
fileHandler(c.Fasthttp)
// Finish request if found and not forbidden
status := c.Fasthttp.Response.StatusCode()
if status != 404 && status != 403 {
return
}
// Reset response
c.Fasthttp.Response.Reset()
// Next middleware
c.Next()
},
}
// Add route to stack
app.addRoute(MethodGet, route)
app.addRoute(MethodHead, route)
}
func (app *App) addRoute(method string, route *Route) {
m := methodINT[method]
app.routes[m] = append(app.routes[m], route)
}