forked from gogearbox/gearbox
-
Notifications
You must be signed in to change notification settings - Fork 0
/
router.go
214 lines (180 loc) · 4.71 KB
/
router.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
package gearbox
import (
"log"
"strings"
"sync"
"github.com/valyala/fasthttp"
)
var (
defaultContentType = []byte("text/plain; charset=utf-8")
)
type router struct {
trees map[string]*node
cache map[string]*matchResult
cacheLen int
mutex sync.RWMutex
notFound handlersChain
settings *Settings
pool sync.Pool
}
type matchResult struct {
handlers handlersChain
params map[string]string
}
// acquireCtx returns instance of context after initializing it
func (r *router) acquireCtx(fctx *fasthttp.RequestCtx) *context {
ctx := r.pool.Get().(*context)
// Initialize
ctx.index = 0
ctx.paramValues = make(map[string]string)
ctx.requestCtx = fctx
return ctx
}
// releaseCtx frees context
func (r *router) releaseCtx(ctx *context) {
ctx.handlers = nil
ctx.paramValues = nil
ctx.requestCtx = nil
r.pool.Put(ctx)
}
// handle registers handlers for provided method and path to be used
// in routing incoming requests
func (r *router) handle(method, path string, handlers handlersChain) {
if path == "" {
panic("path is empty")
} else if method == "" {
panic("method is empty")
} else if path[0] != '/' {
panic("path must begin with '/' in path '" + path + "'")
} else if len(handlers) == 0 {
panic("no handlers provided with path '" + path + "'")
}
// initialize tree if it's empty
if r.trees == nil {
r.trees = make(map[string]*node)
}
// get root of method if it's existing, otherwise creates it
root := r.trees[method]
if root == nil {
root = createRootNode()
r.trees[method] = root
}
root.addRoute(path, handlers)
}
// allowed checks if provided path can be routed in another method(s)
func (r *router) allowed(reqMethod, path string, ctx *context) string {
var allow string
pathLen := len(path)
// handle * and /* requests
if (pathLen == 1 && path[0] == '*') || (pathLen > 1 && path[1] == '*') {
for method := range r.trees {
if method == MethodOptions {
continue
}
if allow != "" {
allow += ", " + method
} else {
allow = method
}
}
return allow
}
for method, tree := range r.trees {
if method == reqMethod || method == MethodOptions {
continue
}
handlers := tree.matchRoute(path, ctx)
if handlers != nil {
if allow != "" {
allow += ", " + method
} else {
allow = method
}
}
}
if len(allow) > 0 {
allow += ", " + MethodOptions
}
return allow
}
// Handler handles all incoming requests
func (r *router) Handler(fctx *fasthttp.RequestCtx) {
context := r.acquireCtx(fctx)
defer r.releaseCtx(context)
if r.settings.AutoRecover {
defer func(fctx *fasthttp.RequestCtx) {
if rcv := recover(); rcv != nil {
log.Printf("recovered from error: %v", rcv)
fctx.Error(fasthttp.StatusMessage(fasthttp.StatusInternalServerError),
fasthttp.StatusInternalServerError)
}
}(fctx)
}
path := GetString(fctx.URI().PathOriginal())
if r.settings.CaseInSensitive {
path = strings.ToLower(path)
}
method := GetString(fctx.Method())
var cacheKey string
useCache := !r.settings.DisableCaching &&
(method == MethodGet || method == MethodPost)
if useCache {
cacheKey = path + method
r.mutex.RLock()
cacheResult, ok := r.cache[cacheKey]
if ok {
context.handlers = cacheResult.handlers
context.paramValues = cacheResult.params
r.mutex.RUnlock()
context.handlers[0](context)
return
}
r.mutex.RUnlock()
}
if root := r.trees[method]; root != nil {
if handlers := root.matchRoute(path, context); handlers != nil {
context.handlers = handlers
context.handlers[0](context)
if useCache {
r.mutex.Lock()
if r.cacheLen == r.settings.CacheSize {
r.cache = make(map[string]*matchResult)
r.cacheLen = 0
}
r.cache[cacheKey] = &matchResult{
handlers: handlers,
params: context.paramValues,
}
r.cacheLen++
r.mutex.Unlock()
}
return
}
}
if method == MethodOptions && r.settings.HandleOPTIONS {
if allow := r.allowed(method, path, context); len(allow) > 0 {
fctx.Response.Header.Set("Allow", allow)
return
}
} else if r.settings.HandleMethodNotAllowed {
if allow := r.allowed(method, path, context); len(allow) > 0 {
fctx.Response.Header.Set("Allow", allow)
fctx.SetStatusCode(fasthttp.StatusMethodNotAllowed)
fctx.SetContentTypeBytes(defaultContentType)
fctx.SetBodyString(fasthttp.StatusMessage(fasthttp.StatusMethodNotAllowed))
return
}
}
// Custom Not Found (404) handlers
if r.notFound != nil {
r.notFound[0](context)
return
}
// Default Not Found response
fctx.Error(fasthttp.StatusMessage(fasthttp.StatusNotFound),
fasthttp.StatusNotFound)
}
// SetNotFound appends handlers to custom not found (404) handlers
func (r *router) SetNotFound(handlers handlersChain) {
r.notFound = append(r.notFound, handlers...)
}