-
Notifications
You must be signed in to change notification settings - Fork 2
/
response.go
63 lines (52 loc) · 1.48 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
55
56
57
58
59
60
61
62
63
package web
import (
"context"
"encoding/json"
"net/http"
"github.com/pkg/errors"
)
// Respond converts a Go value to JSON and sends it to the client.
func Respond(ctx context.Context, w http.ResponseWriter, data interface{}, statusCode int) error {
// Set the status code for the request logger middleware.
v := ctx.Value(KeyValues).(*Values)
v.StatusCode = statusCode
if statusCode == http.StatusNoContent {
w.WriteHeader(statusCode)
return nil
}
// Convert the response value to JSON.
res, err := json.Marshal(data)
if err != nil {
return err
}
// Respond with the provided JSON.
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(statusCode)
if _, err := w.Write(res); err != nil {
return err
}
return nil
}
// RespondError sends an error reponse back to the client.
func RespondError(ctx context.Context, w http.ResponseWriter, err error) error {
// If the error was of the type *Error, the handler has
// a specific status code and error to return.
if webErr, ok := errors.Cause(err).(*Error); ok {
er := ErrorResponse{
Error: webErr.Err.Error(),
Fields: webErr.Fields,
}
if err := Respond(ctx, w, er, webErr.Status); err != nil {
return err
}
return nil
}
// If not, the handler sent any arbitrary error value so use 500.
er := ErrorResponse{
Error: http.StatusText(http.StatusInternalServerError),
}
if err := Respond(ctx, w, er, http.StatusInternalServerError); err != nil {
return err
}
return nil
}