-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathformatters.go
61 lines (48 loc) · 1.05 KB
/
formatters.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
package main
import (
"encoding/csv"
"encoding/json"
"fmt"
"io"
)
type Formatter interface {
io.Closer
Write(v interface{}, fields ...string) error
}
type CSVFormatter struct {
w *csv.Writer
}
func NewCSVFormatter(writer io.Writer, headers []string) (*CSVFormatter, error) {
w := csv.NewWriter(writer)
err := w.Write(headers)
if err != nil {
return nil, err
}
return &CSVFormatter{
w: csv.NewWriter(writer),
}, nil
}
func (f *CSVFormatter) Write(v interface{}, fields ...string) error {
b, err := json.Marshal(v)
if err != nil {
return fmt.Errorf("failed to serialize v: %v", err)
}
r := append(fields, string(b))
return f.w.Write(r)
}
func (f *CSVFormatter) Close() error {
f.w.Flush()
return nil
}
type JSONFormatter struct {
w *json.Encoder
}
func NewJSONFormatter(writer io.Writer, headers []string) (*JSONFormatter, error) {
return nil, fmt.Errorf("not supported")
}
func (f *JSONFormatter) Write(v interface{}, fields ...string) error {
return fmt.Errorf("not supported")
}
func (f *JSONFormatter) Close() error {
return nil
}