-
Notifications
You must be signed in to change notification settings - Fork 0
/
response.go
54 lines (45 loc) · 1.07 KB
/
response.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
package jsonapi
import (
"encoding/json"
"net/http"
)
type errorResponse struct {
StatusCode int `json:"status"`
Details string `json:"details"`
Errors []*ErrorItem `json:"errors,omitempty"`
}
var SendResponse = sendResponse
type ResponseSenderFunc = func(w http.ResponseWriter, req *http.Request, v interface{})
func sendResponse(w http.ResponseWriter, _ *http.Request, v interface{}) {
if v == nil {
w.WriteHeader(http.StatusNoContent)
return
}
status := http.StatusOK
switch t := v.(type) {
case error:
status = http.StatusInternalServerError
if c, ok := v.(Coder); ok {
status = c.Code()
}
v = &errorResponse{
StatusCode: status,
Details: t.Error(),
}
case []*ErrorItem:
status = http.StatusBadRequest
v = &errorResponse{
StatusCode: status,
Details: "Validation errors",
Errors: t,
}
default:
// Override status code if we can
if c, ok := v.(Coder); ok {
status = c.Code()
}
}
w.Header().Add("Content-Type", "application/json")
w.WriteHeader(status)
_ = json.NewEncoder(w).Encode(v)
}