// Chapter 43 example: a template in a string, filled from a struct. // Run with: go run exercises/43/01-first-template.go package main import ( "fmt" "html/template" "net/http" ) type playerPage struct { Name string Level int } const playerText = `
Level {{.Level}}
` var playerTemplate = template.Must(template.New("player").Parse(playerText)) func handleHome(w http.ResponseWriter, r *http.Request) { data := playerPage{Name: "Keiko", Level: 7} w.Header().Set("Content-Type", "text/html; charset=utf-8") err := playerTemplate.Execute(w, data) if err != nil { fmt.Println("Template error:", err) } } func main() { 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) } }