将工厂改成黑盒模式,降低用户使用成本

This commit is contained in:
2025-11-30 15:54:27 +08:00
parent 6323b49517
commit d454d8e143
18 changed files with 2075 additions and 1046 deletions

View File

@@ -0,0 +1,61 @@
package main
import (
"log"
"net/http"
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"`
}
// 获取用户列表使用Handler和PaginationRequest
func GetUserList(h *commonhttp.Handler) {
var req ListUserRequest
// 方式1从JSON请求体解析分页字段会自动解析
if h.Request().Method == http.MethodPost {
if err := h.ParseJSON(&req); err != nil {
h.WriteJSON(http.StatusBadRequest, 400, "请求参数解析失败", nil)
return
}
} else {
// 方式2从查询参数解析分页
pagination := h.ParsePaginationRequest()
req.PaginationRequest = *pagination
req.Keyword = h.GetQuery("keyword", "")
}
// 使用分页方法
page := req.GetPage() // 获取页码默认1
size := req.GetSize() // 获取每页数量默认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)
// 返回分页响应
h.SuccessPage(users, total, page, size)
}
func main() {
http.HandleFunc("/users", commonhttp.HandleFunc(GetUserList))
log.Println("Server started on :8080")
log.Fatal(http.ListenAndServe(":8080", nil))
}