-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcsv_reader.go
More file actions
81 lines (64 loc) · 1.9 KB
/
Copy pathcsv_reader.go
File metadata and controls
81 lines (64 loc) · 1.9 KB
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
75
76
77
78
79
80
81
package ratchet_processors
import (
"encoding/csv"
"fmt"
"io"
"github.com/licaonfee/ratchet/data"
"github.com/licaonfee/ratchet/processors"
"github.com/licaonfee/ratchet/util"
)
// CSVReader is a ratchet DataProcessor for extracting data from CSV files
type CSVReader struct {
reader *csv.Reader
headers []string
}
// Assert CSVReader satisfies the interface processors.DataProcessor
var _ processors.DataProcessor = &CSVReader{}
// NewCSVReader creates a new CSVReader that will read CSV data from an io.Reader
func NewCSVReader(reader io.Reader) (*CSVReader, error) {
csvReader := csv.NewReader(reader)
headers, err := csvReader.Read()
if err == io.EOF {
return nil, fmt.Errorf("unable to read headers from CSV: EOF received")
}
if err != nil {
return nil, fmt.Errorf("error reading headers from CSV: %s", err)
}
return &CSVReader{
reader: csvReader,
headers: headers,
}, nil
}
// ProcessData will be called for each data sent from the previous stage.
func (r *CSVReader) ProcessData(d data.JSON, outputChan chan data.JSON, killChan chan error) {
r.forEachData(killChan, func(d data.JSON) {
outputChan <- d
})
}
func (r *CSVReader) forEachData(killChan chan error, forEach func(d data.JSON)) {
for {
row, err := r.reader.Read()
if err != nil {
if err == io.EOF {
break
}
util.KillPipelineIfErr(fmt.Errorf("Error reading CSV rows: %s", err), killChan)
}
fields := make([]interface{}, len(row))
for i, v := range row {
fields[i] = v
}
rows := [][]interface{}{fields}
d, err := data.JSONFromHeaderAndRows(r.headers, rows)
if err != nil {
util.KillPipelineIfErr(fmt.Errorf("Error marshaling CSV rows: %s", err), killChan)
}
forEach(d)
}
}
// Finish will be called after the previous stage has finished sending data,
func (r *CSVReader) Finish(outputChan chan data.JSON, killChan chan error) {
}
func (r *CSVReader) String() string {
return "CSVReader"
}