-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgroup.go
More file actions
81 lines (67 loc) · 1.48 KB
/
Copy pathgroup.go
File metadata and controls
81 lines (67 loc) · 1.48 KB
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
package drouter
import "net/http"
type Group struct {
parent *Group
router *Router
path string
mdws []Middleware
}
func (g *Group) WithGroup(path string, fn func(g Group)) {
fn(Group{
parent: g,
router: g.router,
path: path,
})
}
func (g *Group) Use(mdws ...Middleware) {
g.mdws = append(g.mdws, mdws...)
}
func (g Group) GET(path string, handler Handler) {
g.addRoute(http.MethodGet, path, handler)
}
func (g Group) POST(path string, handler Handler) {
g.addRoute(http.MethodPost, path, handler)
}
func (g Group) PUT(path string, handler Handler) {
g.addRoute(http.MethodPut, path, handler)
}
func (g Group) PATCH(path string, handler Handler) {
g.addRoute(http.MethodPatch, path, handler)
}
func (g Group) DELETE(path string, handler Handler) {
g.addRoute(http.MethodDelete, path, handler)
}
func (g Group) mergedMdws() []Middleware {
if g.parent == nil {
return g.mdws
}
return append(g.parent.mergedMdws(), g.mdws...)
}
func (g *Group) addRoute(method string, path string, handler Handler) {
p := joinPath(g.pathToGroup(), path)
if p == "" {
p = "/"
}
r := route{
method: method,
path: p,
pathMatcher: newPathMatcher(p),
handler: handler,
group: g,
}
g.router.addRoute(r)
}
func (g Group) pathToGroup() string {
if g.parent == nil {
return g.path
}
return joinPath(g.parent.pathToGroup(), g.path)
}
func joinPath(p1 string, p2 string) string {
switch p2 {
case "", "/":
return p1
default:
return p1 + "/" + p2
}
}