forked from nkanaev/yarr
-
Notifications
You must be signed in to change notification settings - Fork 0
/
router.go
82 lines (69 loc) · 1.47 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
package router
import (
"net/http"
"regexp"
"strings"
)
type Handler func(*Context)
type Router struct {
middle []Handler
routes []Route
base string
}
type Route struct {
regex *regexp.Regexp
chain []Handler
}
func NewRouter(base string) *Router {
router := &Router{}
router.middle = make([]Handler, 0)
router.routes = make([]Route, 0)
router.base = base
return router
}
func (r *Router) Use(h Handler) {
r.middle = append(r.middle, h)
}
func (r *Router) For(path string, handler Handler) {
chain := make([]Handler, 0)
chain = append(chain, r.middle...)
chain = append(chain, handler)
x := Route{}
x.regex = routeRegexp(path)
x.chain = chain
r.routes = append(r.routes, x)
}
func (r *Router) resolve(path string) *Route {
for _, route := range r.routes {
if route.regex.MatchString(path) {
return &route
}
}
return nil
}
func (r *Router) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
// autoclose open base url
if r.base != "" {
if r.base == req.URL.Path {
http.Redirect(rw, req, r.base+"/", http.StatusFound)
return
}
if !strings.HasPrefix(req.URL.Path, r.base) {
rw.WriteHeader(http.StatusNotFound)
return
}
}
path := strings.TrimPrefix(req.URL.Path, r.base)
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()
}