-
Notifications
You must be signed in to change notification settings - Fork 70
/
json.go
65 lines (53 loc) · 1.2 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
package output
import (
"bytes"
"errors"
"fmt"
)
// jsonSetPrettyPrint toggles the pretty printing within
// the json formatter
func (o *Output) jsonSetPrettyPrint(pretty bool) error {
if o == nil || o.jsonFormatter == nil {
return errors.New("invalid output formatter")
}
if pretty {
o.jsonFormatter.DisabledColor = false
o.jsonFormatter.Indent = 2
o.jsonFormatter.Newline = "\n"
} else {
o.jsonFormatter.DisabledColor = true
o.jsonFormatter.Indent = 0
o.jsonFormatter.Newline = ""
}
return nil
}
// JSON prints out data as JSON
func (o *Output) json(data interface{}) error {
var (
formatted []byte
err error
)
// Early quit on no data
if data == nil {
return nil
}
if o == nil || o.jsonFormatter == nil {
return errors.New("invalid output formatter")
}
// ensure right printing config
o.jsonSetPrettyPrint(o.prettyPrint)
// Let's see what they sent us
switch d := data.(type) {
case *bytes.Buffer:
formatted, err = o.jsonFormatter.Format(d.Bytes())
case []byte:
formatted, err = o.jsonFormatter.Format(d)
default:
formatted, err = o.jsonFormatter.Marshal(d)
}
if err != nil {
return err
}
fmt.Println(bytes.NewBuffer(formatted).String())
return nil
}