-
Notifications
You must be signed in to change notification settings - Fork 0
/
httputil.go
38 lines (32 loc) · 938 Bytes
/
httputil.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
package simfaas
import (
`net/http`
`regexp`
)
// RegexpHandler is simple http.Handler to enable the use of
// wildcards in routes.
type RegexpHandler struct {
routes []*route
}
func (h *RegexpHandler) Handler(pattern *regexp.Regexp, handler http.Handler) {
h.routes = append(h.routes, &route{pattern, handler})
}
func (h *RegexpHandler) HandleFunc(pattern *regexp.Regexp, handler func(http.ResponseWriter, *http.Request)) {
h.routes = append(h.routes, &route{pattern, http.HandlerFunc(handler)})
}
func (h *RegexpHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
// Reverse match, such that newer routes have precedence
for i := len(h.routes) - 1; i >= 0; i-- {
route := h.routes[i]
if route.pattern.MatchString(r.URL.Path) {
route.handler.ServeHTTP(w, r)
return
}
}
// no pattern matched; send 404 response
http.NotFound(w, r)
}
type route struct {
pattern *regexp.Regexp
handler http.Handler
}