forked from go-chi/chi
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathhandler.go
More file actions
67 lines (55 loc) · 1.33 KB
/
handler.go
File metadata and controls
67 lines (55 loc) · 1.33 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
package phi
import (
"encoding/json"
"errors"
"log"
"net/http"
)
// Defines a function which accepts a ResponseWriter, Request and a phi.Error
// this function is used to handle errors thrown by any handler/route
//
// can be set by SetErrorHandler
var ErrorHandler = defaultErrorHandler
func defaultErrorHandler(w http.ResponseWriter, r *http.Request, e *Error) {
if w.Header().Get("Content-Type") == "" {
w.Header().Set("Content-Type", "application/json")
}
parsed, err := json.Marshal(Map{
"error": e.Error,
"message": e.Message,
})
if err == nil {
if _, err = w.Write(parsed); err != nil {
log.Printf("#> defaultHandler: %v", err)
}
return
}
if e.StatusCode != 0 {
w.WriteHeader(e.StatusCode)
}
if _, err = w.Write(parsed); err != nil {
log.Printf("#> defaultHandler: %v", err)
}
}
type Handler func(w *Response, r *Request) *Error
func (h Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if err := h(
&Response{
ResponseWriter: w,
},
&Request{
Request: r,
},
); err != nil {
ErrorHandler(w, r, err)
}
}
// set custom error handler
type ErrorHandlerFunc func(w http.ResponseWriter, r *http.Request, e *Error)
func SetErrorHandler(fn ErrorHandlerFunc) error {
if fn == nil {
return errors.New("couldn't set empty error handling function")
}
ErrorHandler = fn
return nil
}