将工厂改成黑盒模式,降低用户使用成本
This commit is contained in:
109
examples/http_handler_example.go
Normal file
109
examples/http_handler_example.go
Normal file
@@ -0,0 +1,109 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"log"
|
||||
"net/http"
|
||||
|
||||
commonhttp "git.toowon.com/jimmy/go-common/http"
|
||||
)
|
||||
|
||||
// 用户结构
|
||||
type User struct {
|
||||
ID int64 `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Email string `json:"email"`
|
||||
}
|
||||
|
||||
// 获取用户列表(使用Handler黑盒模式)
|
||||
func GetUserList(h *commonhttp.Handler) {
|
||||
// 获取分页参数(简洁方式)
|
||||
pagination := h.ParsePaginationRequest()
|
||||
page := pagination.GetPage()
|
||||
pageSize := pagination.GetSize()
|
||||
|
||||
// 获取查询参数(简洁方式)
|
||||
_ = h.GetQuery("keyword", "") // 示例:获取查询参数
|
||||
|
||||
// 模拟查询数据
|
||||
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, pageSize)
|
||||
}
|
||||
|
||||
// 创建用户(使用Handler黑盒模式)
|
||||
func CreateUser(h *commonhttp.Handler) {
|
||||
// 解析请求体(简洁方式)
|
||||
var req struct {
|
||||
Name string `json:"name"`
|
||||
Email string `json:"email"`
|
||||
}
|
||||
|
||||
if err := h.ParseJSON(&req); err != nil {
|
||||
h.WriteJSON(http.StatusBadRequest, 400, "请求参数解析失败", nil)
|
||||
return
|
||||
}
|
||||
|
||||
// 参数验证
|
||||
if req.Name == "" {
|
||||
h.Error(1001, "用户名不能为空")
|
||||
return
|
||||
}
|
||||
|
||||
// 模拟创建用户
|
||||
user := User{
|
||||
ID: 1,
|
||||
Name: req.Name,
|
||||
Email: req.Email,
|
||||
}
|
||||
|
||||
// 返回成功响应(简洁方式)
|
||||
h.SuccessWithMessage("创建成功", user)
|
||||
}
|
||||
|
||||
// 获取用户详情(使用Handler黑盒模式)
|
||||
func GetUser(h *commonhttp.Handler) {
|
||||
// 获取查询参数(简洁方式)
|
||||
id := h.GetQueryInt64("id", 0)
|
||||
|
||||
if id == 0 {
|
||||
h.WriteJSON(http.StatusBadRequest, 400, "用户ID不能为空", nil)
|
||||
return
|
||||
}
|
||||
|
||||
// 模拟查询用户
|
||||
if id == 1 {
|
||||
user := User{ID: 1, Name: "User1", Email: "user1@example.com"}
|
||||
h.Success(user)
|
||||
} else {
|
||||
h.Error(1002, "用户不存在")
|
||||
}
|
||||
}
|
||||
|
||||
func main() {
|
||||
// 方式1:使用HandleFunc包装器(推荐,最简洁)
|
||||
http.HandleFunc("/users", commonhttp.HandleFunc(func(h *commonhttp.Handler) {
|
||||
switch h.Request().Method {
|
||||
case http.MethodGet:
|
||||
GetUserList(h)
|
||||
case http.MethodPost:
|
||||
CreateUser(h)
|
||||
default:
|
||||
h.WriteJSON(http.StatusMethodNotAllowed, 405, "方法不支持", nil)
|
||||
}
|
||||
}))
|
||||
|
||||
// 方式2:手动创建Handler(需要更多控制时)
|
||||
http.HandleFunc("/user", func(w http.ResponseWriter, r *http.Request) {
|
||||
h := commonhttp.NewHandler(w, r)
|
||||
GetUser(h)
|
||||
})
|
||||
|
||||
log.Println("Server started on :8080")
|
||||
log.Fatal(http.ListenAndServe(":8080", nil))
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user