-
Notifications
You must be signed in to change notification settings - Fork 0
/
json.go
66 lines (55 loc) · 1.73 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
60
61
62
63
64
65
66
package helpers
import (
"bytes"
"encoding/json"
"fmt"
"io"
"strings"
"github.com/sensu/sensu-go/types"
)
var htmlReplacer = strings.NewReplacer(`\u0026`, "&", `\u003c`, "<", `\u003e`, ">")
// PrintJSON takes a record(s) and an io.Writer, converts the record to human-
// readable JSON (pretty-prints), and then prints the result to the given
// writer. Unescapes any &, <, or > characters it finds.
func PrintJSON(r interface{}, io io.Writer) error {
buf := new(bytes.Buffer)
encoder := json.NewEncoder(buf)
encoder.SetIndent("", " ")
encoder.SetEscapeHTML(false)
if err := encoder.Encode(r); err != nil {
return err
}
s := htmlReplacer.Replace(buf.String())
_, err := fmt.Fprintln(io, s)
return err
}
// PrintWrappedJSON takes a record(s) and Resource, converts the record to
// human-readable JSON (pretty-prints), wraps that JSON using types.Wrapper, and
// then prints the result to the given writer. Unescapes any &, <, or >
// characters it finds.
func PrintWrappedJSON(r types.Resource, wr io.Writer) error {
w := wrapResource(r)
buf := new(bytes.Buffer)
encoder := json.NewEncoder(buf)
encoder.SetIndent("", " ")
encoder.SetEscapeHTML(false)
if err := encoder.Encode(w); err != nil {
return err
}
s := htmlReplacer.Replace(buf.String())
_, err := fmt.Fprint(wr, s)
return err
}
// PrintWrappedJSONList takes a resource list and an io.Writer, converts the
// record to human-readable JSON (pretty-prints), wraps that JSON using
// types.Wrapper, and then prints the result to the given writer. Unescapes
// any &, <, or > characters it finds.
func PrintWrappedJSONList(r []types.Resource, io io.Writer) error {
for _, res := range r {
err := PrintWrappedJSON(res, io)
if err != nil {
return err
}
}
return nil
}