/
outputer.go
58 lines (49 loc) · 1.09 KB
/
outputer.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 runner
import (
"errors"
jsoniter "github.com/json-iterator/go"
"io"
"os"
"path/filepath"
)
// OutputWriter outputs content to writers.
type OutputWriter struct {
JSON bool
}
// NewOutputWriter creates a new OutputWriter
func NewOutputWriter(json bool) *OutputWriter {
return &OutputWriter{JSON: json}
}
func (o *OutputWriter) createFile(filename string, appendToFile bool) (*os.File, error) {
if filename == "" {
return nil, errors.New("empty filename")
}
dir := filepath.Dir(filename)
if dir != "" {
if _, err := os.Stat(dir); os.IsNotExist(err) {
err := os.MkdirAll(dir, os.ModePerm)
if err != nil {
return nil, err
}
}
}
var file *os.File
var err error
if appendToFile {
file, err = os.OpenFile(filename, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
} else {
file, err = os.Create(filename)
}
if err != nil {
return nil, err
}
return file, nil
}
func (o *OutputWriter) writeJSONResults(results interface{}, writer io.Writer) error {
encoder := jsoniter.NewEncoder(writer)
err := encoder.Encode(results)
if err != nil {
return err
}
return nil
}