-
Notifications
You must be signed in to change notification settings - Fork 0
/
router.go
77 lines (61 loc) · 1.64 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
package junkboy
import (
"context"
"net/http"
"regexp"
"strings"
)
type Router struct {
pathPrefix string
routes []route
}
func NewRouter(pathPrefix string) *Router {
return &Router{
pathPrefix: strings.TrimSuffix(pathPrefix, "/"),
}
}
func (rt *Router) AddRoute(methods []string, pattern string, handler http.HandlerFunc) {
newRt := newRoute(methods, rt.pathPrefix+pattern, handler)
rt.routes = append(rt.routes, newRt)
}
type ctxKey struct{}
func (rt *Router) ServeHTTP(w http.ResponseWriter, r *http.Request) {
var allow []string
for _, route := range rt.routes {
matches := route.regex.FindStringSubmatch(r.URL.Path)
if len(matches) > 0 {
for _, method := range route.methods {
if r.Method != method {
allow = append(allow, method)
continue
}
}
//if r.Method != route.method {
// allow = append(allow, route.method)
// continue
//}
ctx := context.WithValue(r.Context(), ctxKey{}, matches[1:])
route.handler(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 {
methods []string
regex *regexp.Regexp
handler http.HandlerFunc
}
func newRoute(methods []string, pattern string, handler http.HandlerFunc) route {
return route{methods, regexp.MustCompile("^" + pattern + "$"), handler}
}
func getField(r *http.Request, index int) string {
//nolint:errcheck // Need to figure out what error value can be.
fields := r.Context().Value(ctxKey{}).([]string)
return fields[index]
}