-
Notifications
You must be signed in to change notification settings - Fork 0
/
routing.go
362 lines (328 loc) · 11.7 KB
/
routing.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
package just
import (
"fmt"
"net/http"
"path"
"regexp"
"strings"
"unicode"
)
var (
rxPathFindParams = regexp.MustCompile(`\{([^/]*?)\}`)
)
const (
patternParamPath = "(.*?)"
patternParamString = "([^/\\\\]*?)"
patternParamFloat = "([+-]?(\\d*[.])?\\d+)"
patternParamInteger = "([+-]?\\d+)"
patternParamFileExt = "(\\.[A-Za-z0-9]+|)"
patternParamBoolean = "(1|0|t|f|true|false|T|F|TRUE|FALSE)"
patternParamUUID = "([a-fA-F0-9]{8}-?[a-f0-9]{4}-?[1-5][a-fA-F0-9]{3}-?[89abAB][a-fA-F0-9]{3}-?[a-fA-F0-9]{12})"
patternParamRID = "([0-9a-z]{20})"
patternHex = "((0[xX])?[0-9a-fA-F]+)"
)
// Method of processing a request or middleware.
type HandlerFunc func(*Context) IResponse
// Interface information on route.
type IRouteInfo interface {
BasePath() string
CountHandlers() int
HandlerByIndex(index int) (HandlerFunc, bool)
}
// Route interface.
type IRoute interface {
IRouteInfo
// Use middleware.
Use(...HandlerFunc) IRoute
// Processing of requests to the application server.
Handle(string, string, ...HandlerFunc) IRoute
ANY(string, ...HandlerFunc) IRoute
GET(string, ...HandlerFunc) IRoute
POST(string, ...HandlerFunc) IRoute
DELETE(string, ...HandlerFunc) IRoute
PATCH(string, ...HandlerFunc) IRoute
PUT(string, ...HandlerFunc) IRoute
OPTIONS(string, ...HandlerFunc) IRoute
HEAD(string, ...HandlerFunc) IRoute
StaticFile(string, string) IRoute
Static(string, string) IRoute
StaticFS(string, http.FileSystem) IRoute
CheckPath(string) (map[string]string, bool)
}
// Router interface.
type IRouter interface {
IRoute
Group(string, ...HandlerFunc) IRouter
}
// Base Router struct.
type Router struct {
basePath string // The way that process route.
rxPath *regexp.Regexp // The regular expression used to validate the path.
handlers []HandlerFunc // The list of processors, including middleware available for this route.
routeParamNames []string // A list of detected parameters in their path.
parent *Router // A pointer to the parent router.
groups map[string]*Router // Routers (map[relativePath]*Router).
routes map[string][]IRoute // Routes with grouping by method (map[httpMethod][]IRoute).
}
func connectHandlersByRouter(r *Router, handlers []HandlerFunc) []HandlerFunc {
if r != nil && r.handlers != nil {
return append(append(make([]HandlerFunc, 0, 0), r.handlers...), handlers...)
}
return handlers
}
func regularityBasePath(basePath string, exactly bool, supportEndSlash bool) (rxPath *regexp.Regexp, paramNames []string) {
if strings.IndexByte(basePath, '{') < 0 {
return
}
params := rxPathFindParams.FindAllStringSubmatch(basePath, -1)
if len(params) < 1 {
return
}
paramNames = make([]string, len(params))
regExpPattern := basePath
for i, param := range params {
if len(param) == 0 {
continue
}
if len(param) > 1 {
// Анализ параметра
if pos := strings.IndexByte(param[1], ':'); pos > 0 {
paramNames[i] = strings.TrimSpace(param[1][0:pos])
if req := strings.TrimSpace(param[1][pos+1:]); len(req) > 1 {
// Анализ рекомендаций параметра
findPattern := true
switch req {
case "p", "path":
regExpPattern = strings.Replace(regExpPattern, param[0], patternParamPath, 1)
case "hex":
regExpPattern = strings.Replace(regExpPattern, param[0], patternHex, 1)
case "rid":
regExpPattern = strings.Replace(regExpPattern, param[0], patternParamRID, 1)
case "uuid":
regExpPattern = strings.Replace(regExpPattern, param[0], patternParamUUID, 1)
case "i", "int", "integer":
regExpPattern = strings.Replace(regExpPattern, param[0], patternParamInteger, 1)
case "f", "number", "float":
regExpPattern = strings.Replace(regExpPattern, param[0], patternParamFloat, 1)
case "b", "bool", "boolean":
regExpPattern = strings.Replace(regExpPattern, param[0], patternParamBoolean, 1)
case "f.e", "file.ext":
regExpPattern = strings.Replace(regExpPattern, param[0], patternParamFileExt, 1)
default:
{
findPattern = false
if begin, end := strings.IndexByte(req, '('), strings.LastIndexByte(req, ')'); begin > 0 && end > begin {
if t := strings.TrimSpace(req[:begin]); len(t) > 0 {
if findPattern = t == "regexp" || t == "enum"; findPattern && len(strings.TrimSpace(req[begin+1:end])) > 0 {
switch t {
case "rgx", "regexp":
regExpPattern = strings.Replace(regExpPattern, param[0], strings.TrimSpace(req[begin:]), 1)
case "e", "enum":
regExpPattern = strings.Replace(regExpPattern, param[0], "("+strings.Join(strings.FieldsFunc(req[begin+1:end], func(c rune) bool {
return !unicode.IsLetter(c) && !unicode.IsNumber(c)
}), "|")+")", 1)
}
}
}
}
}
}
if findPattern {
continue
}
}
} else {
paramNames[i] = strings.TrimSpace(param[1])
}
} else {
paramNames[i] = strings.TrimSpace(param[0])
}
regExpPattern = strings.Replace(regExpPattern, param[0], patternParamString, 1)
}
var (
err error
end string
)
if supportEndSlash {
end = "(\\/)?"
}
if exactly {
end += "$"
}
rxPath, err = regexp.Compile("^" + regExpPattern + end)
if err != nil {
panic(err)
}
return
}
func (r *Router) handle(httpMethod string, relativePath string, handlers []HandlerFunc) IRoute {
if r.routes == nil {
r.routes = make(map[string][]IRoute)
}
if _, ok := r.routes[httpMethod]; !ok {
r.routes[httpMethod] = make([]IRoute, 0)
}
basePath := joinPaths(r.basePath, strings.TrimRight(relativePath, "/"))
rxPath, routeParamNames := regularityBasePath(basePath, true, true)
if IsDebug() {
if rxPath != nil {
fmt.Println("[DEBUG] Registration", httpMethod, "route regexp:", rxPath.String(), routeParamNames)
} else {
fmt.Println("[DEBUG] Registration", httpMethod, "plain route:", basePath)
}
}
r.routes[httpMethod] = append(r.routes[httpMethod], &Router{
basePath: basePath,
rxPath: rxPath,
handlers: connectHandlersByRouter(r, handlers),
routeParamNames: routeParamNames,
parent: r,
groups: nil,
routes: nil,
})
return r
}
// Use middleware.
func (r *Router) Use(middleware ...HandlerFunc) IRoute {
if r.handlers == nil {
r.handlers = make([]HandlerFunc, 0)
}
r.handlers = append(r.handlers, middleware...)
return r
}
// Create group router.
// The group does not support regular expressions, text only.
func (r *Router) Group(relativePath string, handlers ...HandlerFunc) IRouter {
if len(relativePath) < 1 || relativePath == "/" {
panic(fmt.Errorf("the group cannot be empty"))
return nil
}
var (
rxPath *regexp.Regexp
routeParamNames []string
)
basePath := joinPaths(r.basePath, strings.TrimRight(relativePath, "/"))
if strings.IndexByte(basePath, '{') >= 0 {
rxPath, routeParamNames = regularityBasePath(basePath, false, true)
}
group := &Router{
basePath: basePath,
rxPath: rxPath,
handlers: connectHandlersByRouter(r, handlers),
routeParamNames: routeParamNames,
parent: r,
groups: nil,
routes: nil,
}
if r.groups == nil {
r.groups = make(map[string]*Router)
}
r.groups[relativePath] = group
return group
}
// Create a HTTP request handler.
func (r *Router) Handle(httpMethod, relativePath string, handlers ...HandlerFunc) IRoute {
if matches, err := regexp.MatchString("^[A-Z]+$", httpMethod); !matches || err != nil {
panic("HTTP method [" + httpMethod + "] not valid")
}
return r.handle(httpMethod, relativePath, handlers)
}
// Static serves files from the given file system root.
// Internally a http.FileServer is used, therefore http.NotFound is used instead of the Router's NotFound handler.
// To use the operating system's file system implementation, use:
// `router.Static("/static", "/var/www")`
func (r *Router) Static(relativePath, root string) IRoute {
return r.StaticFS(relativePath, http.Dir(root))
}
// StaticFile registers a single route in order to server a single file of the local filesystem.
// `router.StaticFile("favicon.ico", "./resources/favicon.ico")`
func (r *Router) StaticFile(relativePath, filePath string) IRoute {
handler := func(c *Context) IResponse {
return FileResponse(filePath)
}
return r.GET(relativePath, handler).HEAD(relativePath, handler)
}
// StaticFS works just like `Static()` but a custom `http.FileSystem` can be used instead.
func (r *Router) StaticFS(relativePath string, fs http.FileSystem) IRoute {
fileServer := http.StripPrefix(joinPaths(r.basePath, relativePath), http.FileServer(fs))
handler := func(c *Context) IResponse {
return StreamResponse(func(w http.ResponseWriter, r *http.Request) {
fileServer.ServeHTTP(w, r)
})
}
urlPattern := path.Join(relativePath, "/{filepath:path}")
return r.GET(urlPattern).HEAD(urlPattern, handler)
}
// POST is a shortcut for router.Handle("POST", path, handlers...).
func (r *Router) POST(relativePath string, handlers ...HandlerFunc) IRoute {
return r.handle(http.MethodPost, relativePath, handlers)
}
// GET is a shortcut for router.Handle("GET", path, handlers...).
func (r *Router) GET(relativePath string, handlers ...HandlerFunc) IRoute {
return r.handle(http.MethodGet, relativePath, handlers)
}
// DELETE is a shortcut for router.Handle("DELETE", path, handlers...).
func (r *Router) DELETE(relativePath string, handlers ...HandlerFunc) IRoute {
return r.handle(http.MethodDelete, relativePath, handlers)
}
// PATCH is a shortcut for router.Handle("PATCH", path, handlers...).
func (r *Router) PATCH(relativePath string, handlers ...HandlerFunc) IRoute {
return r.handle(http.MethodPatch, relativePath, handlers)
}
// PUT is a shortcut for router.Handle("PUT", path, handlers...).
func (r *Router) PUT(relativePath string, handlers ...HandlerFunc) IRoute {
return r.handle(http.MethodPut, relativePath, handlers)
}
// OPTIONS is a shortcut for router.Handle("OPTIONS", path, handlers...).
func (r *Router) OPTIONS(relativePath string, handlers ...HandlerFunc) IRoute {
return r.handle(http.MethodOptions, relativePath, handlers)
}
// HEAD is a shortcut for router.Handle("HEAD", path, handlers...).
func (r *Router) HEAD(relativePath string, handlers ...HandlerFunc) IRoute {
return r.handle(http.MethodHead, relativePath, handlers)
}
// Any registers a route that matches all the HTTP methods. GET, POST, PUT, PATCH, DELETE.
func (r *Router) ANY(relativePath string, handlers ...HandlerFunc) IRoute {
r.handle(http.MethodGet, relativePath, handlers)
r.handle(http.MethodPost, relativePath, handlers)
r.handle(http.MethodPut, relativePath, handlers)
r.handle(http.MethodPatch, relativePath, handlers)
r.handle(http.MethodDelete, relativePath, handlers)
return r
}
func (r *Router) CheckPath(path string) (map[string]string, bool) {
if r.rxPath != nil {
if r.rxPath.MatchString(path) {
if indexes := r.rxPath.FindStringSubmatchIndex(path); len(indexes) > 2 && len(indexes)%2 == 0 {
values := make([]string, 0)
for e, i := 0, 2; i < len(indexes); i += 2 {
if indexes[i] >= e {
values = append(values, path[indexes[i]:indexes[i+1]])
e = indexes[i+1]
}
}
if len(values) >= len(r.routeParamNames) {
params := make(map[string]string)
for i := 0; i < len(r.routeParamNames); i++ {
params[r.routeParamNames[i]] = values[i]
}
return params, true
}
}
return nil, false
}
}
return nil, strings.Compare(path, r.basePath) == 0
}
func (r *Router) BasePath() string {
return r.basePath
}
func (r *Router) CountHandlers() int {
return len(r.handlers)
}
func (r *Router) HandlerByIndex(index int) (HandlerFunc, bool) {
if index >= 0 && index < len(r.handlers) {
return r.handlers[index], true
}
return nil, false
}