-
Notifications
You must be signed in to change notification settings - Fork 1
/
httpJson.go
61 lines (54 loc) · 1.32 KB
/
httpJson.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
package render
import (
"encoding/json"
"net/http"
)
type infoErr struct {
Message interface{} `json:"message"`
Title string `json:"title,omitempty"`
}
type responseErr struct {
Err infoErr `json:"errors"`
}
// RespondJSON makes the response with payload as json format
func RespondJSON(w http.ResponseWriter, status int, payload interface{}) {
response, err := json.Marshal(payload)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte(err.Error()))
return
}
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(status)
w.Write([]byte(response))
}
// RespondError makes the error response with payload as json format
func RespondError(w http.ResponseWriter, status int, err interface{}) {
var m interface{}
switch err.(type) {
case error:
m = err.(error).Error()
case []error:
var strErrs []string
for _, v := range err.([]error) {
strErrs = append(strErrs, v.Error())
}
m = strErrs
}
e := responseErr{
infoErr{
Message: m,
},
}
RespondJSON(w, status, e)
}
// RespondErrorWithTitle makes the error response with title with payload as json format
func RespondErrorWithTitle(w http.ResponseWriter, status int, message, title string) {
e := responseErr{
infoErr{
Message: message,
Title: title,
},
}
RespondJSON(w, status, e)
}