-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcsvreader.go
53 lines (48 loc) · 934 Bytes
/
csvreader.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
package csvreader
import (
"context"
"encoding/csv"
"errors"
"io"
"log"
)
type Reader struct {
Columns []string
Data <-chan map[string]string
}
func NewReader(ctx context.Context, reader io.Reader) (*Reader, error) {
r := csv.NewReader(reader)
header, err := r.Read()
if err == io.EOF {
return nil, errors.New("Unable to read file")
}
c := make(chan map[string]string)
go func() {
defer close(c)
for {
select {
case <-ctx.Done():
return
default:
record, err := r.Read()
if err == io.EOF {
return
}
if err != nil {
log.Println(err)
return
}
c <- toMap(header, record)
}
}
}()
return &Reader{Columns: header, Data: c}, nil
}
func toMap(header []string, values []string) map[string]string {
// TODO: Verify header and values are same length
m := make(map[string]string, len(header))
for i, col := range header {
m[col] = values[i]
}
return m
}