-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcrater.go
97 lines (79 loc) · 2.3 KB
/
crater.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
95
96
97
package crater
import (
"net/http"
"regexp"
"github.com/gavruk/schema"
)
const (
method_GET = "GET"
method_POST = "POST"
method_PUT = "PUT"
method_DELETE = "DELETE"
ct_JSON = "application/json"
ct_FormUrlEncoded = "application/x-www-form-urlencoded"
ct_MultipartFormData = "multipart/form-data"
)
type httpHandler func(http.ResponseWriter, *http.Request)
type route struct {
pattern *regexp.Regexp
routeHandler http.Handler
}
type regexpHandler struct {
getRoutes []*route
postRoutes []*route
putRoutes []*route
deleteRoutes []*route
notFoundHandler httpHandler
}
func newCraterHandler() *regexpHandler {
return ®expHandler{
getRoutes: make([]*route, 0),
postRoutes: make([]*route, 0),
putRoutes: make([]*route, 0),
deleteRoutes: make([]*route, 0),
notFoundHandler: http.NotFound,
}
}
func (h *regexpHandler) handleGet(pattern *regexp.Regexp, handler httpHandler) {
h.getRoutes = append(h.getRoutes, &route{pattern, http.HandlerFunc(handler)})
}
func (h *regexpHandler) handlePost(pattern *regexp.Regexp, handler httpHandler) {
h.postRoutes = append(h.postRoutes, &route{pattern, http.HandlerFunc(handler)})
}
func (h *regexpHandler) handlePut(pattern *regexp.Regexp, handler httpHandler) {
h.putRoutes = append(h.putRoutes, &route{pattern, http.HandlerFunc(handler)})
}
func (h *regexpHandler) handleDelete(pattern *regexp.Regexp, handler httpHandler) {
h.deleteRoutes = append(h.deleteRoutes, &route{pattern, http.HandlerFunc(handler)})
}
func (h *regexpHandler) handleStatic(pattern *regexp.Regexp, url string, fs http.FileSystem) {
h.getRoutes = append(h.getRoutes, &route{pattern, http.StripPrefix(url, http.FileServer(fs))})
}
func (h *regexpHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
var routes []*route
switch r.Method {
case method_GET:
routes = h.getRoutes
case method_POST:
routes = h.postRoutes
case method_PUT:
routes = h.putRoutes
case method_DELETE:
routes = h.deleteRoutes
}
urlPath := r.URL.Path
if urlPath == "" {
h.notFoundHandler(w, r)
}
if urlPath[0] != '/' {
urlPath = "/" + urlPath
}
for _, route := range routes {
if route.pattern.MatchString(urlPath) {
route.routeHandler.ServeHTTP(w, r)
return
}
}
h.notFoundHandler(w, r)
}
var schemaDecoder = schema.NewDecoder()