调整request的方法,增加类型转换的方法

This commit is contained in:
2025-12-07 09:31:59 +08:00
parent 545c6ef6a4
commit 684923f9cb
8 changed files with 321 additions and 444 deletions

View File

@@ -4,8 +4,9 @@ import (
"log"
"net/http"
commonhttp "git.toowon.com/jimmy/go-common/http"
"git.toowon.com/jimmy/go-common/factory"
commonhttp "git.toowon.com/jimmy/go-common/http"
"git.toowon.com/jimmy/go-common/tools"
)
// 用户结构
@@ -18,14 +19,14 @@ type User struct {
// 获取用户列表使用公共方法和factory
func GetUserList(w http.ResponseWriter, r *http.Request) {
fac, _ := factory.NewFactoryFromFile("config.json")
// 获取分页参数(使用公共方法)
pagination := commonhttp.ParsePaginationRequest(r)
page := pagination.GetPage()
pageSize := pagination.GetSize()
pageSize := pagination.GetPageSize()
// 获取查询参数(使用公共方法)
_ = commonhttp.GetQuery(r, "keyword", "") // 示例:获取查询参数
_ = r.URL.Query().Get("keyword") // 示例:获取查询参数
// 模拟查询数据
users := []User{
@@ -41,7 +42,7 @@ func GetUserList(w http.ResponseWriter, r *http.Request) {
// 创建用户使用公共方法和factory
func CreateUser(w http.ResponseWriter, r *http.Request) {
fac, _ := factory.NewFactoryFromFile("config.json")
// 解析请求体(使用公共方法)
var req struct {
Name string `json:"name"`
@@ -73,9 +74,9 @@ func CreateUser(w http.ResponseWriter, r *http.Request) {
// 获取用户详情使用公共方法和factory
func GetUser(w http.ResponseWriter, r *http.Request) {
fac, _ := factory.NewFactoryFromFile("config.json")
// 获取查询参数(使用公共方法)
id := commonhttp.GetQueryInt64(r, "id", 0)
id := tools.ConvertInt64(r.URL.Query().Get("id"), 0)
if id == 0 {
commonhttp.WriteJSON(w, http.StatusBadRequest, 400, "用户ID不能为空", nil)

View File

@@ -4,14 +4,14 @@ import (
"log"
"net/http"
commonhttp "git.toowon.com/jimmy/go-common/http"
"git.toowon.com/jimmy/go-common/factory"
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 用户结构
@@ -36,13 +36,13 @@ func GetUserList(w http.ResponseWriter, r *http.Request) {
// 方式2从查询参数解析分页
pagination := commonhttp.ParsePaginationRequest(r)
req.PaginationRequest = *pagination
req.Keyword = commonhttp.GetQuery(r, "keyword", "")
req.Keyword = r.URL.Query().Get("keyword")
}
// 使用分页方法
page := req.GetPage() // 获取页码默认1
size := req.GetSize() // 获取每页数量默认20最大100
_ = req.GetOffset() // 计算偏移量
page := req.GetPage() // 获取页码默认1
pageSize := req.GetPageSize() // 获取每页数量默认20最大100
_ = req.GetOffset() // 计算偏移量
// 模拟查询数据
users := []User{
@@ -52,7 +52,7 @@ func GetUserList(w http.ResponseWriter, r *http.Request) {
total := int64(100)
// 返回分页响应使用factory方法
fac.SuccessPage(w, users, total, page, size)
fac.SuccessPage(w, users, total, page, pageSize)
}
func main() {