-
-
Notifications
You must be signed in to change notification settings - Fork 9
/
encoder.go
66 lines (55 loc) · 1.6 KB
/
encoder.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
package http
import (
"context"
"encoding/json"
"net/http"
)
type encoder struct{}
type errorResponse struct {
Message string `json:"message"`
Status int `json:"status,omitempty"`
}
func (e encoder) StatusResponse(ctx context.Context, w http.ResponseWriter, response interface{}, status int) {
if response != nil {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(status)
if err := json.NewEncoder(w).Encode(response); err != nil {
w.WriteHeader(http.StatusInternalServerError)
return
}
} else {
w.WriteHeader(status)
}
}
func (e encoder) StatusCreated(w http.ResponseWriter) {
w.WriteHeader(http.StatusCreated)
}
func (e encoder) StatusCreatedData(w http.ResponseWriter, data interface{}) {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(http.StatusCreated)
if err := json.NewEncoder(w).Encode(data); err != nil {
w.WriteHeader(http.StatusInternalServerError)
return
}
}
func (e encoder) NoContent(w http.ResponseWriter) {
w.WriteHeader(http.StatusNoContent)
}
func (e encoder) StatusNotFound(ctx context.Context, w http.ResponseWriter) {
w.WriteHeader(http.StatusNotFound)
}
func (e encoder) StatusInternalError(w http.ResponseWriter) {
w.WriteHeader(http.StatusInternalServerError)
}
func (e encoder) Error(w http.ResponseWriter, err error) {
res := errorResponse{
Message: err.Error(),
}
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(http.StatusInternalServerError)
err = json.NewEncoder(w).Encode(res)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
return
}
}