-
Notifications
You must be signed in to change notification settings - Fork 0
/
router.go
279 lines (222 loc) · 7.51 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
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
package fit
import (
"fmt"
"log"
"net/http"
"regexp"
)
const (
star = byte('*')
colon = byte(':')
slash = byte('/')
)
// Router ...
type Router struct {
// Resource tree for the assigned routes
res *resource
// Contains ResponseHandler(s) called before the handlers assigned on the route
before []ResponseHandler
// Contains ResponseHandler(s) called after the handlers assigned on the route
after []ResponseHandler
// Contains a ResponseHandler called after everything, not dependent of the middleware chain
logger ResponseHandler
// Contains the default function to use when a page was not found (404)
NotFound ResponseHandler
// A boolean value for toggling automatic redirects, if the route exists with (or without) slashes "/"
RedirectSlashes bool
}
// NewRouter returns a new instance of the Router struct.
// It's created with an empty resource and a standard not found handler for 404 requests.
func NewRouter() *Router {
return &Router{
newResource(), // Resource creation
nil, // Before ResponseHandler(s)
nil, // After ResponseHandler(s)
nil, // Logger ResponseHandler
notFoundHandler(), // Default not found handler
true, // RedirectSlashes is activated pr. default
}
}
// Before appends handler(s) before all other handlers, globally for the instance of the router
func (r *Router) Before(handlers ...ResponseHandler) {
r.before = append(r.before, handlers...)
}
// After appends handler(s) after all other handlers, globally for the instance of the router
func (r *Router) After(handlers ...ResponseHandler) {
r.after = append(r.after, handlers...)
}
// Logger to use. Did works the same way as the other ResponseHandlers, except it does not exist
// in the middleware chain, and is being called even though next was never called
func (r *Router) Logger(logger ResponseHandler) {
r.logger = logger
}
// Serve ..
func (r *Router) Serve(port ...int) {
// Setting the default port, as we're using variadic variables, to make it possible to use Serve() parameterless
portString := ":8080"
if len(port) > 0 {
portString = fmt.Sprintf(":%d", port[0])
}
fmt.Printf("Now serving on localhost%s\n", portString)
// Booting the server up, using a custom wrapper
log.Fatal(r.listenAndServe(portString))
}
// listenAndServe custom instance of the http.Server struct, to enable graceful shutdown
// TODO: Create a listener, to enabling closing of the server again later => https://play.golang.org/p/-G7nJlH_Mz
func (r *Router) listenAndServe(address string) error {
// Binding the main request function to handle all requests made
server := &http.Server{Addr: address, Handler: http.HandlerFunc(r.request)}
return server.ListenAndServe()
}
// redirectPath fixes the path by either include a slash, or remove one.
// Searches for the fixed path and returns a boolean value for the result, and the redirect path
func (r *Router) redirectPath(path, method string) (bool, string) {
redirectPath := path
pathLength := len(redirectPath)
if redirectPath[pathLength-1] == slash {
redirectPath = redirectPath[:pathLength-1]
} else {
redirectPath += "/"
}
// Attempt to find the fixed route
found, handler, _ := r.findRoute(redirectPath, method)
return found && handler != nil, redirectPath
}
func (r *Router) request(w http.ResponseWriter, rq *http.Request) {
path := rq.URL.Path
found, handlers, parameters := r.findRoute(path, rq.Method)
c := newContext()
c.writer, c.request = w, rq
if found && len(handlers) > 0 {
handlerChain := []ResponseHandler{}
if r.before != nil {
handlerChain = append(handlerChain, r.before...)
}
handlerChain = append(handlerChain, handlers...)
if r.after != nil {
handlerChain = append(handlerChain, r.after...)
}
c.params, c.handlers, c.currentHandler, c.maxHandlers = parameters, handlerChain, 0, len(handlerChain)
c.callByIndex(0)
} else if found, redirectPath := r.redirectPath(path, rq.Method); found && r.RedirectSlashes {
c.status = http.StatusMovedPermanently
http.Redirect(w, rq, redirectPath, c.status)
} else {
c.status = http.StatusNotFound
// Error handler here
if r.NotFound == nil {
fmt.Fprintln(w, "Requested page was not found")
} else {
r.NotFound(c)
}
}
if r.logger != nil {
r.logger(c)
}
}
func (r *Router) addRoute(path string, methods []string, handlers ...ResponseHandler) *Options {
i, pathLength, res, options, max := 0, len(path), r.res, &Options{path: path}, 0
for i < pathLength {
position := res.getIndexPosition(path[i])
if position == len(res.prefix) || res.prefix[position] != path[i] {
position = find(path, colon, i, pathLength)
if position == pathLength {
position = find(path, star, i, pathLength)
res = res.insertChild(path[i], newResourceFromPath(path[i:position]))
if position < pathLength {
res = res.insertChild(star, newResourceFromPath(path[position+1:]))
max++
}
res.addMethods(methods, options, handlers...)
break
}
res = res.insertChild(path[i], newResourceFromPath(path[i:position]))
i = find(path, slash, position, pathLength)
res = res.insertChild(colon, newResourceFromPath(path[position+1:i]))
max++
if i == pathLength {
res.addMethods(methods, options, handlers...)
}
} else if path[i] == colon {
res = res.children[0]
i += len(res.path) + 1
max++
if i == pathLength {
res.addMethods(methods, options, handlers...)
}
} else {
res = res.getChild(path[i])
j, resourcePathLength := 0, len(res.path)
for j < resourcePathLength && i < pathLength && path[i] == res.path[j] {
i++
j++
}
if j < resourcePathLength {
child := res.copy()
child.path = res.path[j:]
// Why cant i simplify this with newResource?
res.path = res.path[:j]
res.methods = make(map[string][]ResponseHandler)
res.prefix = string(child.path[0])
res.children = []*resource{child}
res.options = &Options{}
}
if i == pathLength {
res.addMethods(methods, options, handlers...)
}
}
}
if r.res.max < max {
r.res.max = max
}
return options
}
func (r *Router) appendParameter(parameters *Parameters, key, value string) {
if parameters.stack == nil {
parameters.stack = make([]parameter, 0, r.res.max)
}
parameters.stack = append(parameters.stack, parameter{key, value})
}
func (r *Router) findRoute(path, method string) (found bool, handlers []ResponseHandler, parameters Parameters) {
// TODO - Make params object instead of map
i, pathLength, res, parameters := 0, len(path), r.res, Parameters{}
for i < pathLength {
if len(res.prefix) == 0 {
return
}
if res.prefix[0] == colon {
res = res.children[0]
position := find(path, slash, i, len(path))
r.appendParameter(¶meters, res.path, path[i:position])
i = position
} else if res.prefix[0] == star {
res = res.children[0]
r.appendParameter(¶meters, res.path, path[i:])
break
} else {
position := res.getIndexPosition(path[i])
if position == len(res.prefix) || res.prefix[position] != path[i] {
return
}
res = res.children[position]
position = i + len(res.path)
if position > pathLength || path[i:position] != res.path {
return
}
i = position
}
}
// If regex is specified, we will run it against the parameters
if res.options.regex != nil {
for name, constraint := range res.options.regex {
if ok, param := parameters.GetByName(name); ok {
validRoute := regexp.MustCompile(constraint)
if !validRoute.MatchString(param) {
// Not found
return
}
}
}
}
return true, res.methods[method], parameters
}