This repository has been archived by the owner on Jul 2, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrouter.go
94 lines (80 loc) · 1.69 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
package bourbon
import (
"net/http"
"strings"
)
type defaultRouter struct {
routes map[string][]Route
}
func (dr *defaultRouter) Add(routes ...Route) {
for _, r := range routes {
dr.routes[r.Method()] = append(dr.routes[r.Method()], r)
}
}
func (dr *defaultRouter) Find(method, uri string) Route {
// serve OPTIONS
if method == "OPTIONS" {
var methods []string
var parent Bourbon
for k := range dr.routes {
for _, r := range dr.routes[k] {
if r.Regexp().MatchString(uri) {
methods = append(methods, k)
parent = r.Parent()
}
}
}
if len(methods) > 0 {
options := createOptions(methods)
options.SetParent(parent)
return options
}
return createNotFound()
}
// serve route
for _, r := range dr.routes[method] {
if r.Regexp().MatchString(uri) {
return r
}
}
// serve 405
for m, routes := range dr.routes {
if m == method {
continue
}
for _, r := range routes {
if r.Regexp().MatchString(uri) {
methodNotAllowed := createMethodNotAllowed()
methodNotAllowed.SetParent(r.Parent())
return methodNotAllowed
}
}
}
// serve 404
return createNotFound()
}
func createOptions(methods []string) Route {
return &route{
handler: func(rw http.ResponseWriter) {
rw.Header().Set("Allow", strings.Join(methods, ","))
rw.Header().Set("Content-Length", "0")
},
}
}
func createMethodNotAllowed() Route {
return &route{
handler: func() (int, Encodeable) {
return 405, CreateMessage(405)
},
}
}
func createNotFound() Route {
return &route{
handler: func() (int, Encodeable) {
return 404, CreateMessage(404)
},
}
}
func createDefaultRouter() Router {
return &defaultRouter{routes: make(map[string][]Route)}
}