|
1 | 1 | package vox |
2 | 2 |
|
3 | | -import ( |
4 | | - "regexp" |
5 | | -) |
6 | | - |
7 | | -// Route will register a new path handler to a given path. |
8 | | -func (app *Application) Route(method string, path string, handler Handler) { |
9 | | - // TODO: support string based path |
10 | | - r := routeToRegexp(path) |
11 | | - app.middlewares = append(app.middlewares, func(ctx *Context, req *Request, res *Response) { |
12 | | - if match(req, method, r) { |
13 | | - handler(ctx, req, res) |
14 | | - return |
| 3 | +// routeHandler handles route matching and parameter extraction |
| 4 | +func (app *Application) routeHandler(ctx *Context, req *Request, res *Response) { |
| 5 | + match, found := app.router.Match(req.Method, "", req.URL.Path) |
| 6 | + if found { |
| 7 | + for k, v := range match.Params { |
| 8 | + req.Params[k] = v |
15 | 9 | } |
16 | | - ctx.Next() |
17 | | - }) |
| 10 | + if h, ok := match.Handler.(Handler); ok { |
| 11 | + h(ctx, req, res) |
| 12 | + } |
| 13 | + } |
| 14 | + ctx.Next() |
18 | 15 | } |
19 | 16 |
|
20 | | -func match(req *Request, method string, path *regexp.Regexp) bool { |
21 | | - if req.Method != method && method != "*" { |
22 | | - // TODO(asaka): ignore case? |
23 | | - return false |
24 | | - } |
25 | | - match := path.FindStringSubmatch(req.URL.Path) |
26 | | - if match == nil { |
27 | | - return false |
| 17 | +// Route will register a new path handler to a given path. |
| 18 | +func (app *Application) Route(method string, path string, handler Handler) { |
| 19 | + var err error |
| 20 | + if method == "*" { |
| 21 | + err = app.router.Handle(path, handler) |
| 22 | + } else { |
| 23 | + err = app.router.Handle(method+" "+path, handler) |
28 | 24 | } |
29 | | - for i, name := range path.SubexpNames() { |
30 | | - if i == 0 || name == "" { |
31 | | - continue |
32 | | - } |
33 | | - req.Params[name] = match[i] |
| 25 | + if err != nil { |
| 26 | + panic(err) |
34 | 27 | } |
35 | | - return true |
36 | 28 | } |
37 | 29 |
|
38 | 30 | // Get register a new path handler for GET method. |
@@ -74,10 +66,3 @@ func (app *Application) Options(path string, handler Handler) { |
74 | 66 | func (app *Application) Trace(path string, handler Handler) { |
75 | 67 | app.Route("TRACE", path, handler) |
76 | 68 | } |
77 | | - |
78 | | -func routeToRegexp(path string) *regexp.Regexp { |
79 | | - replaced := regexp.MustCompile(`{(?P<param>\w+)}`).ReplaceAllStringFunc(path, func(s string) string { |
80 | | - return "(?P<" + s[1:len(s)-1] + ">[-_.\\p{Lu}\\p{Ll}0-9]+)" |
81 | | - }) |
82 | | - return regexp.MustCompile("^" + replaced + "$") |
83 | | -} |
0 commit comments