-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathwriter.go
68 lines (60 loc) · 1.48 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
package goltsv
import (
"bufio"
"io"
)
// A Writer wites records to a LTSV encoded file.
//
// As returned by NewWriter, a Writer writes records terminated by a
// newline and uses '\t' as the field delimiter.
// Detailed format is described in LTSV official web site. (http://ltsv.org/)
type LTSVWriter struct {
UseCRLF bool
writer *bufio.Writer
}
// NewWriter returns a new Writer that writes to w.
func NewWriter(w io.Writer) *LTSVWriter {
return <SVWriter{
writer: bufio.NewWriter(w),
}
}
// LTSVWriter writes a single LTSV record to w.
// A record is a map of label and value.
// TODO(ymotongpoo): add any feature to organize order of field.
func (w *LTSVWriter) Write(record map[string]string) (err error) {
first := true
for key, value := range record {
if !first {
if _, err = w.writer.WriteRune('\t'); err != nil {
return
}
} else {
first = false
}
field := key + ":" + value
_, err = w.writer.WriteString(field)
if err != nil {
return
}
}
if w.UseCRLF {
_, err = w.writer.WriteString("\r\n")
} else {
err = w.writer.WriteByte('\n')
}
return
}
// WriteAll writes multiple LTSV records to w using Write and then calls Flush.
func (w *LTSVWriter) WriteAll(records []map[string]string) (err error) {
for _, record := range records {
err = w.Write(record)
if err != nil {
return err
}
}
return w.writer.Flush()
}
// Flush writes bufferd data to the underlying bufio.Writer
func (w *LTSVWriter) Flush() (err error) {
return w.writer.Flush()
}