router servehttp

This commit is contained in:
Nazar Kanaev 2021-03-16 16:06:31 +00:00
parent 4a4303afef
commit f214c3166b

View File

@ -1,6 +1,7 @@
package router
import (
"net/http"
"regexp"
)
@ -35,7 +36,7 @@ func (r *Router) For(path string, handler Handler) {
r.routes = append(r.routes, x)
}
func (r *Router) resolve(path string) *route {
func (r *Router) resolve(path string) *Route {
for _, r := range r.routes {
if r.regex.MatchString(path) {
return &r
@ -44,6 +45,24 @@ func (r *Router) resolve(path string) *route {
return nil
}
func (r *Router) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
path := req.Url.Path
route := r.resolve(path)
if route == nil {
rw.WriteHeader(http.StatusNotFound)
return
}
context := &Context{}
context.Req = req
context.Out = rw
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)