-
Notifications
You must be signed in to change notification settings - Fork 0
/
sheet.go
76 lines (65 loc) · 1.43 KB
/
sheet.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
package sheet
import (
"encoding/csv"
"fmt"
"io"
)
type Handler func(params []string, data *map[string]interface{}) error
type Operation struct {
Columns []int
Handler Handler
}
type Row struct {
Data map[string]interface{}
Operations []Operation
}
type CSV struct {
Data io.ReadCloser
IgnoreRows []int
Row Row
Delimiter rune
}
func Consume(csvDefinition CSV) error {
// Defer closing the file
defer csvDefinition.Data.Close()
// New CSV Reader
reader := csv.NewReader(csvDefinition.Data)
if csvDefinition.Delimiter != 0 {
reader.Comma = csvDefinition.Delimiter
}
records, err := reader.ReadAll()
if err != nil {
return err
}
// Handle each record
for i, record := range records {
if !rowIgnored(i, csvDefinition.IgnoreRows) {
handleRecord(i, record, csvDefinition.Row)
}
}
// OK
return nil
}
func rowIgnored(rowNumber int, ignoredRows []int) bool {
for _, ignoredRow := range ignoredRows {
if ignoredRow == rowNumber {
return true
}
}
return false
}
func handleRecord(index int, record []string, row Row) {
row.Data = make(map[string]interface{})
for _, model := range row.Operations {
var params = []string{}
for _, columnNumber := range model.Columns {
params = append(params, record[columnNumber])
}
err := model.Handler(params, &row.Data)
if err != nil {
// If there's an error, break out
fmt.Printf("Skipping row %v\nError: %v\n", index, err)
return
}
}
}