-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
113 lines (98 loc) · 1.98 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
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
package main
import (
"encoding/csv"
"fmt"
"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)
stateLookup := map[string]*state{}
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 add each row to stateLookup map
stateLookup[state.abbreviation] = state
}
}
// #5 lookup the state
if len(os.Args) < 2 {
log.Fatalln("expected state abbreviation")
}
abbreviation := os.Args[1]
state, ok := stateLookup[abbreviation]
if !ok {
log.Fatalln("invalid state abbreviation")
}
fmt.Println(`
<html>
<head></head>
<body>
<table>
<tr>
<th>Abbreviation</th>
<th>Name</th>
</tr>`)
fmt.Println(`
<tr>
<td>` + state.abbreviation + `</td>
<td>` + state.name + `</td>
</tr>
`)
fmt.Println(`
</table>
</body>
</html>
`)
}
/*
at terminal:
go install
at terminal:
programName <state abbreviation> > index.html
*/