GolangStudy/src/study/day9Interface/Practice/7.9.go

74 lines
1.5 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

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 = `
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<!--额加个边框吧-->
<table border="1" cellspacing="0">
<tr>
<th><a href="/?sort=Name">Name</a></th>
<th><a href="/?sort=Age">Age</a></th>
<th><a href="./?sort=Sex">Sex</a></th>
<th><a href="./?sort=ID">ID</a></th>
</tr>
{{range .}}
<tr>
<td>{{.Name}}</td>
<td>{{.Age}}</td>
<td>{{.Sex}}</td>
<td>{{.ID}}</td>
</tr>
{{end}}
</table>
</body>
</html>
`
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)
}