-
-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
json.go
80 lines (67 loc) · 1.82 KB
/
json.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
package herodot
import (
"encoding/json"
"net/http"
"github.com/Sirupsen/logrus"
"github.com/pborman/uuid"
"golang.org/x/net/context"
)
type jsonError struct {
RequestID string `json:"request"`
Message string `json:"message"`
*Error
}
type JSON struct {
Logger logrus.FieldLogger
}
func (h *JSON) WriteCreated(ctx context.Context, w http.ResponseWriter, r *http.Request, location string, e interface{}) {
w.Header().Set("Location", location)
h.WriteCode(ctx, w, r, http.StatusCreated, e)
}
func (h *JSON) Write(ctx context.Context, w http.ResponseWriter, r *http.Request, e interface{}) {
h.WriteCode(ctx, w, r, http.StatusOK, e)
}
func (h *JSON) WriteCode(ctx context.Context, w http.ResponseWriter, r *http.Request, code int, e interface{}) {
js, err := json.Marshal(e)
if err != nil {
h.WriteError(ctx, w, r, err)
return
}
if code == 0 {
code = http.StatusOK
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(code)
w.Write(js)
}
func (h *JSON) WriteError(ctx context.Context, w http.ResponseWriter, r *http.Request, err error) {
e := ToError(err)
h.WriteErrorCode(ctx, w, r, e.StatusCode, err)
return
}
func (h *JSON) WriteErrorCode(ctx context.Context, w http.ResponseWriter, r *http.Request, code int, err error) {
id, _ := ctx.Value(RequestIDKey).(string)
if id == "" {
id = uuid.New()
}
if code == 0 {
code = http.StatusInternalServerError
}
LogError(err, id, code)
je := ToError(err)
je.StatusCode = code
js, err := json.Marshal(&jsonError{
RequestID: id,
Error: ToError(err),
Message: err.Error(),
})
if err != nil {
LogError(err, id, http.StatusInternalServerError)
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(code)
w.Write(js)
}