-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwriter.go
74 lines (61 loc) · 1.32 KB
/
writer.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
70
71
72
73
74
package csv
import (
"bufio"
"io"
)
// Writer can be used to write CSV formatted data to an io.Writer
type Writer struct {
w *bufio.Writer
}
// NewWriter returns a writer ready to write CSV formatted data to the destination
func NewWriter(destination io.Writer) *Writer {
return &Writer{
w: bufio.NewWriter(destination),
}
}
// Write writes a single record as CSV formatted data to the destination
func (w *Writer) Write(record []string) error {
var err error
for i := 0; i < len(record); i++ {
if i > 0 {
_, err = w.w.Write([]byte(`,`))
if err != nil {
return err
}
}
_, err = w.w.Write([]byte(`"`))
if err != nil {
return err
}
for j := 0; j < len(record[i]); j++ {
if record[i][j] == '"' {
_, err = w.w.Write([]byte(`""`))
} else {
_, err = w.w.Write([]byte(record[i][j : j+1]))
}
if err != nil {
return err
}
}
_, err = w.w.Write([]byte(`"`))
if err != nil {
return err
}
}
_, err = w.w.Write([]byte("\r\n"))
return err
}
// WriteAll writes records as CSV formatted data to the destination
func (w *Writer) WriteAll(records [][]string) error {
for i := 0; i < len(records); i++ {
err := w.Write(records[i])
if err != nil {
return err
}
}
return nil
}
// Flush flushes the internal write buffer
func (w *Writer) Flush() error {
return w.w.Flush()
}