-
Notifications
You must be signed in to change notification settings - Fork 0
/
group.go
63 lines (50 loc) · 1.35 KB
/
group.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
package japi
import (
"net/http"
"strings"
)
type group struct {
r *API
prefix string
}
func (g *group) Get(path string, handle http.Handler) {
g.Handle(http.MethodGet, path, handle)
}
func (g *group) Post(path string, handle http.Handler) {
g.Handle(http.MethodPost, path, handle)
}
func (g *group) Put(path string, handle http.Handler) {
g.Handle(http.MethodPut, path, handle)
}
func (g *group) Patch(path string, handle http.Handler) {
g.Handle(http.MethodPatch, path, handle)
}
func (g *group) Delete(path string, handle http.Handler) {
g.Handle(http.MethodDelete, path, handle)
}
func (g *group) Handle(method, path string, handle http.Handler) {
g.r.Handle(method, g.prefix+path, handle)
}
func (g *group) HandleFunc(method, path string, handle http.HandlerFunc) {
g.Handle(method, path, handle)
}
func (g *group) Group(path string) Router {
return &group{prefix: g.prefix + path, r: g.r}
}
func (g *group) Use(mw ...Middleware) {
g.r.Use(func(next http.Handler) http.Handler {
mwNext := next
// TODO (jv) do we need to reverse?
for _, fn := range mw {
mwNext = fn(mwNext)
}
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Only use the middleware if path belongs to group.
if strings.HasPrefix(r.URL.Path, g.prefix) {
mwNext.ServeHTTP(w, r)
} else {
next.ServeHTTP(w, r)
}
})
})
}