// Homework 34, challenge: Players from a template file. // // Finish the template in templates/players.html, then finish handleHome. // // GET / shows every player. GET /?min=50 shows only players with a score of 50 // or more. A min that is not a whole number replies with status 400. // // Run from this folder, because the template path is relative to it: // cd exercises/34/homework/04-players // go run . package main import ( "bytes" "fmt" "html/template" "net/http" ) type player struct { Name string Score int } type playersPage struct { Min string Players []player } // Nothing changes this slice, so the handlers can share it. var allPlayers = []player{ {Name: "Keiko", Score: 70}, {Name: "Arif", Score: 45}, {Name: "Ada", Score: 90}, } var playersTemplate *template.Template func handleHome(w http.ResponseWriter, r *http.Request) { // TODO: read min, check it, and make a slice of the players to show. data := playersPage{Min: "", Players: allPlayers} var page bytes.Buffer err := playersTemplate.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 main() { parsed, err := template.ParseFiles("templates/players.html") if err != nil { fmt.Println("Could not read the template:", err) fmt.Println("Run this program from its own folder, and check the template.") return } playersTemplate = parsed http.HandleFunc("GET /{$}", handleHome) 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) } }