-
Notifications
You must be signed in to change notification settings - Fork 20
/
routing.go
42 lines (33 loc) · 905 Bytes
/
routing.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
package main
import(
"regexp"
"net/http"
)
type Route struct {
pattern *regexp.Regexp
handler http.Handler
}
type RegexpRouter struct {
routes []*Route
}
func MakeRouter() *RegexpRouter {
r := new(RegexpRouter)
r.routes = make([]*Route, 0, 20)
return r
}
func (r *RegexpRouter) Handler(matchRegexp string, handler http.Handler) {
r.routes = append(r.routes, &Route{regexp.MustCompile(matchRegexp), handler})
}
func (r *RegexpRouter) HandleFunc(matchRegexp string, handlerFunc func(http.ResponseWriter, *http.Request)) {
handler := http.HandlerFunc(handlerFunc)
r.routes = append(r.routes, &Route{regexp.MustCompile(matchRegexp), handler})
}
func (r *RegexpRouter) ServeHTTP(resp http.ResponseWriter, req *http.Request) {
for _, route := range r.routes {
if route.pattern.MatchString(req.URL.Path) {
route.handler.ServeHTTP(resp, req)
return
}
}
http.NotFound(resp, req)
}