重构项目的实现,优化使用方法与使用逻辑
This commit is contained in:
@@ -1,3 +1,6 @@
|
||||
//go:build example
|
||||
// +build example
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
@@ -8,56 +11,47 @@ import (
|
||||
commonhttp "git.toowon.com/jimmy/go-common/http"
|
||||
)
|
||||
|
||||
// ListUserRequest 用户列表请求(包含分页字段)
|
||||
type ListUserRequest struct {
|
||||
Keyword string `json:"keyword"`
|
||||
commonhttp.PaginationRequest // 嵌入分页请求结构
|
||||
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
|
||||
func main() {
|
||||
if err := factory.Init("config.json"); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
app := factory.Default()
|
||||
chain := app.MiddlewareChain()
|
||||
http.Handle("/users", chain.ThenFunc(listUsers))
|
||||
log.Fatal(http.ListenAndServe(":8080", nil))
|
||||
}
|
||||
|
||||
// 方式1:从JSON请求体解析(分页字段会自动解析)
|
||||
func listUsers(w http.ResponseWriter, r *http.Request) {
|
||||
app := factory.Default()
|
||||
i18n, _ := app.I18n()
|
||||
h := commonhttp.NewHandler(w, r, commonhttp.WithI18n(i18n))
|
||||
|
||||
var req ListUserRequest
|
||||
if r.Method == http.MethodPost {
|
||||
if err := commonhttp.ParseJSON(r, &req); err != nil {
|
||||
commonhttp.WriteJSON(w, http.StatusBadRequest, 400, "请求参数解析失败", nil)
|
||||
if err := h.ParseJSON(&req); err != nil {
|
||||
h.Error("common.invalid_request")
|
||||
return
|
||||
}
|
||||
} else {
|
||||
// 方式2:从查询参数解析分页
|
||||
pagination := commonhttp.ParsePaginationRequest(r)
|
||||
req.PaginationRequest = *pagination
|
||||
p := h.Pagination()
|
||||
req.PaginationRequest = *p
|
||||
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))
|
||||
h.SuccessPage(users, 100)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user