-
Notifications
You must be signed in to change notification settings - Fork 0
/
node.go
337 lines (331 loc) · 8.37 KB
/
node.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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
package gorr
import (
"errors"
"fmt"
"net/http"
"strings"
"github.com/Contra-Culture/report"
)
type (
Handler func(report.Node, http.ResponseWriter, *http.Request, Params) error
Node struct {
typ NodeType
parent *Node
inheritedBeforeHandlers []Handler
inheritableBeforeHandler Handler
beforeHandler Handler
afterHandler Handler
inheritableAfterHandler Handler
inheritedAfterHandlers []Handler
methods map[HTTPMethod]*Method
static map[string]*Node // nested static fragment nodes (Priority: 1)
param *Node // nested param node (Priority: 2)
wildcard *Node // nested wildcard node (Priority: 3)
matcher interface{} // interface{} is string, map[string]bool, func(string) bool or Query
__notFoundErrorHandler Handler
__methodNotAllowedErrorHandler Handler
__internalServerErrorHandler Handler
name string
title string
description string
}
Method struct {
title string
description string
handler Handler
}
HTTPMethod string
NodeType int
Query func(Params) (interface{}, error)
params map[string]interface{}
Params interface {
Get(string) (interface{}, bool)
Set(string, interface{}) error
}
)
const (
_ NodeType = iota
STATIC
STRING_PARAM
ID_PARAM
VARIANT_PARAM
WILDCARD
)
const (
GET = "GET"
HEAD = "HEAD"
POST = "POST"
PUT = "PUT"
DELETE = "DELETE"
CONNECT = "CONNECT"
OPTIONS = "OPTIONS"
TRACE = "TRACE"
PATCH = "PATCH"
)
func NewParams() Params {
return params(map[string]interface{}{})
}
func (ps params) Get(pn string) (v interface{}, ok bool) {
v, ok = ps[pn]
return
}
func (ps params) Set(pn string, v interface{}) (err error) {
_, exists := ps[pn]
if exists {
err = fmt.Errorf("parameter \"%s\" already setted", pn)
return
}
ps[pn] = v
return
}
func new(p *Node, t NodeType) (n *Node) {
n = &Node{
parent: p,
typ: t,
methods: map[HTTPMethod]*Method{},
static: map[string]*Node{},
}
if p != nil {
if p.inheritableBeforeHandler != nil {
n.inheritedBeforeHandlers = append(p.inheritedBeforeHandlers, p.inheritableBeforeHandler)
}
if p.inheritableAfterHandler != nil {
n.inheritedAfterHandlers = append(p.inheritedAfterHandlers, p.inheritableAfterHandler)
}
}
return
}
func (n *Node) Param() (string, bool) {
switch n.typ {
case STRING_PARAM, ID_PARAM, VARIANT_PARAM:
return n.title, true
default:
return "", false
}
}
// Handles request and/or delegates it to its child.
func (n *Node) Handle(rep report.Node, w http.ResponseWriter, r *http.Request) {
var (
ok bool
params = NewParams()
parent = n
fragments = []string{}
)
for _, f := range strings.Split(r.URL.Path, "/") {
if len(f) > 0 {
fragments = append(fragments, f)
}
}
outer:
for ; len(fragments) > 0; fragments = fragments[1:] {
f := fragments[0]
rep.Info("fragment %s of fragments: %s", f, strings.Join(fragments, "/"))
n, ok = parent.static[f]
if ok {
rep.Info("static node `%s` picked", f)
parent = n
continue outer
}
n = parent.param
if n != nil {
rep.Info("param node `:%s` picked", f)
switch matcher := n.matcher.(type) {
case []string:
rep.Info("[]string matcher picked")
params.Set(n.name, f)
for _, v := range matcher {
if v == f {
parent = n
continue outer
}
}
n.handleNotFoundError(rep, w, r, params)
return
case func(string) bool:
rep.Info("func(string) bool matcher picked")
params.Set(n.name, f)
if matcher(f) {
parent = n
continue outer
}
n.handleNotFoundError(rep, w, r, params)
return
case Query:
rep.Info("Query matcher picked")
idParamName := fmt.Sprintf("%sID", n.name)
params.Set(idParamName, f)
v, err := matcher(params)
if err != nil {
n.handleNotFoundError(rep, w, r, params)
return
}
params.Set(n.name, v)
parent = n
continue outer
default:
rep.Error("wrong param matcher type")
n.handleNotFoundError(rep, w, r, params)
return
}
} else {
n = parent.wildcard
if n != nil {
parent = n
continue outer
}
parent.handleNotFoundError(rep, w, r, params)
return
}
}
child := rep.Structure("leaf node (%s:%s)", n.name, nodeTypeString(n.typ))
n.handle(child, w, r, params)
child.Finalize()
rep.Finalize()
}
func (n *Node) handle(rep report.Node, w http.ResponseWriter, r *http.Request, params Params) {
var (
err error
h Handler
)
method, ok := n.methods[HTTPMethod(r.Method)]
if !ok {
rep.Error("method not allowed %s", r.Method)
n.handleMethodNotAllowedError(rep, w, r, params)
return
}
for _, h = range n.inheritedBeforeHandlers {
err = h(rep, w, r, params)
if err != nil {
rep.Error("inheritedBeforeHandlers> internal server error: %s", err.Error())
n.handleInternalServerError(rep, w, r, params)
return
}
}
h = n.inheritableBeforeHandler
if h != nil {
err = h(rep, w, r, params)
if err != nil {
rep.Error("inheritableBeforeHandler> internal server error: %s", err.Error())
n.handleInternalServerError(rep, w, r, params)
return
}
}
h = n.beforeHandler
if h != nil {
err = h(rep, w, r, params)
if err != nil {
rep.Error("beforeHandler> internal server error: %s", err.Error())
n.handleInternalServerError(rep, w, r, params)
return
}
}
err = method.Handler()(rep, w, r, params)
if err != nil {
rep.Error("Handler> internal server error %s", err.Error())
n.handleInternalServerError(rep, w, r, params)
return
}
h = n.afterHandler
if h != nil {
err = h(rep, w, r, params)
if err != nil {
rep.Error("afterHandler> internal server error: %s", err.Error())
n.handleInternalServerError(rep, w, r, params)
return
}
}
h = n.inheritableAfterHandler
if h != nil {
err = h(rep, w, r, params)
if err != nil {
rep.Error("ineritableAfterHandler> internal server error: %s", err.Error())
n.handleInternalServerError(rep, w, r, params)
return
}
}
for i := len(n.inheritedAfterHandlers) - 1; i >= 0; i-- {
h = n.inheritedAfterHandlers[i]
err = h(rep, w, r, params)
if err != nil {
rep.Error("inheritedAfterHandlers> internal server error: %s", err.Error())
n.handleInternalServerError(rep, w, r, params)
return
}
}
}
func (n *Node) handleMethodNotAllowedError(rep report.Node, w http.ResponseWriter, r *http.Request, params Params) (err error) {
var handle Handler
for {
handle = n.__methodNotAllowedErrorHandler
if handle != nil {
rep.Info("method not allowed error handling: handler not found")
handle(rep, w, r, params)
return
}
n = n.parent
if n != nil {
continue
}
rep.Info("method not allowed error handling: handler not found")
return errors.New("method not allowed handler is not provided")
}
}
func (n *Node) handleNotFoundError(rep report.Node, w http.ResponseWriter, r *http.Request, params Params) (err error) {
var handle Handler
for {
handle = n.__notFoundErrorHandler
if handle != nil {
rep.Info("not found error handling: handler not found")
err = handle(rep, w, r, params)
return
}
n = n.parent
if n != nil {
continue
}
rep.Info("not found error handling: handler not found")
return errors.New("not found handler is not provided")
}
}
func (n *Node) handleInternalServerError(rep report.Node, w http.ResponseWriter, r *http.Request, params Params) (err error) {
var handle Handler
for {
handle = n.__internalServerErrorHandler
if handle != nil {
rep.Info("internal server error handling")
handle(rep, w, r, params)
return
}
n = n.parent
if n != nil {
continue
}
rep.Info("internal server error handling: handler not found")
return errors.New("internal server error handler is not provided")
}
}
func (m *Method) Title() string {
return m.title
}
func (m *Method) Decription() string {
return m.description
}
func (m *Method) Handler() Handler {
return m.handler
}
func nodeTypeString(t NodeType) string {
switch t {
case STATIC:
return "static"
case STRING_PARAM:
return "string-param"
case ID_PARAM:
return "ID-param"
case VARIANT_PARAM:
return "variant-param"
case WILDCARD:
return "*"
default:
panic(fmt.Sprintf("wrong node type %d", int(t))) // should not occure
}
}