-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathjson.go
More file actions
100 lines (83 loc) · 1.89 KB
/
json.go
File metadata and controls
100 lines (83 loc) · 1.89 KB
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
// Copyright 2012 by sdm. All rights reserved.
// license that can be found in the LICENSE file.
package wk
import (
"encoding/json"
"io"
"net/http"
)
const (
_jsonPrefix = ""
_jsonIndent = "\t"
)
// JsonResult marshal data and write to response
// ContentType is "application/json"
type JsonResult struct {
NeedIndent bool
Data interface{}
buffer io.Reader
}
// Json return *JsonResult
func Json(a interface{}) *JsonResult {
return &JsonResult{
Data: a,
NeedIndent: false,
}
}
// marshal
func (j *JsonResult) marshal() ([]byte, error) {
if j.NeedIndent {
return json.MarshalIndent(j.Data, _jsonPrefix, _jsonIndent)
}
return json.Marshal(j.Data)
}
// Execute encode result as json and write to response
func (j *JsonResult) Execute(ctx *HttpContext) error {
ctx.ContentType(ContentTypeJson)
if !j.NeedIndent {
w := ctx.Resonse.(io.Writer)
encoder := json.NewEncoder(w)
return encoder.Encode(j.Data)
}
b, err := j.marshal()
if err != nil {
return err
}
_, err = ctx.Write(b)
return err
}
// ContentType return "application/json"
func (j *JsonResult) Type() string {
return ContentTypeJson
}
// WriteTo writes marshaled data to w
func (j *JsonResult) Write(header http.Header, body io.Writer) error {
header.Set(HeaderContentType, j.Type())
b, err := j.marshal()
if err != nil {
return err
}
_, err = body.Write(b)
return err
}
// // Read reads marshaled data
// // TODO: bug fix
// func (j *JsonResult) Read(p []byte) (n int, err error) {
// if j.buffer == nil {
// b, err := j.marshal()
// if err != nil {
// return 0, err
// }
// j.buffer = bytes.NewBuffer(b)
// }
// return j.buffer.Read(p)
// }
// // WriteTo writes marshaled data to w
// func (j *JsonResult) WriteTo(w io.Writer) (n int64, err error) {
// b, err := j.marshal()
// if err != nil {
// return 0, err
// }
// buffer := bytes.NewBuffer(b)
// return buffer.WriteTo(w)
// }