64 lines
1.7 KiB
Go
64 lines
1.7 KiB
Go
package main
|
||
|
||
import (
|
||
"log"
|
||
"net/http"
|
||
|
||
"git.toowon.com/jimmy/go-common/factory"
|
||
commonhttp "git.toowon.com/jimmy/go-common/http"
|
||
)
|
||
|
||
// ListUserRequest 用户列表请求(包含分页字段)
|
||
type ListUserRequest struct {
|
||
Keyword string `json:"keyword"`
|
||
commonhttp.PaginationRequest // 嵌入分页请求结构
|
||
}
|
||
|
||
// User 用户结构
|
||
type User struct {
|
||
ID int64 `json:"id"`
|
||
Name string `json:"name"`
|
||
Email string `json:"email"`
|
||
}
|
||
|
||
// 获取用户列表(使用公共方法和factory)
|
||
func GetUserList(w http.ResponseWriter, r *http.Request) {
|
||
fac, _ := factory.NewFactoryFromFile("config.json")
|
||
var req ListUserRequest
|
||
|
||
// 方式1:从JSON请求体解析(分页字段会自动解析)
|
||
if r.Method == http.MethodPost {
|
||
if err := commonhttp.ParseJSON(r, &req); err != nil {
|
||
commonhttp.WriteJSON(w, http.StatusBadRequest, 400, "请求参数解析失败", nil)
|
||
return
|
||
}
|
||
} else {
|
||
// 方式2:从查询参数解析分页
|
||
pagination := commonhttp.ParsePaginationRequest(r)
|
||
req.PaginationRequest = *pagination
|
||
req.Keyword = r.URL.Query().Get("keyword")
|
||
}
|
||
|
||
// 使用分页方法
|
||
page := req.GetPage() // 获取页码(默认1)
|
||
pageSize := req.GetPageSize() // 获取每页数量(默认20,最大100)
|
||
_ = req.GetOffset() // 计算偏移量
|
||
|
||
// 模拟查询数据
|
||
users := []User{
|
||
{ID: 1, Name: "User1", Email: "user1@example.com"},
|
||
{ID: 2, Name: "User2", Email: "user2@example.com"},
|
||
}
|
||
total := int64(100)
|
||
|
||
// 返回分页响应(使用factory方法)
|
||
fac.SuccessPage(w, users, total, page, pageSize)
|
||
}
|
||
|
||
func main() {
|
||
http.HandleFunc("/users", GetUserList)
|
||
|
||
log.Println("Server started on :8080")
|
||
log.Fatal(http.ListenAndServe(":8080", nil))
|
||
}
|