-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathresponse.go
102 lines (86 loc) · 2.49 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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
package rest
import (
"bytes"
"encoding/json"
"errors"
"log"
"net/http"
"net/url"
"strings"
)
// HttpError - structure for http errors
type HttpError struct {
Err string `json:"error"`
Message string `json:"message,omitempty"`
TraceID string `json:"trace_id,omitempty"`
}
var (
ErrUnmarshal = errors.New("UNMARSHAL_ERROR")
ErrMissingField = errors.New("MISSING_FIELD")
ErrNotFound = errors.New("NOT_FOUND")
ErrValidate = errors.New("VALIDATION_ERROR")
)
// Just to confirm Error interface
func (e HttpError) Error() string {
return e.Err
}
// RenderJSON sends data as json
func RenderJSON(w http.ResponseWriter, code int, data interface{}) {
buf := &bytes.Buffer{}
enc := json.NewEncoder(buf)
enc.SetEscapeHTML(true)
if data != nil {
if err := enc.Encode(data); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
if w.Header().Get("Content-Type") == "" {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
}
w.WriteHeader(code)
_, _ = w.Write(buf.Bytes())
}
// JsonResponse - write a response with application/json Content-Type header
func JsonResponse(w http.ResponseWriter, data interface{}) {
RenderJSON(w, http.StatusOK, data)
}
// TextResponse - write a response with application/text Content-Type header
func TextResponse(w http.ResponseWriter, data string) {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte(data))
}
// OkResponse - write OK response with application/json Content-Type header
func OkResponse(w http.ResponseWriter) {
RenderJSON(w, http.StatusOK, struct {
OK bool `json:"ok"`
}{
OK: true,
})
}
// ErrorResponse - write a HttpError structure as response
func ErrorResponse(w http.ResponseWriter, r *http.Request, code int, error error, msg string) {
err := HttpError{
Err: http.StatusText(code),
Message: msg,
TraceID: r.Header.Get("Uber-Trace-Id"),
}
if error != nil {
err.Err = error.Error()
}
err.Err = strings.ToUpper(err.Err)
err.Err = strings.Replace(err.Err, " ", "_", -1)
uri := r.URL.String()
if qun, e := url.QueryUnescape(uri); e == nil {
uri = qun
}
log.Printf("[DEBUG] %s - %s - %d (%s) - %s - %s", r.Method, uri, code, http.StatusText(code), err, msg)
RenderJSON(w, code, err)
}
// NotFound - return error page for not found
func NotFound(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "text/plain")
w.WriteHeader(http.StatusNotFound)
_, _ = w.Write([]byte("Not found."))
}