-
Notifications
You must be signed in to change notification settings - Fork 2
/
router.go
275 lines (253 loc) · 6.53 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
package fresh
import (
"net/http"
"os"
"path/filepath"
"strings"
)
type (
// Single route struct
route struct {
path string
handlers []*handler
parent *route
children []*route
after []HandlerFunc
before []HandlerFunc
parameter bool
}
// Router struct
router struct {
*fresh
route *route
static map[string]string
}
// Handler struct
Handler interface {
After(...HandlerFunc) Handler
Before(...HandlerFunc) Handler
}
handler struct {
method string
ctrl HandlerFunc
before []HandlerFunc
after []HandlerFunc
}
// Resource struct
resource struct {
methods []string
rest []Handler
}
Resource interface {
After(...HandlerFunc) Resource
Before(...HandlerFunc) Resource
}
)
// isURLParameter check if given string is a param
func isURLParameter(value string) bool {
if strings.HasPrefix(value, ":") {
return true
}
return false
}
func (r *route) getHandler(method string) *handler {
for _, h := range r.handlers {
if h.method == method {
return h
}
}
return nil
}
// Add handlers to a route
func (r *route) addHandler(method string, controller HandlerFunc, middleware ...HandlerFunc) Handler {
// If already exist an entry for the method change related handler
for _, h := range r.handlers {
if h.method == method {
h.ctrl = controller
return h
}
}
h := handler{method: method, ctrl: controller}
r.handlers = append(r.handlers, &h)
return &h
}
// Process a request
func (r *router) process(handler *handler, response http.ResponseWriter, request *http.Request, context *context) (err error) {
context.init(request, response)
// TODO improve layout
// log route stdout
defer func() {
r.config.log(request.Method, request.RequestURI, context.response.reply.code)
}()
if err = handler.middleware(context, handler.before...); err != nil {
return err
}
// route controller
err = handler.ctrl(context)
if err != nil {
return err
}
// after middleware
if err = handler.middleware(context, handler.after...); err != nil {
return err
}
// loop handlers
for _, ch := range r.config.handlers {
err := ch(context)
if err != nil {
return err
}
}
// write response
context.response.write()
return
}
// After middleware for a resource
func (r *resource) After(middleware ...HandlerFunc) Resource {
if middleware != nil {
for _, route := range r.rest {
route.After(middleware...)
}
}
return r
}
// Before middleware for a resource
func (r *resource) Before(middleware ...HandlerFunc) Resource {
if middleware != nil {
for _, route := range r.rest {
route.Before(middleware...)
}
}
return r
}
// Run a middleware
func (h *handler) middleware(c Context, handlers ...HandlerFunc) error {
for _, f := range handlers {
if f != nil {
if err := f(c); err != nil {
return err
}
}
}
return nil
}
// After middleware for a single route
func (h *handler) After(middleware ...HandlerFunc) Handler {
if middleware != nil {
h.after = append(h.after, middleware...)
}
return h
}
// Before middleware for a single route
func (h *handler) Before(middleware ...HandlerFunc) Handler {
if middleware != nil {
h.before = append(h.before, middleware...)
}
return h
}
// Register static routes for assets
func (r *router) addStatic(static map[string]string) Handler {
for k, v := range static {
r.static[k] = v
}
return nil
}
// Router main function. Find the matching route and call registered handlers.
func (r *router) serveStatic(response http.ResponseWriter, request *http.Request) {
for publicPath, staticPath := range r.static {
path := strings.Replace(strings.Trim(request.URL.Path, "/"), publicPath, staticPath, 1)
path, _ = filepath.Abs(path)
f, err := os.Stat(path)
if err == nil && !f.IsDir() {
http.ServeFile(response, request, path)
return
} else if f.IsDir() {
for _, testDefaultFile := range r.config.Default {
filePath := filepath.Join(path, testDefaultFile)
if f, err := os.Stat(filePath); err == nil && !f.IsDir() {
http.ServeFile(response, request, filePath)
return
}
}
}
}
// TODO improve layout
// log route stdout
r.config.log(request.Method, request.RequestURI, 404)
// write response
http.NotFound(response, request)
}
// Add new route with its handlers
func (r *router) addRoute(method string, path string, handler HandlerFunc) Handler {
splittedPath := strings.Split(strings.Trim(path, "/"), "/")
route := r.register(r.route, splittedPath, nil)
return route.addHandler(method, handler)
}
// Scan the tree to find the matching route (if save create all needed routes)
func (r *router) findNode(parent *route, path []string, context *context) *route {
if len(path) > 0 {
for _, route := range parent.children {
if route.path == path[0] {
return r.findNode(route, path[1:], context)
}
if route.parameter {
context.parameters[route.path[1:]] = path[0]
return r.findNode(route, path[1:], context)
}
}
if parent.children[len(parent.children)-1].parameter {
return parent.children[len(parent.children)-1]
} else {
return nil
}
}
return parent
}
// Scan the tree searching for correct route node position
func (r *router) register(parent *route, path []string, context *context) *route {
if len(path) > 0 {
for _, route := range parent.children {
if route.path == path[0] {
return r.register(route, path[1:], context)
}
}
newRoute := &route{path: path[0], parent: parent}
switch {
case isURLParameter(path[0]):
newRoute.parameter = true
parent.children = append(parent.children, newRoute)
default:
parent.children = append([]*route{newRoute}, parent.children...)
}
return r.register(newRoute, path[1:], context)
}
return parent
}
// Router main function. Find the matching route and call registered handlers.
func (r *router) ServeHTTP(response http.ResponseWriter, request *http.Request) {
context := &context{}
context.parameters = make(map[string]string)
splittedPath := strings.Split(strings.Trim(request.URL.Path, "/"), "/")
if route := r.findNode(r.route, splittedPath, context); route != nil {
if r.config.Options && request.Method == "OPTIONS" {
h := &handler{
ctrl: func(c Context) error {
return c.Response().Code(http.StatusOK)
},
}
err := r.process(h, response, request, context)
if err != nil {
context.Response().writeErr(err)
}
return
}
if routeHandler := route.getHandler(request.Method); routeHandler != nil {
err := r.process(routeHandler, response, request, context)
if err != nil {
context.Response().writeErr(err)
}
return
}
}
r.serveStatic(response, request)
}