调整项目结构,factory只负责暴露方法,不实现业务细节

This commit is contained in:
2025-12-07 00:04:01 +08:00
parent b66f345281
commit 339920a940
23 changed files with 2165 additions and 1231 deletions

View File

@@ -5,6 +5,7 @@ import (
"net/http"
commonhttp "git.toowon.com/jimmy/go-common/http"
"git.toowon.com/jimmy/go-common/factory"
)
// ListUserRequest 用户列表请求(包含分页字段)
@@ -20,21 +21,22 @@ type User struct {
Email string `json:"email"`
}
// 获取用户列表(使用Handler和PaginationRequest
func GetUserList(h *commonhttp.Handler) {
// 获取用户列表(使用公共方法和factory
func GetUserList(w http.ResponseWriter, r *http.Request) {
fac, _ := factory.NewFactoryFromFile("config.json")
var req ListUserRequest
// 方式1从JSON请求体解析分页字段会自动解析
if h.Request().Method == http.MethodPost {
if err := h.ParseJSON(&req); err != nil {
h.WriteJSON(http.StatusBadRequest, 400, "请求参数解析失败", nil)
if r.Method == http.MethodPost {
if err := commonhttp.ParseJSON(r, &req); err != nil {
commonhttp.WriteJSON(w, http.StatusBadRequest, 400, "请求参数解析失败", nil)
return
}
} else {
// 方式2从查询参数解析分页
pagination := h.ParsePaginationRequest()
pagination := commonhttp.ParsePaginationRequest(r)
req.PaginationRequest = *pagination
req.Keyword = h.GetQuery("keyword", "")
req.Keyword = commonhttp.GetQuery(r, "keyword", "")
}
// 使用分页方法
@@ -49,12 +51,12 @@ func GetUserList(h *commonhttp.Handler) {
}
total := int64(100)
// 返回分页响应
h.SuccessPage(users, total, page, size)
// 返回分页响应使用factory方法
fac.SuccessPage(w, users, total, page, size)
}
func main() {
http.HandleFunc("/users", commonhttp.HandleFunc(GetUserList))
http.HandleFunc("/users", GetUserList)
log.Println("Server started on :8080")
log.Fatal(http.ListenAndServe(":8080", nil))