-
Notifications
You must be signed in to change notification settings - Fork 0
/
record_emitter.go
120 lines (97 loc) · 2 KB
/
record_emitter.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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
package record_emitter
import (
"encoding/csv"
"errors"
"fmt"
"io"
"os"
"strings"
)
type Record struct {
headerMap map[string]int
Row []string
}
func (record *Record) Get(field string) string {
if index, present := record.headerMap[field]; present {
if len(record.Row) >= index {
return strings.Trim(record.Row[index], " ")
} else {
return ""
}
} else {
return ""
}
}
func (record *Record) ProtectedGet(field string) (string, error) {
if index, present := record.headerMap[field]; present {
if len(record.Row) >= index {
return record.Row[index], nil
} else {
return "", errors.New("Index out of bounds of HeaderMap")
}
} else {
return "", errors.New("Value " + field + " not found")
}
}
func NewEmitter(filepath string) RecordEmitter {
recordEmitter := RecordEmitter{Filepath: filepath}
err := recordEmitter.openFile()
if err != nil {
fmt.Println(err)
}
return recordEmitter
}
type RecordEmitter struct {
Filepath string
file *os.File
Reader *csv.Reader
HeaderMap map[string]int
cursor int
}
func (re *RecordEmitter) openFile() error {
file, err := os.Open(re.Filepath)
if err != nil {
return err
}
re.file = file
if err != nil {
return err
}
re.Reader = csv.NewReader(NewCRLFReader(file))
re.Reader.LazyQuotes = true
return nil
}
func (re *RecordEmitter) CloseFile() bool {
re.file.Close()
return true
}
func (re *RecordEmitter) buildHeaderMap(headerRow []string) {
re.HeaderMap = make(map[string]int)
for index, value := range headerRow {
re.HeaderMap[value] = index
}
}
func (re *RecordEmitter) Start() <-chan Record {
ch := make(chan Record)
go func() {
for {
row, err := re.Reader.Read()
if err == io.EOF {
break
} else if err != nil {
fmt.Println("Error:", err)
}
if re.cursor == 0 {
re.cursor += 1
re.buildHeaderMap(row)
continue
}
ch <- Record{Row: row, headerMap: re.HeaderMap}
re.cursor += 1
}
fmt.Println(re.cursor)
re.CloseFile()
close(ch)
}()
return ch
}