diff --git a/src/router/context.go b/src/router/context.go index d893fc0..ca78edc 100644 --- a/src/router/context.go +++ b/src/router/context.go @@ -1,6 +1,8 @@ package router import ( + "encoding/json" + "log" "net/http" ) @@ -16,7 +18,7 @@ type Context struct { func (c *Context) Next() { c.index++ - c.handlers[c.index](c) + c.chain[c.index](c) } func (c *Context) JSON(status int, data interface{}) { diff --git a/src/router/match.go b/src/router/match.go new file mode 100644 index 0000000..79f3898 --- /dev/null +++ b/src/router/match.go @@ -0,0 +1,24 @@ +package router + +import "regexp" + +func regexGroups(input string, regex *regexp.Regexp) map[string]string { + groups := make(map[string]string) + matches := regex.FindStringSubmatchIndex(input) + for i, key := range regex.SubexpNames()[1:] { + groups[key] = input[matches[i*2+2]:matches[i*2+3]] + } + return groups +} + +func routeRegexp(route string) *regexp.Regexp { + chunks := regexp.MustCompile(`[\*\:]\w+`) + output := chunks.ReplaceAllStringFunc(route, func(m string) string { + if m[0:1] == `*` { + return "(?P<" + m[1:] + ">.+)" + } + return "(?P<" + m[1:] + ">[^/]+)" + }) + output = "^" + output + "$" + return regexp.MustCompile(output) +} diff --git a/src/router/router_test.go b/src/router/match_test.go similarity index 100% rename from src/router/router_test.go rename to src/router/match_test.go diff --git a/src/router/router.go b/src/router/router.go index 9a9caea..e614457 100644 --- a/src/router/router.go +++ b/src/router/router.go @@ -46,7 +46,7 @@ func (r *Router) resolve(path string) *Route { } func (r *Router) ServeHTTP(rw http.ResponseWriter, req *http.Request) { - path := req.Url.Path + path := req.URL.Path route := r.resolve(path) if route == nil { @@ -57,29 +57,8 @@ func (r *Router) ServeHTTP(rw http.ResponseWriter, req *http.Request) { context := &Context{} context.Req = req context.Out = rw - context.vars = regexGroups(path, route.regex) + context.Vars = regexGroups(path, route.regex) context.index = -1 context.chain = route.chain context.Next() } - -func regexGroups(input string, regex *regexp.Regexp) map[string]string { - groups := make(map[string]string) - matches := regex.FindStringSubmatchIndex(input) - for i, key := range regex.SubexpNames()[1:] { - groups[key] = input[matches[i*2+2]:matches[i*2+3]] - } - return groups -} - -func routeRegexp(route string) *regexp.Regexp { - chunks := regexp.MustCompile(`[\*\:]\w+`) - output := chunks.ReplaceAllStringFunc(route, func(m string) string { - if m[0:1] == `*` { - return "(?P<" + m[1:] + ">.+)" - } - return "(?P<" + m[1:] + ">[^/]+)" - }) - output = "^" + output + "$" - return regexp.MustCompile(output) -}