-
Notifications
You must be signed in to change notification settings - Fork 0
/
path_muxer.go
391 lines (348 loc) · 9.37 KB
/
path_muxer.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
// Package mux provides a path multiplexer and
// interfaces for plugin handling and custom
// path matching.
package mux
// A custom multiplexer that can handle
// wildcards and regex routes.
import (
"bytes"
"fmt"
"net/http"
"net/url"
"path"
"strings"
)
// ---------------------------------
// ---------- Path Muxer -----------
// PathMuxer matches string paths and methods to endpoint handlers.
// Paths can contain named parameters which can be restricted by regexes.
// PathMuxer also allows the use of global and per-route plugins.
type PathMuxer struct {
chain *plugins
compiled *plugins
methods map[string]*group
NotFound http.Handler
NotImplemented http.Handler
Redirect http.Handler
// If strict, Paths with trailing slashes are considered
// a different path than those without trailing slashes.
// E.g. '/a/b/' != '/a/b'.
Strict bool
}
// New returns a pointer to a newly initialized PathMuxer.
func New() *PathMuxer {
muxer := PathMuxer{
chain: newPlugins(),
methods: make(map[string]*group),
NotFound: NotFoundHandler{},
NotImplemented: NotImplementedHandler{},
Redirect: RedirectHandler{},
Strict: true,
}
return &muxer
}
// Add sets the handler for a specific method+path combination
// and returns the endpoint node.
func (mux *PathMuxer) Add(method, path string, handler http.Handler) Endpoint {
path = cleanPath(path)
if strings.Contains(path, "/*/") {
panic("PathMuxer.Add: '*' is reserved by PathMuxer.")
}
// Grab matcher for method
g, ok := mux.methods[method]
if !ok {
g = newGroup(method, "", mux)
mux.methods[method] = g
}
return g.Add(path, handler)
}
// AddFunc wraps f as an http.Handler and set is as handler for a specific method+path
// combination. AddFunc returns the endpoint node.
func (mux *PathMuxer) AddFunc(method, path string, f func(w http.ResponseWriter, r *http.Request)) Endpoint {
return mux.Add(method, path, http.Handler(http.HandlerFunc(f)))
}
// Group creates a group at the passed in path.
// Groups and endpoints with paths that are
// subpaths of the passed in path are automatically
// subsumed by the newly created group.
// If there is a super-group that the passed in path
// falls under, the newly created group will be created
// under the super-group.
func (mux *PathMuxer) Group(method, path string) Group {
path = cleanPath(path)
// Drop path after/including catch-all
if i := strings.Index(path, "^"); i != -1 {
path = path[:i]
}
// Drop trailing slash as it doesn't make sense
// in the context of groups
if len(path) > 1 && path[len(path)-1] == '/' {
path = path[:len(path)-1]
}
g, ok := mux.methods[method]
if !ok {
g = newGroup(method, "", mux)
mux.methods[method] = g
}
return g.Group(path)
}
// Use adds a plugin handler onto the end of the chain of global
// plugins for the muxer.
func (mux *PathMuxer) Use(handler PluginHandler) *PathMuxer {
mux.chain.use(handler)
for _, g := range mux.methods {
g.compile()
}
return mux
}
// UseHandler wraps the handler as a PluginHandler and adds it onto the ned of
// the global plugin chain for the muxer.
func (mux *PathMuxer) UseHandler(handler http.Handler) *PathMuxer {
pluginHandler := PluginFunc(
func(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
handler.ServeHTTP(w, r)
next(w, r)
})
mux.Use(pluginHandler)
return mux
}
// ServeHTTP dispatches the correct handler for the route.
func (mux *PathMuxer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if p := cleanPath(r.URL.Path); p != r.URL.Path {
r.URL.Path = p
mux.Redirect.ServeHTTP(w, r)
return
}
g, ok := mux.methods[r.Method]
if !ok {
mux.NotImplemented.ServeHTTP(w, r)
return
}
g.exec(w, r)
}
// -----------------------------
// ---------- Helpers ----------
// NotFoundHandler is the default http.Handler for Not Found responses. Returns a 404 status
// with message "Not Found."
type NotFoundHandler struct{}
func (handler NotFoundHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusNotFound)
fmt.Fprintf(w, "Not Found.")
}
// NotImplementedHandler is the default http.Handler for Not Implemented responses. Returns a 501 status
// with message "Not Implemented."
type NotImplementedHandler struct{}
func (handler NotImplementedHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusNotImplemented)
fmt.Fprintf(w, "Not Implemented.")
}
// RedirectHandler is the default http.Handler for Redirect responses. Returns a 301 status and redirects
// to the URL stored in r. This handler assumes the necessary adjustments to r.URL
// have been made prior to calling the handler.
type RedirectHandler struct{}
func (handler RedirectHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Location", r.URL.String())
w.WriteHeader(http.StatusMovedPermanently)
}
// Inserts parameters into a parameter map
func insertParams(params []param, values url.Values) {
if len(params) == 0 {
return
}
for _, v := range params {
values.Add(v.key, v.value)
}
}
// Cleans a path by handling duplicate /'s,
// ., and ..
func cleanPath(p string) string {
if p == "" {
return "/"
}
if p[0] != '/' {
p = "/" + p
}
np := path.Clean(p)
// path.Clean removes trailing slash except for root;
// put the trailing slash back if necessary.
if p[len(p)-1] == '/' && np != "/" {
np += "/"
}
return np
}
// If p does not end with a trailing slash, append one.
// Otherwise remove the trailing slash
func handleTrailingSlash(p string) string {
if p == "" {
return "/"
}
if p[len(p)-1] == '/' {
return p[:len(p)-1]
}
p += "/"
return p
}
// checks if two paths are equal but
// counts wildcard segments (/{...}) as
// equivalent
func pathsEqual(p1, p2 string) bool {
if len(p1) != len(p2) {
return false
}
i := 0
j := 0
m := 0
n := 0
for i < len(p1) && j < len(p2) {
a := p1[i]
b := p2[j]
if p1[i] == '{' && (i == 0 || p1[i-1] == '/') {
// possible start to p1 wc
wildA := false
for m = i + 1; m < len(p1) && p1[m] != '/'; m++ {
if m == len(p1)-1 && p1[m] == '}' {
wildA = true
break
} else if m < len(p1)-1 && p1[m] == '}' && p1[m+1] == '/' {
wildA = true
break
}
}
if !wildA {
if b == a {
// No closing brace so no wild but b and a still match
// so continue
i++
j++
continue
}
// No wild and no match so break
return false
}
if b != '{' || (b == '{' && j > 0 && p2[j-1] != '/') {
// No possible start to p2 wc ergo no match
// so break here
return false
} else {
// possible start to p2 wc
wildB := false
for n = j + 1; j < len(p2) && p2[n] != '/'; n++ {
if n == len(p2)-1 && p2[n] == '}' {
// Closing brace found at end of p2
wildB = true
break
} else if n < len(p2)-1 && p2[n] == '}' && p2[n+1] == '/' {
// Closing brace found with more runes to go
wildB = true
break
}
}
if !wildB {
// No brace ergo no p2 wc ergo no match
// so break here
return false
}
i = m
j = n
}
} else if a != b {
return false
}
i++
j++
}
return true
}
// Trims a path prefix but counts wildcard segments (/{...})
// as equivalent. If the prefix cannot be found, no trimming
// is done. (skipWild: true means /{...} matches anything)
func trimPathPrefix(path, prefix string, skipWild bool) string {
i := 0
j := 0
m := 0
n := 0
for i < len(prefix) && j < len(path) {
a := prefix[i]
b := path[j]
if a == '{' && (i == 0 || prefix[i-1] == '/') {
// Possible start to prefix wc
wildA := false
for m = i + 1; m < len(prefix) && prefix[m] != '/'; m++ {
if m == len(prefix)-1 && prefix[m] == '}' {
// Closing brace found at end of prefix.
wildA = true
break
} else if m < len(prefix)-1 && prefix[m] == '}' && prefix[m+1] == '/' {
// Closing brace found with more runes to go
wildA = true
break
}
}
if !wildA {
if b == a {
// No closing brace so no wild but b and a still match
// so continue
i++
j++
continue
}
// No wild and no a b match so break
return path
}
if b != '{' || (b == '{' && j > 0 && path[j-1] != '/') {
// No possible start to path wc ergo no match
if skipWild {
// Skipping wilds so fast foward to next segment
for ; i < len(prefix) && prefix[i] != '/'; i++ {
}
for ; j < len(path) && path[j] != '/'; j++ {
}
continue
}
// Not skipping wilds so no match ergo break here
return path
} else {
// Possible start to path wc
wildB := false
for n = j + 1; j < len(path) && path[n] != '/'; n++ {
if n == len(path)-1 && path[n] == '}' {
// Closing brace found at end of path
wildB = true
break
} else if n < len(path)-1 && path[n] == '}' && path[n+1] == '/' {
// Closing brace found with more runes to go
wildB = true
break
}
}
if !wildB {
// No brace ergo no path wc ergo no match
if skipWild {
// Skipping wild keep on rolling
for ; i < len(prefix) && prefix[i] != '/'; i++ {
}
for ; j < len(path) && path[j] != '/'; j++ {
}
continue
}
// Not skipping break here
return path
}
i = m
j = n
}
} else if a != b {
return path
}
i++
j++
}
if i < len(prefix) {
return path
}
var buf bytes.Buffer
for ; j < len(path); j++ {
buf.WriteByte(byte(path[j]))
}
return buf.String()
}