调整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

@@ -77,20 +77,26 @@ now := tools.Now()
str := tools.FormatDateTime(now)
```
#### HTTP响应Handler黑盒模式)
#### HTTP响应Factory黑盒模式,推荐
```go
import (
"net/http"
commonhttp "git.toowon.com/jimmy/go-common/http"
"git.toowon.com/jimmy/go-common/factory"
"git.toowon.com/jimmy/go-common/tools"
)
func GetUser(h *commonhttp.Handler) {
id := h.GetQueryInt64("id", 0)
h.Success(data)
func GetUser(w http.ResponseWriter, r *http.Request) {
fac, _ := factory.NewFactoryFromFile("config.json")
// 获取查询参数(使用类型转换方法)
id := tools.ConvertInt64(r.URL.Query().Get("id"), 0)
// 返回成功响应
fac.Success(w, data)
}
http.HandleFunc("/user", commonhttp.HandleFunc(GetUser))
http.HandleFunc("/user", GetUser)
```
#### 中间件(生产级配置)

View File

@@ -32,7 +32,7 @@
| **金额计算** | `YuanToCents()`, `CentsToYuan()`, `FormatYuan()` | `fac.YuanToCents(100.5)` |
| **版本信息** | `GetVersion()` | `fac.GetVersion()` |
| **HTTP响应** | `Success()`, `Error()`, `SuccessPage()` | `fac.Success(w, data)` |
| **HTTP请求** | `ParseJSON()`, `GetQuery()`, `GetTimezone()` 等 | `fac.ParseJSON(r, &req)` |
| **HTTP请求** | `ParseJSON()`, `ConvertInt()`, `GetTimezone()` 等 | `fac.ParseJSON(r, &req)` |
### 🔧 高级功能Get方法仅在必要时使用
@@ -286,11 +286,15 @@ import "net/http"
var req UserRequest
fac.ParseJSON(r, &req)
// 获取查询参数
id := fac.GetQueryInt64(r, "id", 0)
uid := fac.GetQueryUint64(r, "uid", 0)
userId := fac.GetQueryUint32(r, "user_id", 0)
keyword := fac.GetQuery(r, "keyword", "")
// 获取查询参数(使用类型转换方法)
id := fac.ConvertInt64(r.URL.Query().Get("id"), 0)
uid := fac.ConvertUint64(r.URL.Query().Get("uid"), 0)
userId := fac.ConvertUint32(r.URL.Query().Get("user_id"), 0)
keyword := r.URL.Query().Get("keyword") // 字符串直接获取
// 获取表单参数
age := fac.ConvertInt(r.FormValue("age"), 0)
isActive := fac.ConvertBool(r.FormValue("is_active"), false)
// 获取时区需要配合middleware.Timezone使用
timezone := fac.GetTimezone(r)
@@ -657,34 +661,74 @@ fac.Success(w, user, "获取成功") // 自定义消息
- `r`: HTTP请求
- `v`: 目标结构体指针
#### GetQuery(r *http.Request, key, defaultValue string) string
获取查询参数。
#### GetQueryInt(r *http.Request, key string, defaultValue int) int
获取查询整数参数。
#### GetQueryInt64(r *http.Request, key string, defaultValue int64) int64
获取查询64位整数参数。
#### GetQueryUint64(r *http.Request, key string, defaultValue uint64) uint64
获取查询64位无符号整数参数。
#### GetQueryUint32(r *http.Request, key string, defaultValue uint32) uint32
获取查询32位无符号整数参数。
#### GetFormValue(r *http.Request, key, defaultValue string) string
获取表单值。
#### GetTimezone(r *http.Request) string
从请求的context中获取时区需要配合middleware.Timezone使用
### 类型转换方法(黑盒模式)
#### ConvertInt(value string, defaultValue int) int
将字符串转换为int类型。
**参数:**
- `value`: 待转换的字符串
- `defaultValue`: 转换失败或字符串为空时返回的默认值
**示例:**
```go
// 从查询参数获取整数
id := fac.ConvertInt(r.URL.Query().Get("id"), 0)
// 从表单获取整数
age := fac.ConvertInt(r.FormValue("age"), 0)
```
#### ConvertInt64(value string, defaultValue int64) int64
将字符串转换为int64类型。
**示例:**
```go
id := fac.ConvertInt64(r.URL.Query().Get("id"), 0)
```
#### ConvertUint64(value string, defaultValue uint64) uint64
将字符串转换为uint64类型。
**示例:**
```go
uid := fac.ConvertUint64(r.URL.Query().Get("uid"), 0)
```
#### ConvertUint32(value string, defaultValue uint32) uint32
将字符串转换为uint32类型。
**示例:**
```go
userId := fac.ConvertUint32(r.URL.Query().Get("user_id"), 0)
```
#### ConvertBool(value string, defaultValue bool) bool
将字符串转换为bool类型。
**示例:**
```go
isActive := fac.ConvertBool(r.URL.Query().Get("is_active"), false)
```
#### ConvertFloat64(value string, defaultValue float64) float64
将字符串转换为float64类型。
**示例:**
```go
price := fac.ConvertFloat64(r.URL.Query().Get("price"), 0.0)
```
### 日期时间工具方法(黑盒模式)
#### Now(timezone ...string) time.Time

View File

@@ -111,13 +111,14 @@ import (
"net/http"
"git.toowon.com/jimmy/go-common/factory"
commonhttp "git.toowon.com/jimmy/go-common/http"
"git.toowon.com/jimmy/go-common/tools"
)
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)
// 返回成功响应使用factory方法
fac.Success(w, data)
@@ -145,10 +146,10 @@ func GetUserList(w http.ResponseWriter, r *http.Request) {
// 获取分页参数使用factory方法推荐
pagination := fac.ParsePaginationRequest(r)
page := pagination.GetPage()
pageSize := pagination.GetSize()
pageSize := pagination.GetPageSize()
// 获取查询参数(使用factory方法推荐
keyword := fac.GetQuery(r, "keyword", "")
// 获取查询参数(直接使用HTTP原生方法
keyword := r.URL.Query().Get("keyword")
// 查询数据
list, total := getDataList(keyword, page, pageSize)
@@ -170,11 +171,12 @@ http.HandleFunc("/users", GetUserList)
import (
"net/http"
commonhttp "git.toowon.com/jimmy/go-common/http"
"git.toowon.com/jimmy/go-common/tools"
)
func GetUser(w http.ResponseWriter, r *http.Request) {
// 获取查询参数
id := commonhttp.GetQueryInt64(r, "id", 0)
id := tools.ConvertInt64(r.URL.Query().Get("id"), 0)
// 返回成功响应
commonhttp.Success(w, data)
@@ -252,30 +254,41 @@ if err := commonhttp.ParseJSON(r, &req); err != nil {
#### 获取查询参数
```go
// 使用公共方法
name := commonhttp.GetQuery(r, "name", "")
id := commonhttp.GetQueryInt(r, "id", 0)
userId := commonhttp.GetQueryInt64(r, "userId", 0)
isActive := commonhttp.GetQueryBool(r, "isActive", false)
price := commonhttp.GetQueryFloat64(r, "price", 0.0)
import "git.toowon.com/jimmy/go-common/tools"
// 字符串直接获取
name := r.URL.Query().Get("name")
// 使用类型转换方法
id := tools.ConvertInt(r.URL.Query().Get("id"), 0)
userId := tools.ConvertInt64(r.URL.Query().Get("userId"), 0)
isActive := tools.ConvertBool(r.URL.Query().Get("isActive"), false)
price := tools.ConvertFloat64(r.URL.Query().Get("price"), 0.0)
```
#### 获取表单参数
```go
// 使用公共方法
name := commonhttp.GetFormValue(r, "name", "")
age := commonhttp.GetFormInt(r, "age", 0)
userId := commonhttp.GetFormInt64(r, "userId", 0)
isActive := commonhttp.GetFormBool(r, "isActive", false)
import "git.toowon.com/jimmy/go-common/tools"
// 字符串直接获取
name := r.FormValue("name")
// 使用类型转换方法
age := tools.ConvertInt(r.FormValue("age"), 0)
userId := tools.ConvertInt64(r.FormValue("userId"), 0)
isActive := tools.ConvertBool(r.FormValue("isActive"), false)
```
#### 获取请求头
```go
// 使用公共方法
token := commonhttp.GetHeader(r, "Authorization", "")
contentType := commonhttp.GetHeader(r, "Content-Type", "application/json")
// 直接使用HTTP原生方法
token := r.Header.Get("Authorization")
contentType := r.Header.Get("Content-Type")
if contentType == "" {
contentType = "application/json" // 设置默认值
}
```
#### 获取分页参数
@@ -297,9 +310,9 @@ if err := commonhttp.ParseJSON(r, &req); err != nil {
}
// 使用分页方法
page := req.GetPage() // 获取页码默认1
size := req.GetSize() // 获取每页数量默认20最大100优先使用page_size
offset := req.GetOffset() // 计算偏移量
page := req.GetPage() // 获取页码默认1
pageSize := req.GetPageSize() // 获取每页数量默认20最大100
offset := req.GetOffset() // 计算偏移量
```
**方式2从查询参数/form解析分页**
@@ -308,7 +321,7 @@ offset := req.GetOffset() // 计算偏移量
// 使用公共方法
pagination := commonhttp.ParsePaginationRequest(r)
page := pagination.GetPage()
size := pagination.GetSize()
pageSize := pagination.GetPageSize()
offset := pagination.GetOffset()
```
@@ -333,6 +346,7 @@ import (
"net/http"
"git.toowon.com/jimmy/go-common/factory"
commonhttp "git.toowon.com/jimmy/go-common/http"
"git.toowon.com/jimmy/go-common/tools"
)
// 用户结构
@@ -349,10 +363,10 @@ func GetUserList(w http.ResponseWriter, r *http.Request) {
// 获取分页参数(使用公共方法)
pagination := commonhttp.ParsePaginationRequest(r)
page := pagination.GetPage()
pageSize := pagination.GetSize()
pageSize := pagination.GetPageSize()
// 获取查询参数(使用公共方法)
keyword := commonhttp.GetQuery(r, "keyword", "")
// 获取查询参数(直接使用HTTP原生方法)
keyword := r.URL.Query().Get("keyword")
// 查询数据
users, total := queryUsers(keyword, page, pageSize)
@@ -397,8 +411,8 @@ func CreateUser(w http.ResponseWriter, r *http.Request) {
func GetUser(w http.ResponseWriter, r *http.Request) {
fac, _ := factory.NewFactoryFromFile("config.json")
// 获取查询参数(使用factory方法推荐
id := fac.GetQueryInt64(r, "id", 0)
// 获取查询参数(使用类型转换方法
id := tools.ConvertInt64(r.URL.Query().Get("id"), 0)
if id == 0 {
commonhttp.WriteJSON(w, http.StatusBadRequest, 400, "用户ID不能为空", nil)
@@ -593,45 +607,45 @@ if err := commonhttp.ParseJSON(r, &req); err != nil {
}
```
#### GetQuery(r *http.Request, key, defaultValue string) string
#### 获取查询参数和表单参数
获取查询参数(字符串)。
**推荐方式:使用类型转换工具**
#### GetQueryInt(r *http.Request, key string, defaultValue int) int
```go
import "git.toowon.com/jimmy/go-common/tools"
获取查询参数(整数)。
// 字符串直接使用HTTP原生方法
name := r.URL.Query().Get("name")
if name == "" {
name = "default" // 设置默认值
}
#### GetQueryInt64(r *http.Request, key string, defaultValue int64) int64
// 类型转换使用tools包
id := tools.ConvertInt(r.URL.Query().Get("id"), 0)
userId := tools.ConvertInt64(r.URL.Query().Get("userId"), 0)
isActive := tools.ConvertBool(r.URL.Query().Get("isActive"), false)
price := tools.ConvertFloat64(r.URL.Query().Get("price"), 0.0)
获取查询参数int64
// 表单参数类似
age := tools.ConvertInt(r.FormValue("age"), 0)
```
#### GetQueryBool(r *http.Request, key string, defaultValue bool) bool
**类型转换方法说明:**
获取查询参数(布尔值)。
- `tools.ConvertInt(value string, defaultValue int) int` - 转换为int
- `tools.ConvertInt64(value string, defaultValue int64) int64` - 转换为int64
- `tools.ConvertUint64(value string, defaultValue uint64) uint64` - 转换为uint64
- `tools.ConvertUint32(value string, defaultValue uint32) uint32` - 转换为uint32
- `tools.ConvertBool(value string, defaultValue bool) bool` - 转换为bool
- `tools.ConvertFloat64(value string, defaultValue float64) float64` - 转换为float64
#### GetQueryFloat64(r *http.Request, key string, defaultValue float64) float64
**获取请求头:**
获取查询参数(浮点数)。
#### GetFormValue(r *http.Request, key, defaultValue string) string
获取表单值(字符串)。
#### GetFormInt(r *http.Request, key string, defaultValue int) int
获取表单值(整数)。
#### GetFormInt64(r *http.Request, key string, defaultValue int64) int64
获取表单值int64
#### GetFormBool(r *http.Request, key string, defaultValue bool) bool
获取表单值(布尔值)。
#### GetHeader(r *http.Request, key, defaultValue string) string
获取请求头。
```go
// 直接使用HTTP原生方法
token := r.Header.Get("Authorization")
contentType := r.Header.Get("Content-Type")
```
#### ParsePaginationRequest(r *http.Request) *PaginationRequest
@@ -692,12 +706,11 @@ commonhttp.Success(w, data, "操作成功") // 数据+消息
**字段:**
- `Page`: 页码默认1
- `Size`: 每页数量(兼容旧版本)
- `PageSize`: 每页数量推荐使用优先于Size
- `PageSize`: 每页数量
**方法:**
- `GetPage() int`: 获取页码如果未设置则返回默认值1
- `GetSize() int`: 获取每页数量,优先使用PageSize如果未设置则使用Size默认20最大100
- `GetPageSize() int`: 获取每页数量,如果未设置则返回默认20最大限制100
- `GetOffset() int`: 计算数据库查询的偏移量
#### ParsePaginationRequest(r *http.Request) *PaginationRequest