74 lines
1.5 KiB
Go
74 lines
1.5 KiB
Go
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)
|
||
}
|