forked from netlify/gotrue
-
Notifications
You must be signed in to change notification settings - Fork 0
/
router.go
92 lines (75 loc) · 1.98 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
83
84
85
86
87
88
89
90
91
92
package api
import (
"context"
"net/http"
"github.com/go-chi/chi"
)
func newRouter() *router {
return &router{chi.NewRouter()}
}
type router struct {
chi chi.Router
}
func (r *router) Route(pattern string, fn func(*router)) {
r.chi.Route(pattern, func(c chi.Router) {
fn(&router{c})
})
}
func (r *router) Get(pattern string, fn apiHandler) {
r.chi.Get(pattern, handler(fn))
}
func (r *router) Post(pattern string, fn apiHandler) {
r.chi.Post(pattern, handler(fn))
}
func (r *router) Put(pattern string, fn apiHandler) {
r.chi.Put(pattern, handler(fn))
}
func (r *router) Delete(pattern string, fn apiHandler) {
r.chi.Delete(pattern, handler(fn))
}
func (r *router) With(fn middlewareHandler) *router {
c := r.chi.With(middleware(fn))
return &router{c}
}
func (r *router) WithBypass(fn func(next http.Handler) http.Handler) *router {
c := r.chi.With(fn)
return &router{c}
}
func (r *router) Use(fn middlewareHandler) {
r.chi.Use(middleware(fn))
}
func (r *router) UseBypass(fn func(next http.Handler) http.Handler) {
r.chi.Use(fn)
}
func (r *router) ServeHTTP(w http.ResponseWriter, req *http.Request) {
r.chi.ServeHTTP(w, req)
}
type apiHandler func(w http.ResponseWriter, r *http.Request) error
func handler(fn apiHandler) http.HandlerFunc {
return fn.serve
}
func (h apiHandler) serve(w http.ResponseWriter, r *http.Request) {
if err := h(w, r); err != nil {
handleError(err, w, r)
}
}
type middlewareHandler func(w http.ResponseWriter, r *http.Request) (context.Context, error)
func (m middlewareHandler) handler(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
m.serve(next, w, r)
})
}
func (m middlewareHandler) serve(next http.Handler, w http.ResponseWriter, r *http.Request) {
ctx, err := m(w, r)
if err != nil {
handleError(err, w, r)
return
}
if ctx != nil {
r = r.WithContext(ctx)
}
next.ServeHTTP(w, r)
}
func middleware(fn middlewareHandler) func(http.Handler) http.Handler {
return fn.handler
}