// Homework 34, problem 2: A task list. // // The tasks are in a package-level slice, and nothing changes them. Finish the // template: show one
  • per task, add " (done)" after the name of a finished // task, and show "Nothing to do." when the slice is empty. Use {{range}}, // {{if}} and {{else}}. To test the empty case, make the slice empty for a moment. // // Run with: go run exercises/34/homework/02-task-list.go package main import ( "bytes" "fmt" "html/template" "net/http" ) type task struct { Name string Done bool } var tasks = []task{ {Name: "Install Go", Done: true}, {Name: "Write a server", Done: true}, {Name: "Finish this homework", Done: false}, } // TODO: show the tasks in this template. const tasksText = ` Tasks

    Tasks

    ` var tasksTemplate = template.Must(template.New("tasks").Parse(tasksText)) func handleHome(w http.ResponseWriter, r *http.Request) { var page bytes.Buffer err := tasksTemplate.Execute(&page, tasks) 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() { 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) } }