代码拉取完成,页面将自动刷新
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
*/
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。