将工厂改成黑盒模式,降低用户使用成本
This commit is contained in:
61
examples/http_pagination_example.go
Normal file
61
examples/http_pagination_example.go
Normal 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))
|
||||
}
|
||||
Reference in New Issue
Block a user