fix router

This commit is contained in:
Nazar Kanaev 2021-03-16 20:48:00 +00:00
parent f214c3166b
commit 80482e70a8
4 changed files with 29 additions and 24 deletions

View File

@ -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{}) {

24
src/router/match.go Normal file
View File

@ -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)
}

View File

@ -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)
}