// Chapter 34 example: a template in its own file. // // Run from this folder, because the template path is relative to it: // cd exercises/34/05-template-file // go run . package main import ( "bytes" "fmt" "html/template" "net/http" ) type scorePage struct { Player string Scores []int } var scoreTemplate *template.Template func handleHome(w http.ResponseWriter, r *http.Request) { data := scorePage{Player: "Keiko", Scores: []int{40, 25, 70}} var page bytes.Buffer err := scoreTemplate.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/scores.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 } scoreTemplate = 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) } }