forked from GoesToEleven/GolangTraining
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
69 lines (61 loc) · 1.26 KB
/
main.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
package main
import (
"encoding/csv"
"io"
"log"
"os"
"strconv"
)
type state struct {
id int
name string
abbreviation string
censusRegionName string
}
func parseState(columns map[string]int, record []string) (*state, error) {
id, err := strconv.Atoi(record[columns["id"]])
name := record[columns["name"]]
abbreviation := record[columns["abbreviation"]]
censusRegionName := record[columns["census_region_name"]]
if err != nil {
return nil, err
}
return &state{
id: id,
name: name,
abbreviation: abbreviation,
censusRegionName: censusRegionName,
}, nil
}
func main() {
// #1 open a file
f, err := os.Open("../state_table.csv")
if err != nil {
log.Fatalln(err)
}
defer f.Close()
// #2 parse a csv file
csvReader := csv.NewReader(f)
columns := make(map[string]int)
for rowCount := 0; ; rowCount++ {
record, err := csvReader.Read()
if err == io.EOF {
break
} else if err != nil {
log.Fatalln(err)
}
if rowCount == 0 {
for idx, column := range record {
columns[column] = idx
}
} else {
// #3 do stuff for each row
state, err := parseState(columns, record)
if err != nil {
log.Fatalln(err)
}
// #4 print out each row
log.Println(state)
}
}
}