day9接口 练习7.9

master
独孤伶俜 2022-12-17 13:49:45 +08:00
parent 6a1339b1f2
commit 7ea088b7e3
3 changed files with 105 additions and 28 deletions

View File

@ -1,6 +1,7 @@
package main
import (
"Study/src/study/day9Interface/Practice/comm"
"fmt"
"reflect"
"sort"
@ -17,37 +18,10 @@ import (
// 4. 实现点击一栏就对一栏排序
// 1. 定义数据类型
type Person struct {
Name string
Age int
Sex bool
ID int
}
type PersonSlice []Person
// Less 没有实现sort.Interface的Less方法
func (p PersonSlice) Less(i, j int, field string) bool {
return PersonByField(p[i], p[j], field)
}
// PersonByField 按照字段排序
func PersonByField(i, j Person, field string) bool {
switch field {
case "Name":
return i.Name > j.Name
case "Age":
return i.Age < j.Age
case "Sex":
return i.Sex != j.Sex
case "ID":
return i.ID < j.ID
}
return false
}
func main() {
// 构建数据
data := PersonSlice{
data := comm.PersonSlice{
{"a", 1, true, 1},
{"b", 2, false, 2},
{"c", 3, true, 3},

View File

@ -0,0 +1,73 @@
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)
}

View File

@ -0,0 +1,30 @@
package comm
type Person struct {
Name string
Age int
Sex bool
ID int
}
type PersonSlice []Person
// Less 没有实现sort.Interface的Less方法
func (p PersonSlice) Less(i, j int, field string) bool {
return PersonByField(p[i], p[j], field)
}
// PersonByField 按照字段排序
func PersonByField(i, j Person, field string) bool {
switch field {
case "Name":
return i.Name > j.Name
case "Age":
return i.Age < j.Age
case "Sex":
return i.Sex != j.Sex
case "ID":
return i.ID < j.ID
}
return false
}