// Chapter 34 example: range and if in a template. // Run with: go run exercises/34/03-range-and-if.go package main import ( "bytes" "fmt" "html/template" "net/http" ) type item struct { Name string Rare bool } type listPage struct { Title string Items []item } const listText = ` {{.Title}}

{{.Title}}

` var listTemplate = template.Must(template.New("list").Parse(listText)) // render builds the page in memory, and sends it only if that worked. func render(w http.ResponseWriter, data listPage) { var page bytes.Buffer err := listTemplate.Execute(&page, data) if err != nil { fmt.Println("Template error:", err) http.Error(w, "The page could not be built.", http.StatusInternalServerError) return } w.Header().Set("Content-Type", "text/html; charset=utf-8") page.WriteTo(w) } func handleBag(w http.ResponseWriter, r *http.Request) { data := listPage{ Title: "My bag", Items: []item{ {Name: "sword", Rare: false}, {Name: "moon stone", Rare: true}, {Name: "potion", Rare: false}, }, } render(w, data) } func handleEmpty(w http.ResponseWriter, r *http.Request) { render(w, listPage{Title: "An empty bag"}) } func main() { http.HandleFunc("GET /{$}", handleBag) http.HandleFunc("GET /empty", handleEmpty) fmt.Println("Server running at http://localhost:8080") fmt.Println("Press Ctrl+C to stop it.") err := http.ListenAndServe("localhost:8080", nil) if err != nil { fmt.Println("Server stopped:", err) } }