-
Notifications
You must be signed in to change notification settings - Fork 4
/
csv.go
56 lines (51 loc) · 1.19 KB
/
csv.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
package util
import (
"bytes"
"encoding/csv"
"fmt"
"strings"
"github.com/pkg/errors"
)
type csvInterface interface {
ToCSV() ([]string, [][]string)
}
func ToCSV(data any) ([]string, [][]string, error) {
if x, ok := data.(csvInterface); ok {
cols, rows := x.ToCSV()
return cols, rows, nil
}
if x, ok := data.(string); ok {
csvdata, err := csv.NewReader(strings.NewReader(x)).ReadAll()
if err != nil || len(csvdata) == 0 {
return []string{x}, [][]string{}, nil //nolint:nilerr
}
return csvdata[0], csvdata[1:], nil
}
if x, ok := data.(error); ok {
return []string{"Error", "Message"}, [][]string{{fmt.Sprintf("%T", x), x.Error()}}, nil
}
if x, ok := data.(*ErrorDetail); ok {
return []string{"Error", "Message"}, [][]string{{x.Type, x.Message}}, nil
}
return nil, nil, errors.Errorf("unable to transform [%T] to CSV", data)
}
func ToCSVBytes(data any) ([]byte, error) {
cols, rows, err := ToCSV(data)
if err != nil {
return nil, err
}
b := bytes.NewBuffer(nil)
c := csv.NewWriter(b)
err = c.Write(cols)
if err != nil {
return nil, err
}
for _, row := range rows {
err = c.Write(row)
if err != nil {
return nil, err
}
}
c.Flush()
return b.Bytes(), nil
}