-
Notifications
You must be signed in to change notification settings - Fork 0
/
retable.go
67 lines (59 loc) · 1.6 KB
/
retable.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
package router
import (
"context"
"net/http"
"regexp"
"strings"
)
// TableRouter is regexp table-based http router
// Inspired by https://github.com/benhoyt/go-routing/tree/master/retable
type TableRouter struct {
routes []route
}
// AddRoute adds given handler for route matching given pattern and method
func (tr *TableRouter) AddRoute(method, pattern string, handler http.Handler) {
tr.routes = append(tr.routes, newRoute(method, pattern, handler))
}
// Serve routes the given request
func (tr *TableRouter) ServeHTTP(w http.ResponseWriter, r *http.Request) {
var allow []string
for _, route := range tr.routes {
matches := route.regex.FindStringSubmatch(r.URL.Path)
if len(matches) > 0 {
if r.Method != route.method {
allow = append(allow, route.method)
continue
}
ctx := context.WithValue(r.Context(), ctxKey{}, matches[1:])
route.handler.ServeHTTP(w, r.WithContext(ctx))
return
}
}
if len(allow) > 0 {
w.Header().Set("Allow", strings.Join(allow, ", "))
http.Error(w, "405 method not allowed", http.StatusMethodNotAllowed)
return
}
http.NotFound(w, r)
}
type route struct {
method string
regex *regexp.Regexp
handler http.Handler
}
func newRoute(method, pattern string, handler http.Handler) route {
return route{method, regexp.MustCompile("^" + pattern + "$"), handler}
}
type ctxKey struct{}
// GetField returns the matched field at given index from the URL path
func GetField(r *http.Request, index int) string {
k := r.Context().Value(ctxKey{})
if k == nil {
return ""
}
fields := k.([]string)
if len(fields) <= index {
return ""
}
return fields[index]
}