-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patherrors.go
61 lines (50 loc) · 1.86 KB
/
errors.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
package mux
import "net/http"
// ErrorHandlerFunc handles error returned by `Handler`.
type ErrorHandlerFunc func(err error, w http.ResponseWriter, r *http.Request)
func basicErrorFunc(err error, w http.ResponseWriter, r *http.Request) {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
// Wrapper defines route wrapping methods and error handling
// for `Router` and `Route`.
type Wrapper interface {
ServeHandler(HandlerFunc) func(http.ResponseWriter, *http.Request)
HandlerFunc(HandlerFunc) http.HandlerFunc
ServeMiddleware(MiddlewareFunc) func(http.Handler) http.Handler
MiddlewareFunc(MiddlewareFunc) func(http.Handler) http.Handler
HandleError(error, http.ResponseWriter, *http.Request)
}
// NewDefaultWrapper returns a new default wrapper.
func NewDefaultWrapper(fn ErrorHandlerFunc) Wrapper { return &defaultWrapper{fn} }
type defaultWrapper struct{ ErrorHandler ErrorHandlerFunc }
func (wr *defaultWrapper) ServeHandler(fn HandlerFunc) func(w http.ResponseWriter, r *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
if err := fn(w, r); err != nil {
wr.HandleError(err, w, r)
}
}
}
func (wr *defaultWrapper) HandlerFunc(fn HandlerFunc) http.HandlerFunc {
return wr.ServeHandler(fn)
}
func (wr *defaultWrapper) ServeMiddleware(mwf MiddlewareFunc) func(next http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ctx, err := mwf(w, r)
if err != nil {
wr.HandleError(err, w, r)
return
}
if ctx != nil {
r = r.WithContext(ctx)
}
next.ServeHTTP(w, r)
})
}
}
func (wr *defaultWrapper) MiddlewareFunc(mwf MiddlewareFunc) func(next http.Handler) http.Handler {
return wr.ServeMiddleware(mwf)
}
func (wr *defaultWrapper) HandleError(err error, w http.ResponseWriter, r *http.Request) {
wr.ErrorHandler(err, w, r)
}