-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathreader.go
65 lines (56 loc) · 1.33 KB
/
reader.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
package main
import (
"bytes"
"encoding/csv"
"fmt"
"io"
)
type (
// Reader reads from a CSV data and mask it.
Reader struct {
r *csv.Reader
template Template
lineNum int
// If SkipHeader is true, the first line is skipped masking as header.
SkipHeader bool
}
)
// NewReader returns a new reader that reads from r while masking data according to the rule.
func NewReader(r io.Reader, template Template) *Reader {
return &Reader{
r: csv.NewReader(r),
template: template,
}
}
// Read reads one record from r.r while masking and return it as a CSV string.
// If there is no data left to be read, Read returns "", io.EOF.
func (r *Reader) Read() (string, error) {
record, err := r.r.Read()
if err != nil {
return "", err
}
r.lineNum++
var tmpl Template
if r.lineNum == 1 && r.SkipHeader {
tmpl, err = r.template.CloneWithEcho()
if err != nil {
return "", fmt.Errorf("failed clone with echo: %v", err)
}
} else {
tmpl = r.template
}
buf := bytes.Buffer{}
err = tmpl.Execute(&buf, toFieldsMap(record))
if err != nil {
return "", fmt.Errorf("failed to execute template: %v", err)
}
return buf.String(), nil
}
func toFieldsMap(record []string) map[string]string {
out := make(map[string]string)
for i, field := range record {
key := fmt.Sprintf("Field%d", i+1)
out[key] = field
}
return out
}