This repository has been archived by the owner on Feb 5, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
responses.go
83 lines (72 loc) · 1.93 KB
/
responses.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
package apiutil
import (
"encoding/json"
"net/http"
)
// WriteResponse wraps response data in an envelope & writes it
func WriteResponse(w http.ResponseWriter, data interface{}) error {
env := map[string]interface{}{
"meta": map[string]interface{}{
"code": http.StatusOK,
},
"data": data,
}
return jsonResponse(w, env)
}
// WritePageResponse wraps response data and pagination information in an
// envelope and writes it
func WritePageResponse(w http.ResponseWriter, data interface{}, r *http.Request, p Page) error {
if p.PrevPageExists() {
p.PrevURL = p.Prev().SetQueryParams(r.URL).String()
}
if p.NextPageExists() {
p.NextURL = p.Next().SetQueryParams(r.URL).String()
}
env := map[string]interface{}{
"meta": map[string]interface{}{
"code": http.StatusOK,
},
"data": data,
"pagination": p,
}
return jsonResponse(w, env)
}
// WriteMessageResponse includes a message with a data response
func WriteMessageResponse(w http.ResponseWriter, message string, data interface{}) error {
env := map[string]interface{}{
"meta": map[string]interface{}{
"code": http.StatusOK,
"message": message,
},
"data": data,
}
return jsonResponse(w, env)
}
// WriteErrResponse writes a JSON error response message & HTTP status
func WriteErrResponse(w http.ResponseWriter, code int, err error) error {
env := map[string]interface{}{
"meta": map[string]interface{}{
"code": code,
"error": err.Error(),
},
}
res, err := json.MarshalIndent(env, "", " ")
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return err
}
w.WriteHeader(code)
_, err = w.Write(res)
return err
}
func jsonResponse(w http.ResponseWriter, env interface{}) error {
res, err := json.Marshal(env)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return err
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
_, err = w.Write(res)
return err
}