Chapter 16 - HTML Templates
Exercise 2: An HTML Template
Complete the code in grocery.go
and list.html
below.
When a browser visits http://localhost:8080/fruit
, your app should respond with this HTML (the spacing doesn’t have to match exactly):
<html>
<ul>
<li>apples</li>
<li>oranges</li>
<li>pears</li>
</ul>
</html>
And when a browser visits http://localhost:8080/meat
, your app should respond with this HTML:
<html>
<ul>
<li>chicken</li>
<li>beef</li>
<li>lamb</li>
</ul>
</html>
Solution
grocery.go
package main
import (
"html/template"
"log"
"net/http"
)
func check(err error) {
if err != nil {
log.Fatal(err)
}
}
func writeList(writer http.ResponseWriter, list []string) {
html, err := template.ParseFiles("list.html")
check(err)
err = html.Execute(writer, list)
check(err)
}
func fruitHandler(writer http.ResponseWriter, request *http.Request) {
writeList(writer, []string{"apples", "oranges", "pears"})
}
func meatHandler(writer http.ResponseWriter, request *http.Request) {
writeList(writer, []string{"chicken", "beef", "lamb"})
}
func main() {
http.HandleFunc("/fruit", fruitHandler)
http.HandleFunc("/meat", meatHandler)
err := http.ListenAndServe("localhost:8080", nil)
log.Fatal(err)
}
list.html
<html>
<ul>
{{range .}}
<li>{{.}}</li>
{{end}}
</ul>
</html>