-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathrouter.go
349 lines (323 loc) · 9.52 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
// Package fastroute is standard http.Handler based high performance HTTP request router.
//
// A trivial example is:
//
// package main
//
// import (
// "fmt"
// "log"
// "net/http"
// "github.com/DATA-DOG/fastroute"
// )
//
// func Index(w http.ResponseWriter, r *http.Request) {
// fmt.Fprint(w, "Welcome!\n")
// }
//
// func Hello(w http.ResponseWriter, r *http.Request) {
// fmt.Fprintf(w, "hello, %s!\n", fastroute.Parameters(r).ByName("name"))
// }
//
// func main() {
// log.Fatal(http.ListenAndServe(":8080", fastroute.New(
// fastroute.Route("/", Index),
// fastroute.Route("/hello/:name", Hello),
// )))
// }
//
// The router can be composed of fastroute.Router interface, which shares
// the same http.Handler interface. This package provides only this orthogonal
// interface as a building block.
//
// It also provides path pattern matching in order to construct dynamic routes
// having named Params available from http.Request at zero allocation cost.
// You can extract path parameters from request this way:
//
// params := fastroute.Parameters(request) // request - *http.Request
// fmt.Println(params.ByName("id"))
//
// The registered path, against which the router matches incoming requests, can
// contain two types of parameters:
// Syntax Type
// :name named parameter
// *name catch-all parameter
//
// Named parameters are dynamic path segments. They match anything until the
// next '/' or the path end:
// Path: /blog/:category/:post
//
// Requests:
// /blog/go/request-routers match: category="go", post="request-routers"
// /blog/go/request-routers/ no match
// /blog/go/ no match
// /blog/go/request-routers/comments no match
//
// Catch-all parameters match anything until the path end, including the
// directory index (the '/' before the catch-all). Since they match anything
// until the end, catch-all parameters must always be the final path element.
// Path: /files/*filepath
//
// Requests:
// /files/ match: filepath="/"
// /files/LICENSE match: filepath="/LICENSE"
// /files/templates/article.html match: filepath="/templates/article.html"
// /files no match
//
package fastroute
import (
"fmt"
"io"
"net/http"
"strings"
"sync"
)
// CompareFunc is used to compare static path
// portions.
//
// It is possible to override it in
// order to use strings.EqualFold for example
// in order to have case insensitive matching.
//
// Be careful if this func is changed during router
// runtime and there is more than one router running
// on the same application.
var CompareFunc func(string, string) bool = func(s1, s2 string) bool {
return s1 == s2
}
// Parameters returns all path parameters for given
// request.
//
// If there were no parameters and route is static
// then empty parameter slice is returned.
func Parameters(req *http.Request) Params {
if p := parameterized(req); p != nil {
return p.params
}
return make(Params, 0)
}
// Pattern gives matched route path pattern
// for this request.
//
// If route is static, empty string will
// be returned.
func Pattern(req *http.Request) string {
if p := parameterized(req); p != nil {
return p.pattern
}
return ""
}
// FlushParameters resets named parameters
// if they were assigned to the request.
//
// When using Router.Match(http.Request) func,
// parameters will be flushed only if matched
// http.Handler is served.
//
// If the purpose is just to test Router
// whether it matches or not, without serving
// matched handler, then this method should
// be invoked to prevent leaking parameters.
func FlushParameters(req *http.Request) {
if p := parameterized(req); p != nil {
p.reset(req)
}
}
// Params is a slice of key value pairs, as extracted from
// the http.Request served by Router.
//
// The slice is ordered, the first URL parameter is also the first slice value.
// It is therefore safe to read values by the index.
type Params []struct{ Key, Value string }
// ByName returns the value of the first Param which key matches the given name.
// If no matching param is found, an empty string is returned.
func (ps Params) ByName(name string) string {
for i := range ps {
if ps[i].Key == name {
return ps[i].Value
}
}
return ""
}
// Router interface is robust and nothing more than
// http.Handler. It simply extends it with one extra method to Match
// http.Handler from http.Request and that allows to chain it
// until a handler is matched.
//
// Match func should return handler or nil.
type Router interface {
http.Handler
// Match should return nil if request
// cannot be matched. When ServeHTTP is
// invoked and handler is nil, it will
// serve http.NotFoundHandler
//
// Note, if the router is matched and it has
// path parameters - then it must be served
// in order to release allocated parameters
// back to the pool. Otherwise you will leak
// parameters, which you can also salvage by
// calling FlushParameters on http.Request
Match(*http.Request) http.Handler
}
// RouterFunc type is an adapter to allow the use of
// ordinary functions as Routers. If f is a function
// with the appropriate signature, RouterFunc(f) is a
// Router that calls f.
type RouterFunc func(*http.Request) http.Handler
// Match calls f(r).
func (rf RouterFunc) Match(r *http.Request) http.Handler {
return rf(r)
}
// ServeHTTP calls f(w, r).
func (rf RouterFunc) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if h := rf(r); h != nil {
h.ServeHTTP(w, r)
} else {
http.NotFound(w, r)
}
}
// New creates Router combined of given routes.
// It attempts to match all routes in order, the first
// matched route serves the request.
//
// Users may sort routes the way he prefers, or add
// dynamic sorting goroutine, which calculates order
// based on hits.
func New(routes ...Router) Router {
return RouterFunc(func(r *http.Request) http.Handler {
var found http.Handler
for _, router := range routes {
if found = router.Match(r); found != nil {
break
}
}
return found
})
}
// Route creates Router which attempts
// to match given path to handler.
//
// Handler is a standard http.Handler which
// may be accepted in the following formats:
// http.Handler
// func(http.ResponseWriter, *http.Request)
//
// Static paths will be simply matched to
// the request URL. While paths having named
// parameters will be matched by segment. And
// bind matched named parameters to http.Request.
//
// When dynamic path is matched, it must be served
// in order to salvage allocated named parameters.
func Route(path string, handler interface{}) Router {
p := "/" + strings.TrimLeft(path, "/")
var h http.Handler = nil
switch t := handler.(type) {
case http.HandlerFunc:
h = t
case func(http.ResponseWriter, *http.Request):
h = http.HandlerFunc(t)
default:
panic(fmt.Sprintf("not a handler given: %T - %+v", t, t))
}
// maybe static route
if strings.IndexAny(p, ":*") == -1 {
return RouterFunc(func(r *http.Request) http.Handler {
if CompareFunc(p, r.URL.Path) {
return h
}
return nil
})
}
// prepare and validate pattern segments to match
segments := strings.Split(strings.Trim(p, "/"), "/")
for i := 0; i < len(segments); i++ {
seg := segments[i]
segments[i] = "/" + seg
if pos := strings.IndexAny(seg, ":*"); pos == -1 {
continue
} else if pos != 0 {
panic("special param matching signs, must follow after slash: " + p)
} else if len(seg)-1 == pos {
panic("param must be named after sign: " + p)
} else if seg[0] == '*' && i+1 != len(segments) {
panic("match all, must be the last segment in pattern: " + p)
} else if strings.IndexAny(seg[1:], ":*") != -1 {
panic("only one param per segment: " + p)
}
}
ts := p[len(p)-1] == '/' // whether we need to match trailing slash
// pool for parameters
num := strings.Count(p, ":") + strings.Count(p, "*")
pool := sync.Pool{}
pool.New = func() interface{} {
return ¶meters{params: make(Params, 0, num), pool: &pool, pattern: p}
}
// extend handler in order to salvage parameters
handle := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
h.ServeHTTP(w, r)
if p := parameterized(r); p != nil {
p.reset(r)
}
})
// dynamic route matcher
return RouterFunc(func(r *http.Request) http.Handler {
p := pool.Get().(*parameters)
if match(segments, r.URL.Path, &p.params, ts) {
p.wrap(r)
return handle
}
p.reset(r)
return nil
})
}
func match(segments []string, url string, ps *Params, ts bool) bool {
for _, seg := range segments {
if lu := len(url); lu == 0 {
return false
} else if seg[1] == ':' {
n := len(*ps)
*ps = (*ps)[:n+1]
end := 1
for end < lu && url[end] != '/' {
end++
}
(*ps)[n].Key, (*ps)[n].Value = seg[2:], url[1:end]
url = url[end:]
} else if seg[1] == '*' {
n := len(*ps)
*ps = (*ps)[:n+1]
(*ps)[n].Key, (*ps)[n].Value = seg[2:], url
return true
} else if lu < len(seg) {
return false
} else if CompareFunc(url[:len(seg)], seg) {
url = url[len(seg):]
} else {
return false
}
}
return (!ts && url == "") || (ts && url == "/") // match trailing slash
}
type parameters struct {
io.ReadCloser
params Params
pattern string
pool *sync.Pool
}
func (p *parameters) wrap(req *http.Request) {
p.ReadCloser = req.Body
req.Body = p
}
func (p *parameters) reset(req *http.Request) {
p.params = p.params[0:0]
p.pool.Put(p)
req.Body = p.ReadCloser
}
func parameterized(req *http.Request) *parameters {
if p, ok := req.Body.(*parameters); ok {
return p
}
return nil
}