-
Notifications
You must be signed in to change notification settings - Fork 43
/
json.go
59 lines (49 loc) · 1.09 KB
/
json.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
package hap
import (
"encoding/json"
"net/http"
)
// JsonOK sends an HTTP 200 (ok) response.
func JsonOK(res http.ResponseWriter, body interface{}) error {
b, err := json.Marshal(body)
if err != nil {
return err
}
res.WriteHeader(http.StatusOK)
wr := NewChunkedWriter(res, 2048)
_, err = wr.Write(b)
return err
}
// JsonMultiStatus sends an HTTP 207 (multi status) response.
func JsonMultiStatus(res http.ResponseWriter, body interface{}) error {
b, err := json.Marshal(body)
if err != nil {
return err
}
res.WriteHeader(http.StatusMultiStatus)
wr := NewChunkedWriter(res, 2048)
_, err = wr.Write(b)
return err
}
// JsonErrors sends an HTTP 500 (bad request) response including the status in the body.
func JsonError(res http.ResponseWriter, status int) error {
resp := struct {
Status int `json:"status"`
}{
Status: status,
}
b, err := json.Marshal(resp)
if err != nil {
return err
}
res.WriteHeader(http.StatusBadRequest)
_, err = res.Write(b)
return err
}
func toJSON(v interface{}) string {
b, err := json.Marshal(v)
if err != nil {
return ""
}
return string(b)
}