-
Notifications
You must be signed in to change notification settings - Fork 2
/
main.go
51 lines (43 loc) · 1.05 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
// Ch07ex12 has the list endpoint rewritten to use html/template.
package main
import (
"fmt"
"html/template"
"log"
"net/http"
)
var itemTable = template.Must(template.New("table").Parse(`<table>
<tr>
<th>Item</th>
<th>Price</th>
</tr>
{{- range $item, $price := .}}
<tr>
<td>{{$item}}</td>
<td>{{$price}}</td>
</tr>
{{- end}}
</table>`))
func main() {
db := database{"shoes": 50, "socks": 5}
http.HandleFunc("/list", db.list)
http.HandleFunc("/price", db.price)
log.Fatal(http.ListenAndServe("localhost:8000", nil))
}
type dollars float32
func (d dollars) String() string { return fmt.Sprintf("$%.2f", d) }
type database map[string]dollars
func (db database) list(w http.ResponseWriter, req *http.Request) {
if err := itemTable.Execute(w, db); err != nil {
panic(err)
}
}
func (db database) price(w http.ResponseWriter, req *http.Request) {
item := req.URL.Query().Get("item")
if price, ok := db[item]; ok {
fmt.Fprintf(w, "%s\n", price)
} else {
w.WriteHeader(http.StatusNotFound) // 404
fmt.Fprintf(w, "no such item: %q\n", item)
}
}