package main import ( "Study/src/study/day9Interface/Practice/comm" "html/template" "log" "net/http" "os" "sort" ) // 使用html/template包(§4.6)替代printTracks将tracks展示成一个HTML表格。 // 将这个解决方案用在前一个练习中,让每次点击一个列的头部产生一个HTTP请求来排序这个表格。 const TEMPL = ` Document {{range .}} {{end}}
Name Age Sex ID
{{.Name}} {{.Age}} {{.Sex}} {{.ID}}
` func main() { // 构建数据 data := comm.PersonSlice{ {"a", 1, true, 1}, {"b", 2, false, 2}, {"c", 3, true, 3}, {"d", 4, false, 4}, {"e", 5, true, 5}, {"f", 6, false, 6}, {"g", 7, true, 7}, } // 构建模版 templ, err := template.New("test").Parse(TEMPL) if err != nil { log.Fatalln(err) } templ.Execute(os.Stdout, data) // 注册web http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { // 排序 sort.Slice(data, func(i, j int) bool { // 获得sort参数 return data.Less(i, j, r.FormValue("sort")) }) // 输出 templ.Execute(w, data) }) // 监听 http.ListenAndServe(":8080", nil) }