forked from revel/revel
-
Notifications
You must be signed in to change notification settings - Fork 0
/
router.go
368 lines (317 loc) · 9.13 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
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
package revel
import (
"encoding/csv"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/url"
"regexp"
"strings"
)
type Route struct {
Method string // e.g. GET
Path string // e.g. /app/{id}
Action string // e.g. Application.ShowApp
FixedParams []string // e.g. "arg1","arg2","arg3" (CSV formatting)
pathPattern *regexp.Regexp // for matching the url path
args []*arg // e.g. {id} from path /app/{id}
actionPattern *regexp.Regexp
}
type RouteMatch struct {
Action string // e.g. Application.ShowApp
ControllerName string // e.g. Application
MethodName string // e.g. ShowApp
FixedParams []string
Params map[string]string // e.g. {id: 123}
}
type arg struct {
name string
index int
constraint *regexp.Regexp
}
var (
nakedPathParamRegex = regexp.MustCompile(`\{([a-zA-Z_][a-zA-Z_0-9]*)\}`)
argsPattern = regexp.MustCompile(`\{<(?P<pattern>[^>]+)>(?P<var>[a-zA-Z_0-9]+)\}`)
)
// Prepares the route to be used in matching.
func NewRoute(method, path, action, fixedArgs string) (r *Route) {
// Handle fixed arguments
argsReader := strings.NewReader(fixedArgs)
csv := csv.NewReader(argsReader)
fargs, err := csv.Read()
if err != nil && err != io.EOF {
ERROR.Printf("Invalid fixed parameters (%v): for string '%v'", err.Error(), fixedArgs)
}
r = &Route{
Method: strings.ToUpper(method),
Path: path,
Action: action,
FixedParams: fargs,
}
// URL pattern
// TODO: Support non-absolute paths
if !strings.HasPrefix(r.Path, "/") {
ERROR.Print("Absolute URL required.")
return
}
// Handle embedded arguments
// Convert path arguments with unspecified regexes to standard form.
// e.g. "/customer/{id}" => "/customer/{<[^/]+>id}
normPath := nakedPathParamRegex.ReplaceAllStringFunc(r.Path, func(m string) string {
var argMatches []string = nakedPathParamRegex.FindStringSubmatch(m)
return "{<[^/]+>" + argMatches[1] + "}"
})
// Go through the arguments
r.args = make([]*arg, 0, 3)
for i, m := range argsPattern.FindAllStringSubmatch(normPath, -1) {
r.args = append(r.args, &arg{
name: string(m[2]),
index: i,
constraint: regexp.MustCompile(string(m[1])),
})
}
// Now assemble the entire path regex, including the embedded parameters.
// e.g. /app/{<[^/]+>id} => /app/(?P<id>[^/]+)
pathPatternStr := argsPattern.ReplaceAllStringFunc(normPath, func(m string) string {
var argMatches []string = argsPattern.FindStringSubmatch(m)
return "(?P<" + argMatches[2] + ">" + argMatches[1] + ")"
})
r.pathPattern = regexp.MustCompile(pathPatternStr + "$")
// Handle action
var actionPatternStr string = strings.Replace(r.Action, ".", `\.`, -1)
for _, arg := range r.args {
var argName string = "{" + arg.name + "}"
if argIndex := strings.Index(actionPatternStr, argName); argIndex != -1 {
actionPatternStr = strings.Replace(actionPatternStr, argName,
"(?P<"+arg.name+">"+arg.constraint.String()+")", -1)
}
}
r.actionPattern = regexp.MustCompile(actionPatternStr)
return
}
// Return nil if no match.
func (r *Route) Match(method string, reqPath string) *RouteMatch {
// Check the Method
if r.Method != "*" && method != r.Method && !(method == "HEAD" && r.Method == "GET") {
return nil
}
// Check the Path
var matches []string = r.pathPattern.FindStringSubmatch(reqPath)
if len(matches) == 0 || len(matches[0]) != len(reqPath) {
return nil
}
// Figure out the Param names.
params := make(map[string]string)
for i, m := range matches[1:] {
params[r.pathPattern.SubexpNames()[i+1]] = m
}
// If the action is variablized, replace into it with the captured args.
action := r.Action
if strings.Contains(action, "{") {
for key, value := range params {
action = strings.Replace(action, "{"+key+"}", value, -1)
}
}
// Special handling for explicit 404's.
if action == "404" {
return &RouteMatch{
Action: "404",
}
}
// Split the action into controller and method
actionSplit := strings.Split(action, ".")
if len(actionSplit) != 2 {
ERROR.Printf("Failed to split action: %s (matching route: %s)", action, r.Action)
return nil
}
return &RouteMatch{
Action: action,
ControllerName: actionSplit[0],
MethodName: actionSplit[1],
Params: params,
FixedParams: r.FixedParams,
}
}
type Router struct {
Routes []*Route
path string
}
func (router *Router) Route(req *http.Request) *RouteMatch {
for _, route := range router.Routes {
if m := route.Match(req.Method, req.URL.Path); m != nil {
return m
}
}
return nil
}
// Refresh re-reads the routes file and re-calculates the routing table.
// Returns an error if a specified action could not be found.
func (router *Router) Refresh() *Error {
// Get the routes file content.
contentBytes, err := ioutil.ReadFile(router.path)
if err != nil {
return &Error{
Title: "Failed to load routes file",
Description: err.Error(),
}
}
return router.parse(string(contentBytes), true)
}
// parse takes the content of a routes file and turns it into the routing table.
func (router *Router) parse(content string, validate bool) *Error {
routes := make([]*Route, 0, 10)
// For each line..
for n, line := range strings.Split(content, "\n") {
line = strings.TrimSpace(line)
if len(line) == 0 || line[0] == '#' {
continue
}
method, path, action, fixedArgs, found := parseRouteLine(line)
if !found {
continue
}
route := NewRoute(method, path, action, fixedArgs)
routes = append(routes, route)
if validate {
if err := router.validate(route); err != nil {
err.Path = router.path
err.Line = n + 1
err.SourceLines = strings.Split(content, "\n")
return err
}
}
}
router.Routes = routes
return nil
}
// Check that every specified action exists.
func (router *Router) validate(route *Route) *Error {
// Skip variable routes.
if strings.ContainsAny(route.Action, "{}") {
return nil
}
// Skip 404s
if route.Action == "404" {
return nil
}
// We should be able to load the action.
parts := strings.Split(route.Action, ".")
if len(parts) != 2 {
return &Error{
Title: "Route validation error",
Description: fmt.Sprintf("Expected two parts (Controller.Action), but got %d: %s",
len(parts), route.Action),
}
}
ct := LookupControllerType(parts[0])
if ct == nil {
return &Error{
Title: "Route validation error",
Description: "Unrecognized controller: " + parts[0],
}
}
mt := ct.Method(parts[1])
if mt == nil {
return &Error{
Title: "Route validation error",
Description: "Unrecognized method: " + parts[1],
}
}
return nil
}
// Groups:
// 1: method
// 4: path
// 5: action
// 6: fixedargs
var routePattern *regexp.Regexp = regexp.MustCompile(
"(?i)^(GET|POST|PUT|DELETE|OPTIONS|HEAD|WS|\\*)" +
"[(]?([^)]*)(\\))?[ \t]+" +
"(.*/[^ \t]*)[ \t]+([^ \t(]+)" +
`\(?([^)]*)\)?[ \t]*$`)
func parseRouteLine(line string) (method, path, action, fixedArgs string, found bool) {
var matches []string = routePattern.FindStringSubmatch(line)
if matches == nil {
return
}
method, path, action, fixedArgs = matches[1], matches[4], matches[5], matches[6]
found = true
return
}
func NewRouter(routesPath string) *Router {
return &Router{
path: routesPath,
}
}
type ActionDefinition struct {
Host, Method, Url, Action string
Star bool
Args map[string]string
}
func (a *ActionDefinition) String() string {
return a.Url
}
func (router *Router) Reverse(action string, argValues map[string]string) *ActionDefinition {
NEXT_ROUTE:
// Loop through the routes.
for _, route := range router.Routes {
if route.actionPattern == nil {
continue
}
var matches []string = route.actionPattern.FindStringSubmatch(action)
if len(matches) == 0 {
continue
}
for i, match := range matches[1:] {
argValues[route.actionPattern.SubexpNames()[i+1]] = match
}
// Create a lookup for the route args.
routeArgs := make(map[string]*arg)
for _, arg := range route.args {
routeArgs[arg.name] = arg
}
// Enforce the constraints on the arg values.
for argKey, argValue := range argValues {
arg, ok := routeArgs[argKey]
if ok && !arg.constraint.MatchString(argValue) {
continue NEXT_ROUTE
}
}
// Build up the URL.
var queryValues url.Values = make(url.Values)
// Handle optional trailing slashes (e.g. "/?") by removing the question mark.
path := strings.Replace(route.Path, "?", "", -1)
for argKey, argValue := range argValues {
if _, ok := routeArgs[argKey]; ok {
// If this arg goes into the path, put it in.
path = regexp.MustCompile(`\{(<[^>]+>)?`+regexp.QuoteMeta(argKey)+`\}`).
ReplaceAllString(path, url.QueryEscape(string(argValue)))
} else {
// Else, add it to the query string.
queryValues.Set(argKey, argValue)
}
}
// Calculate the final URL and Method
url := path
if len(queryValues) > 0 {
url += "?" + queryValues.Encode()
}
method := route.Method
star := false
if route.Method == "*" {
method = "GET"
star = true
}
return &ActionDefinition{
Url: url,
Method: method,
Star: star,
Action: action,
Args: argValues,
Host: "TODO",
}
}
ERROR.Println("Failed to find reverse route:", action, argValues)
return nil
}