-
Notifications
You must be signed in to change notification settings - Fork 0
/
controller.go
110 lines (95 loc) · 2.69 KB
/
controller.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
98
99
100
101
102
103
104
105
106
107
108
109
110
package stgin
import (
"mime/multipart"
"net/http"
"time"
)
type Controller struct {
Name string
routes []Route
prefix string
requestListeners []RequestListener
responseListeners []ResponseListener
apiListeners []APIListener
}
func NewController(name string, prefix string) *Controller {
return &Controller{
Name: name,
prefix: normalizePath("/" + prefix),
}
}
func (controller *Controller) AddRoutes(routes ...Route) {
for _, route := range routes {
path := normalizePath(controller.prefix + route.Path)
route.controller = controller
route.correspondingRegex = getRoutePatternRegexOrPanic(path)
controller.routes = append(controller.routes, route)
}
}
func (controller *Controller) AddRequestListeners(listeners ...RequestListener) {
controller.requestListeners = append(controller.requestListeners, listeners...)
}
func (controller *Controller) AddResponseListener(listeners ...ResponseListener) {
controller.responseListeners = append(controller.responseListeners, listeners...)
}
func (controller *Controller) AddAPIListeners(listeners ...APIListener) {
controller.apiListeners = append(controller.apiListeners, listeners...)
}
func (controller *Controller) executeInternal(request *http.Request) Status {
body := RequestBody{
underlying: nil,
underlyingBytes: []byte{},
hasFilledBytes: false,
}
var headers http.Header
if request.Header == nil {
headers = emptyHeaders
} else {
headers = request.Header
}
rc := RequestContext{
Url: request.URL.Path,
QueryParams: request.URL.Query(),
PathParams: nil,
Headers: headers,
Body: &body,
receivedAt: time.Now(),
Method: request.Method,
ContentLength: request.ContentLength,
Host: request.Host,
MultipartForm: func() *multipart.Form {
return request.MultipartForm
},
Scheme: request.URL.Scheme,
RemoteAddr: request.RemoteAddr,
}
for _, modifier := range controller.requestListeners {
rc = modifier(rc)
}
var done bool
var result Status
for _, route := range controller.routes {
matches, pathParams := route.withPrefixPrepended(controller.prefix).acceptsAndPathParams(request)
if matches && acceptsAllQueries(route.expectedQueries, request.URL.Query()) {
rc.PathParams = pathParams
done = true
result = route.Action(rc)
break
}
}
if !done {
result = NotFound(Json(&generalFailureMessage{
StatusCode: 404,
Path: request.URL.Path,
Message: "not found",
Method: request.Method,
}))
}
for _, modifier := range controller.responseListeners {
result = modifier(result)
}
for _, watcher := range controller.apiListeners {
watcher(rc, result)
}
return result
}