-
Notifications
You must be signed in to change notification settings - Fork 52
/
Copy pathcsv.go
64 lines (52 loc) · 987 Bytes
/
csv.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
package main
import (
"encoding/csv"
"errors"
"io"
"os"
"strings"
)
var (
missingEmailField = errors.New("Email field missing in header.")
)
func readCSV(path string) (*[]Recipient, *string, error) {
file, err := os.Open(path)
if err != nil {
return nil, nil, err
}
defer file.Close()
var (
header []string
headerRead bool
emailField string
recipients []Recipient
)
reader := csv.NewReader(file)
for {
fields, err := reader.Read()
if err == io.EOF {
break
} else if err != nil {
return nil, nil, err
}
if headerRead {
recipient := make(Recipient)
for i, key := range header {
recipient[key] = fields[i]
}
recipients = append(recipients, recipient)
} else {
header = fields
for _, v := range header {
if strings.ToLower(v) == "email" {
emailField = v
}
}
if emailField == "" {
return nil, nil, missingEmailField
}
headerRead = true
}
}
return &recipients, &emailField, nil
}