package main import ( "bytes" "fmt" "html/template" "net/http" "strconv" ) 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) { minText := r.URL.Query().Get("min") lowest := 0 if minText != "" { number, err := strconv.Atoi(minText) if err != nil { http.Error(w, "min must be a whole number.", http.StatusBadRequest) return } lowest = number } shown := []player{} for _, p := range allPlayers { if p.Score >= lowest { shown = append(shown, p) } } data := playersPage{Min: minText, Players: shown} 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) } }