forked from go-kratos/kratos
-
Notifications
You must be signed in to change notification settings - Fork 0
/
json.go
58 lines (48 loc) · 1.36 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
package render
import (
"encoding/json"
"net/http"
"github.com/pkg/errors"
)
var jsonContentType = []string{"application/json; charset=utf-8"}
// JSON common json struct.
type JSON struct {
Code int `json:"code"`
Message string `json:"message"`
TTL int `json:"ttl"`
Data interface{} `json:"data,omitempty"`
}
func writeJSON(w http.ResponseWriter, obj interface{}) (err error) {
var jsonBytes []byte
writeContentType(w, jsonContentType)
if jsonBytes, err = json.Marshal(obj); err != nil {
err = errors.WithStack(err)
return
}
if _, err = w.Write(jsonBytes); err != nil {
err = errors.WithStack(err)
}
return
}
// Render (JSON) writes data with json ContentType.
func (r JSON) Render(w http.ResponseWriter) error {
// FIXME(zhoujiahui): the TTL field will be configurable in the future
if r.TTL <= 0 {
r.TTL = 1
}
return writeJSON(w, r)
}
// WriteContentType write json ContentType.
func (r JSON) WriteContentType(w http.ResponseWriter) {
writeContentType(w, jsonContentType)
}
// MapJSON common map json struct.
type MapJSON map[string]interface{}
// Render (MapJSON) writes data with json ContentType.
func (m MapJSON) Render(w http.ResponseWriter) error {
return writeJSON(w, m)
}
// WriteContentType write json ContentType.
func (m MapJSON) WriteContentType(w http.ResponseWriter) {
writeContentType(w, jsonContentType)
}