-
Notifications
You must be signed in to change notification settings - Fork 26
/
lars.go
427 lines (329 loc) · 10.6 KB
/
lars.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
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
package lars
import (
"fmt"
"net/http"
"reflect"
"strings"
"sync"
"github.com/go-playground/form"
)
// HTTP Constant Terms and Variables
const (
// CONNECT HTTP method
CONNECT = http.MethodConnect
// DELETE HTTP method
DELETE = http.MethodDelete
// GET HTTP method
GET = http.MethodGet
// HEAD HTTP method
HEAD = http.MethodHead
// OPTIONS HTTP method
OPTIONS = http.MethodOptions
// PATCH HTTP method
PATCH = http.MethodPatch
// POST HTTP method
POST = http.MethodPost
// PUT HTTP method
PUT = http.MethodPut
// TRACE HTTP method
TRACE = http.MethodTrace
//-------------
// Media types
//-------------
ApplicationJSON = "application/json"
ApplicationJSONCharsetUTF8 = ApplicationJSON + "; " + CharsetUTF8
ApplicationJavaScript = "application/javascript"
ApplicationJavaScriptCharsetUTF8 = ApplicationJavaScript + "; " + CharsetUTF8
ApplicationXML = "application/xml"
ApplicationXMLCharsetUTF8 = ApplicationXML + "; " + CharsetUTF8
ApplicationForm = "application/x-www-form-urlencoded"
ApplicationProtobuf = "application/protobuf"
ApplicationMsgpack = "application/msgpack"
TextHTML = "text/html"
TextHTMLCharsetUTF8 = TextHTML + "; " + CharsetUTF8
TextPlain = "text/plain"
TextPlainCharsetUTF8 = TextPlain + "; " + CharsetUTF8
MultipartForm = "multipart/form-data"
OctetStream = "application/octet-stream"
//---------
// Charset
//---------
CharsetUTF8 = "charset=utf-8"
//---------
// Headers
//---------
AcceptedLanguage = "Accept-Language"
AcceptEncoding = "Accept-Encoding"
Authorization = "Authorization"
ContentDisposition = "Content-Disposition"
ContentEncoding = "Content-Encoding"
ContentLength = "Content-Length"
ContentType = "Content-Type"
Location = "Location"
Upgrade = "Upgrade"
Vary = "Vary"
WWWAuthenticate = "WWW-Authenticate"
XForwardedFor = "X-Forwarded-For"
XRealIP = "X-Real-Ip"
Allow = "Allow"
Origin = "Origin"
Gzip = "gzip"
WildcardParam = "*wildcard"
basePath = "/"
blank = ""
slashByte = '/'
paramByte = ':'
wildByte = '*'
)
// Handler is the type used in registering handlers.
// NOTE: these handlers may get wrapped by the HandlerFunc
// type internally.
type Handler interface{}
// HandlerFunc is the internal handler type used for middleware and handlers
type HandlerFunc func(Context)
// HandlersChain is an array of HanderFunc handlers to run
type HandlersChain []HandlerFunc
// ContextFunc is the function to run when creating a new context
type ContextFunc func(l *LARS) Context
// CustomHandlerFunc wraped by HandlerFunc and called where you can type cast both Context and Handler
// and call Handler
type CustomHandlerFunc func(Context, Handler)
// customHandlers is a map of your registered custom CustomHandlerFunc's
// used in determining how to wrap them.
type customHandlers map[reflect.Type]CustomHandlerFunc
// LARS is the main routing instance
type LARS struct {
routeGroup
trees map[string]*node
// function that gets called to create the context object... is total overridable using RegisterContext
contextFunc ContextFunc
pool sync.Pool
http404 HandlersChain // 404 Not Found
http405 HandlersChain // 405 Method Not Allowed
automaticOPTIONS HandlersChain
notFound HandlersChain
customHandlersFuncs customHandlers
// mostParams used to keep track of the most amount of
// params in any URL and this will set the default capacity
// of eachContext Params
mostParams uint8
// Enables automatic redirection if the current route can't be matched but a
// handler for the path with (without) the trailing slash exists.
// For example if /foo/ is requested but a route only exists for /foo, the
// client is redirected to /foo with http status code 301 for GET requests
// and 307 for all other request methods.
redirectTrailingSlash bool
// If enabled, the router checks if another method is allowed for the
// current route, if the current request can not be routed.
// If this is the case, the request is answered with 'Method Not Allowed'
// and HTTP status code 405.
// If no other Method is allowed, the request is delegated to the NotFound
// handler.
handleMethodNotAllowed bool
// if enabled automatically handles OPTION requests; manually configured OPTION
// handlers take presidence. default true
automaticallyHandleOPTIONS bool
}
// RouteMap contains a single routes full path
// and other information
type RouteMap struct {
Depth int `json:"depth"`
Path string `json:"path"`
Method string `json:"method"`
Handler string `json:"handler"`
}
var (
default404Handler = func(c Context) {
http.Error(c.Response(), http.StatusText(http.StatusNotFound), http.StatusNotFound)
}
methodNotAllowedHandler = func(c Context) {
c.Response().WriteHeader(http.StatusMethodNotAllowed)
}
automaticOPTIONSHandler = func(c Context) {
c.Response().WriteHeader(http.StatusOK)
}
formDecoder *form.Decoder
formDecoderInit sync.Once
)
// New Creates and returns a new lars instance
func New() *LARS {
l := &LARS{
routeGroup: routeGroup{
middleware: make(HandlersChain, 0),
},
trees: make(map[string]*node),
contextFunc: func(l *LARS) Context {
return NewContext(l)
},
mostParams: 0,
http404: []HandlerFunc{default404Handler},
http405: []HandlerFunc{methodNotAllowedHandler},
redirectTrailingSlash: true,
handleMethodNotAllowed: false,
automaticallyHandleOPTIONS: false,
}
l.routeGroup.lars = l
l.pool.New = func() interface{} {
c := l.contextFunc(l)
b := c.BaseContext()
b.parent = c
return b
}
return l
}
func initFormDecoder() {
formDecoderInit.Do(func() {
formDecoder = form.NewDecoder()
})
}
// BuiltInFormDecoder returns the built in form decoder github.com/go-playground/form
// in order for custom type to be registered.
func (l *LARS) BuiltInFormDecoder() *form.Decoder {
initFormDecoder()
return formDecoder
}
// RegisterCustomHandler registers a custom handler that gets wrapped by HandlerFunc
func (l *LARS) RegisterCustomHandler(customType interface{}, fn CustomHandlerFunc) {
if l.customHandlersFuncs == nil {
l.customHandlersFuncs = make(customHandlers)
}
t := reflect.TypeOf(customType)
if _, ok := l.customHandlersFuncs[t]; ok {
panic(fmt.Sprint("Custom Type + CustomHandlerFunc already declared: ", t))
}
l.customHandlersFuncs[t] = fn
}
// RegisterContext registers a custom Context function for creation
// and resetting of a global object passed per http request
func (l *LARS) RegisterContext(fn ContextFunc) {
l.contextFunc = fn
}
// Register404 alows for overriding of the not found handler function.
// NOTE: this is run after not finding a route even after redirecting with the trailing slash
func (l *LARS) Register404(notFound ...Handler) {
chain := make(HandlersChain, len(notFound))
for i, h := range notFound {
chain[i] = l.wrapHandler(h)
}
l.http404 = chain
}
// SetAutomaticallyHandleOPTIONS tells lars whether to
// automatically handle OPTION requests; manually configured
// OPTION handlers take precedence. default true
func (l *LARS) SetAutomaticallyHandleOPTIONS(set bool) {
l.automaticallyHandleOPTIONS = set
}
// SetRedirectTrailingSlash tells lars whether to try
// and fix a URL by trying to find it
// lowercase -> with or without slash -> 404
func (l *LARS) SetRedirectTrailingSlash(set bool) {
l.redirectTrailingSlash = set
}
// SetHandle405MethodNotAllowed tells lars whether to
// handle the http 405 Method Not Allowed status code
func (l *LARS) SetHandle405MethodNotAllowed(set bool) {
l.handleMethodNotAllowed = set
}
// Serve returns an http.Handler to be used.
func (l *LARS) Serve() http.Handler {
// reserved for any logic that needs to happen before serving starts.
// i.e. although this router does not use priority to determine route order
// could add sorting of tree nodes here....
l.notFound = make(HandlersChain, len(l.middleware)+len(l.http404))
copy(l.notFound, l.middleware)
copy(l.notFound[len(l.middleware):], l.http404)
if l.automaticallyHandleOPTIONS {
l.automaticOPTIONS = make(HandlersChain, len(l.middleware)+1)
copy(l.automaticOPTIONS, l.middleware)
copy(l.automaticOPTIONS[len(l.middleware):], []HandlerFunc{automaticOPTIONSHandler})
}
return http.HandlerFunc(l.serveHTTP)
}
// Conforms to the http.Handler interface.
func (l *LARS) serveHTTP(w http.ResponseWriter, r *http.Request) {
c := l.pool.Get().(*Ctx)
c.parent.RequestStart(w, r)
if root := l.trees[r.Method]; root != nil {
if c.handlers, c.params, c.handlerName = root.find(r.URL.Path, c.params); c.handlers == nil {
c.params = c.params[0:0]
if l.redirectTrailingSlash && len(r.URL.Path) > 1 {
// find again all lowercase
orig := r.URL.Path
lc := strings.ToLower(orig)
if lc != r.URL.Path {
if c.handlers, _, _ = root.find(lc, c.params); c.handlers != nil {
r.URL.Path = lc
c.handlers = l.redirect(r.Method, r.URL.String())
r.URL.Path = orig
goto END
}
}
if lc[len(lc)-1:] == basePath {
lc = lc[:len(lc)-1]
} else {
lc = lc + basePath
}
if c.handlers, _, _ = root.find(lc, c.params); c.handlers != nil {
r.URL.Path = lc
c.handlers = l.redirect(r.Method, r.URL.String())
r.URL.Path = orig
goto END
}
}
} else {
goto END
}
}
if l.automaticallyHandleOPTIONS && r.Method == OPTIONS {
l.getOptions(c)
goto END
}
if l.handleMethodNotAllowed {
if l.checkMethodNotAllowed(c) {
goto END
}
}
// not found
c.handlers = l.notFound
END:
c.parent.Next()
c.parent.RequestEnd()
l.pool.Put(c)
}
func (l *LARS) getOptions(c *Ctx) {
if c.request.URL.Path == "*" { // check server-wide OPTIONS
for m := range l.trees {
if m == OPTIONS {
continue
}
c.response.Header().Add(Allow, m)
}
} else {
for m, tree := range l.trees {
if m == c.request.Method || m == OPTIONS {
continue
}
if c.handlers, _, _ = tree.find(c.request.URL.Path, c.params); c.handlers != nil {
c.response.Header().Add(Allow, m)
}
}
}
c.response.Header().Add(Allow, OPTIONS)
c.handlers = l.automaticOPTIONS
return
}
func (l *LARS) checkMethodNotAllowed(c *Ctx) (found bool) {
for m, tree := range l.trees {
if m != c.request.Method {
if c.handlers, _, _ = tree.find(c.request.URL.Path, c.params); c.handlers != nil {
// add methods
c.response.Header().Add(Allow, m)
found = true
}
}
}
if found {
c.handlers = l.http405
}
return
}