/
json_output.go
executable file
·69 lines (55 loc) · 1.38 KB
/
json_output.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
67
68
69
package command
import (
"encoding/json"
"fmt"
"os"
)
// cliOutput implements OutputFormatter interface by printing the output into std out in JSON format
type jsonOutput struct {
commonOutputFormatter
}
// newJSONOutput is the constructor of jsonOutput
func newJSONOutput() *jsonOutput {
return &jsonOutput{}
}
// WriteOutput implements OutputFormatter interface
func (jo *jsonOutput) WriteOutput() {
if jo.errorOutput != nil {
_, _ = fmt.Fprintln(os.Stderr, jo.getErrorOutput())
return
}
_, _ = fmt.Fprintln(os.Stdout, jo.getCommandOutput())
}
// WriteCommandResult implements OutputFormatter interface
func (jo *jsonOutput) WriteCommandResult(result CommandResult) {
_, _ = fmt.Fprintln(os.Stdout, result.GetOutput())
}
// WriteOutput implements OutputFormatter plus io.Writer interfaces
func (jo *jsonOutput) Write(p []byte) (n int, err error) {
return os.Stdout.Write(p)
}
func (jo *jsonOutput) getErrorOutput() string {
if jo.errorOutput == nil {
return ""
}
return marshalJSONToString(
struct {
Err string `json:"error"`
}{
Err: jo.errorOutput.Error(),
},
)
}
func (jo *jsonOutput) getCommandOutput() string {
if jo.commandOutput == nil {
return ""
}
return marshalJSONToString(jo.commandOutput)
}
func marshalJSONToString(input interface{}) string {
bytes, err := json.Marshal(input)
if err != nil {
return err.Error()
}
return string(bytes)
}