-
Notifications
You must be signed in to change notification settings - Fork 0
/
handler.go
44 lines (37 loc) · 1.12 KB
/
handler.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
package main
import (
"net/http"
"regexp"
"github.com/geocine/sugo/logger"
)
type route struct {
pattern *regexp.Regexp
handler http.Handler
proxy bool
}
// RegexpHandler struct for holding regex routes
type RegexpHandler struct {
routes []*route
}
// Handler registers the handler for the given pattern
func (h *RegexpHandler) Handler(pattern *regexp.Regexp, handler http.Handler) {
h.routes = append(h.routes, &route{pattern, handler, false})
}
// HandleFunc registers the handler function for the given pattern
func (h *RegexpHandler) HandleFunc(pattern *regexp.Regexp, handler func(http.ResponseWriter, *http.Request), proxy bool) {
h.routes = append(h.routes, &route{pattern, http.HandlerFunc(handler), proxy})
}
func (h *RegexpHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
for _, route := range h.routes {
if route.pattern.MatchString(r.URL.Path) {
lrw := NewLoggingResponseWriter(w)
route.handler.ServeHTTP(lrw, r)
if !route.proxy {
logger.LogResponse(r.Method, r.URL.Path, lrw.statusCode, route.proxy)
}
return
}
}
// no pattern matched; send 404 response
http.NotFound(w, r)
}