-
Notifications
You must be signed in to change notification settings - Fork 2
/
route.go
86 lines (71 loc) · 1.76 KB
/
route.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
83
84
85
86
package hermes
import "fmt"
type route struct {
prefix string
router *router
middlewares []Middleware
}
func (r *route) path(subpath string) string {
if len(subpath) > 0 && subpath[0] == '/' {
subpath = subpath[1:]
}
if subpath == "" {
return r.prefix
}
if r.prefix == "" {
return subpath
}
return fmt.Sprintf("%s/%s", r.prefix, subpath)
}
func (r *route) handle(method, path string, handler Handler) {
if path[0] != '/' {
panic("path must begin with '/' in path '" + path + "'")
}
root, ok := r.router.children[method]
if !ok {
root = newNode()
r.router.children[method] = root
}
root.Add(r.path(path), handler, nil, r.middlewares)
}
func (r *route) Delete(path string, handler Handler) {
r.handle("DELETE", path, handler)
}
func (r *route) Get(path string, handler Handler) {
r.handle("GET", path, handler)
}
func (r *route) Post(path string, handler Handler) {
r.handle("POST", path, handler)
}
func (r *route) Put(path string, handler Handler) {
r.handle("PUT", path, handler)
}
func (r *route) Head(path string, handler Handler) {
r.handle("HEAD", path, handler)
}
func (r *route) Options(path string, handler Handler) {
r.handle("OPTIONS", path, handler)
}
func (r *route) Patch(path string, handler Handler) {
r.handle("PATCH", path, handler)
}
func (r *route) Prefix(path string) Routable {
return &route{
prefix: r.path(path),
router: r.router,
middlewares: r.middlewares,
}
}
func (r *route) Group(h func(Routable)) {
h(r)
}
func (r *route) Use(middlewares ...Middleware) {
r.middlewares = append(r.middlewares, middlewares...)
}
func (r *route) With(middlewares ...Middleware) Routable {
return &route{
prefix: r.prefix,
router: r.router,
middlewares: append(r.middlewares, middlewares...),
}
}