调整项目结构,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

@@ -57,12 +57,24 @@ CREATE TABLE users (id BIGINT PRIMARY KEY AUTO_INCREMENT, ...);
#### 日期转换
```go
import "git.toowon.com/jimmy/go-common/datetime"
**推荐方式:通过 factory 使用(黑盒模式)**
datetime.SetDefaultTimeZone(datetime.AsiaShanghai)
now := datetime.Now()
str := datetime.FormatDateTime(now)
```go
import "git.toowon.com/jimmy/go-common/factory"
fac, _ := factory.NewFactoryFromFile("config.json")
now := fac.Now("Asia/Shanghai")
str := fac.FormatDateTime(now)
```
**或者直接使用 tools 包:**
```go
import "git.toowon.com/jimmy/go-common/tools"
tools.SetDefaultTimeZone(tools.AsiaShanghai)
now := tools.Now()
str := tools.FormatDateTime(now)
```
#### HTTP响应Handler黑盒模式

View File

@@ -4,6 +4,8 @@
日期转换工具提供了丰富的日期时间处理功能,支持时区设定、格式转换、时间计算等常用操作。
**重要说明**:日期时间功能位于 `tools` 包中,推荐通过 `factory` 包使用(黑盒模式),也可以直接使用 `tools` 包。
## 功能特性
- 支持时区设定和转换
@@ -16,13 +18,34 @@
## 使用方法
### 1. 设置默认时区
### 方式1通过 factory 使用(推荐,黑盒模式)
```go
import "git.toowon.com/jimmy/go-common/datetime"
import "git.toowon.com/jimmy/go-common/factory"
// 创建工厂
fac, _ := factory.NewFactoryFromFile("config.json")
// 获取当前时间
now := fac.Now("Asia/Shanghai")
// 格式化时间
str := fac.FormatDateTime(now)
// 解析时间
t, _ := fac.ParseDateTime("2024-01-01 12:00:00", "Asia/Shanghai")
// 时间计算
tomorrow := fac.AddDays(now, 1)
```
### 方式2直接使用 tools 包
```go
import "git.toowon.com/jimmy/go-common/tools"
// 设置默认时区为上海时区
err := datetime.SetDefaultTimeZone(datetime.AsiaShanghai)
err := tools.SetDefaultTimeZone(tools.AsiaShanghai)
if err != nil {
log.Fatal(err)
}
@@ -30,166 +53,284 @@ if err != nil {
### 2. 获取当前时间
**通过 factory**
```go
// 使用默认时区
now := datetime.Now()
now := fac.Now()
// 使用指定时区
now := datetime.Now(datetime.AsiaShanghai)
now := datetime.Now("America/New_York")
now := fac.Now("Asia/Shanghai")
now := fac.Now("America/New_York")
```
**直接使用 tools**
```go
// 使用默认时区
now := tools.Now()
// 使用指定时区
now := tools.Now(tools.AsiaShanghai)
now := tools.Now("America/New_York")
```
### 3. 解析时间字符串
**通过 factory**
```go
// 使用默认时区解析
t, err := datetime.Parse("2006-01-02 15:04:05", "2024-01-01 12:00:00")
if err != nil {
log.Fatal(err)
}
t, err := fac.ParseDateTime("2024-01-01 12:00:00")
// 使用指定时区解析
t, err := datetime.Parse("2006-01-02 15:04:05", "2024-01-01 12:00:00", datetime.AsiaShanghai)
t, err := fac.ParseDateTime("2024-01-01 12:00:00", "Asia/Shanghai")
// 解析日期
t, err := fac.ParseDate("2024-01-01")
```
**直接使用 tools**
```go
// 使用默认时区解析
t, err := tools.Parse("2006-01-02 15:04:05", "2024-01-01 12:00:00")
// 使用指定时区解析
t, err := tools.Parse("2006-01-02 15:04:05", "2024-01-01 12:00:00", tools.AsiaShanghai)
// 使用常用格式解析
t, err := datetime.ParseDateTime("2024-01-01 12:00:00")
t, err := datetime.ParseDate("2024-01-01")
t, err := tools.ParseDateTime("2024-01-01 12:00:00")
t, err := tools.ParseDate("2024-01-01")
```
### 4. 格式化时间
**通过 factory**
```go
t := time.Now()
// 使用默认时区格式化
str := datetime.Format(t, "2006-01-02 15:04:05")
str := fac.FormatDateTime(t)
str := fac.FormatDate(t)
str := fac.FormatTime(t)
// 使用指定时区格式化
str := datetime.Format(t, "2006-01-02 15:04:05", datetime.AsiaShanghai)
str := fac.FormatDateTime(t, "Asia/Shanghai")
```
**直接使用 tools**
```go
t := time.Now()
// 使用默认时区格式化
str := tools.Format(t, "2006-01-02 15:04:05")
// 使用指定时区格式化
str := tools.Format(t, "2006-01-02 15:04:05", tools.AsiaShanghai)
// 使用常用格式
str := datetime.FormatDateTime(t) // "2006-01-02 15:04:05"
str := datetime.FormatDate(t) // "2006-01-02"
str := datetime.FormatTime(t) // "15:04:05"
str := tools.FormatDateTime(t) // "2006-01-02 15:04:05"
str := tools.FormatDate(t) // "2006-01-02"
str := tools.FormatTime(t) // "15:04:05"
```
### 5. 时区转换
**通过 factory**
```go
t := time.Now()
t2, err := tools.ToTimezone(t, "Asia/Shanghai")
```
// 转换到指定时区
t2, err := datetime.ToTimezone(t, datetime.AsiaShanghai)
if err != nil {
log.Fatal(err)
}
**直接使用 tools**
```go
t := time.Now()
t2, err := tools.ToTimezone(t, tools.AsiaShanghai)
```
### 6. Unix时间戳转换
**通过 factory**
```go
t := time.Now()
// 转换为Unix时间戳
unix := datetime.ToUnix(t)
unix := fac.ToUnix(t)
// 从Unix时间戳创建时间
t2 := datetime.FromUnix(unix)
t2 := fac.FromUnix(unix)
// 转换为Unix毫秒时间戳
unixMilli := datetime.ToUnixMilli(t)
unixMilli := fac.ToUnixMilli(t)
// 从Unix毫秒时间戳创建时间
t3 := datetime.FromUnixMilli(unixMilli)
t3 := fac.FromUnixMilli(unixMilli)
```
**直接使用 tools**
```go
t := time.Now()
// 转换为Unix时间戳
unix := tools.ToUnix(t)
// 从Unix时间戳创建时间
t2 := tools.FromUnix(unix)
// 转换为Unix毫秒时间戳
unixMilli := tools.ToUnixMilli(t)
// 从Unix毫秒时间戳创建时间
t3 := tools.FromUnixMilli(unixMilli)
```
### 7. 时间计算
**通过 factory**
```go
t := time.Now()
// 添加天数
t1 := datetime.AddDays(t, 7)
t1 := fac.AddDays(t, 7)
// 添加月数
t2 := datetime.AddMonths(t, 1)
t2 := fac.AddMonths(t, 1)
// 添加年数
t3 := datetime.AddYears(t, 1)
t3 := fac.AddYears(t, 1)
```
**直接使用 tools**
```go
t := time.Now()
// 添加天数
t1 := tools.AddDays(t, 7)
// 添加月数
t2 := tools.AddMonths(t, 1)
// 添加年数
t3 := tools.AddYears(t, 1)
```
### 8. 时间范围获取
**通过 factory**
```go
t := time.Now()
// 获取一天的开始时间00:00:00
start := datetime.StartOfDay(t)
start := fac.StartOfDay(t)
// 获取一天的结束时间23:59:59.999999999
end := datetime.EndOfDay(t)
end := fac.EndOfDay(t)
// 获取月份的开始时间
monthStart := datetime.StartOfMonth(t)
monthStart := fac.StartOfMonth(t)
// 获取月份的结束时间
monthEnd := datetime.EndOfMonth(t)
monthEnd := fac.EndOfMonth(t)
// 获取年份的开始时间
yearStart := datetime.StartOfYear(t)
yearStart := fac.StartOfYear(t)
// 获取年份的结束时间
yearEnd := datetime.EndOfYear(t)
yearEnd := fac.EndOfYear(t)
```
**直接使用 tools**
```go
t := time.Now()
// 获取一天的开始时间00:00:00
start := tools.StartOfDay(t)
// 获取一天的结束时间23:59:59.999999999
end := tools.EndOfDay(t)
// 获取月份的开始时间
monthStart := tools.StartOfMonth(t)
// 获取月份的结束时间
monthEnd := tools.EndOfMonth(t)
// 获取年份的开始时间
yearStart := tools.StartOfYear(t)
// 获取年份的结束时间
yearEnd := tools.EndOfYear(t)
```
### 9. 时间差计算
**通过 factory**
```go
t1 := time.Now()
t2 := time.Now().Add(24 * time.Hour)
// 计算天数差
days := datetime.DiffDays(t1, t2)
days := fac.DiffDays(t1, t2)
// 计算小时差
hours := datetime.DiffHours(t1, t2)
hours := fac.DiffHours(t1, t2)
// 计算分钟差
minutes := datetime.DiffMinutes(t1, t2)
minutes := fac.DiffMinutes(t1, t2)
// 计算秒数差
seconds := datetime.DiffSeconds(t1, t2)
seconds := fac.DiffSeconds(t1, t2)
```
**直接使用 tools**
```go
t1 := time.Now()
t2 := time.Now().Add(24 * time.Hour)
// 计算天数差
days := tools.DiffDays(t1, t2)
// 计算小时差
hours := tools.DiffHours(t1, t2)
// 计算分钟差
minutes := tools.DiffMinutes(t1, t2)
// 计算秒数差
seconds := tools.DiffSeconds(t1, t2)
```
### 10. 转换为UTC时间用于数据库存储
**直接使用 toolsfactory 暂未提供):**
```go
// 将任意时区的时间转换为UTC
t := time.Now() // 当前时区的时间
utcTime := datetime.ToUTC(t)
utcTime := tools.ToUTC(t)
// 从指定时区转换为UTC
t, _ := datetime.ParseDateTime("2024-01-01 12:00:00", datetime.AsiaShanghai)
utcTime, err := datetime.ToUTCFromTimezone(t, datetime.AsiaShanghai)
t, _ := tools.ParseDateTime("2024-01-01 12:00:00", tools.AsiaShanghai)
utcTime, err := tools.ToUTCFromTimezone(t, tools.AsiaShanghai)
// 解析时间字符串并直接转换为UTC
utcTime, err := datetime.ParseDateTimeToUTC("2024-01-01 12:00:00", datetime.AsiaShanghai)
utcTime, err := tools.ParseDateTimeToUTC("2024-01-01 12:00:00", tools.AsiaShanghai)
// 解析日期并转换为UTC当天的00:00:00 UTC
utcTime, err := datetime.ParseDateToUTC("2024-01-01", datetime.AsiaShanghai)
utcTime, err := tools.ParseDateToUTC("2024-01-01", tools.AsiaShanghai)
```
## API 参考
### 时区常量
**通过 tools 包使用:**
```go
import "git.toowon.com/jimmy/go-common/tools"
const (
UTC = "UTC"
AsiaShanghai = "Asia/Shanghai"
AmericaNewYork = "America/New_York"
EuropeLondon = "Europe/London"
AsiaTokyo = "Asia/Tokyo"
tools.UTC = "UTC"
tools.AsiaShanghai = "Asia/Shanghai"
tools.AmericaNewYork = "America/New_York"
tools.EuropeLondon = "Europe/London"
tools.AsiaTokyo = "Asia/Tokyo"
)
```
@@ -208,15 +349,22 @@ CommonLayouts.RFC3339Nano = time.RFC3339Nano
### 主要函数
**注意**:以下函数可以通过 `factory``tools` 包调用。推荐使用 `factory` 的黑盒模式。
#### SetDefaultTimeZone(timezone string) error
设置默认时区。
设置默认时区(仅 tools 包提供)
**参数:**
- `timezone`: 时区字符串,如 "Asia/Shanghai"
**返回:** 错误信息
**使用方式:**
```go
tools.SetDefaultTimeZone(tools.AsiaShanghai)
```
#### Now(timezone ...string) time.Time
获取当前时间。
@@ -226,105 +374,54 @@ CommonLayouts.RFC3339Nano = time.RFC3339Nano
**返回:** 时间对象
#### Parse(layout, value string, timezone ...string) (time.Time, error)
**使用方式:**
```go
// 通过 factory
now := fac.Now("Asia/Shanghai")
解析时间字符串。
// 直接使用 tools
now := tools.Now(tools.AsiaShanghai)
```
#### ParseDateTime(value string, timezone ...string) (time.Time, error)
解析日期时间字符串2006-01-02 15:04:05
**参数:**
- `layout`: 时间格式,如 "2006-01-02 15:04:05"
- `value`: 时间字符串
- `timezone`: 可选,时区字符串
**返回:** 时间对象和错误信息
#### Format(t time.Time, layout string, timezone ...string) string
**使用方式:**
```go
// 通过 factory
t, err := fac.ParseDateTime("2024-01-01 12:00:00", "Asia/Shanghai")
格式化时间。
// 直接使用 tools
t, err := tools.ParseDateTime("2024-01-01 12:00:00", tools.AsiaShanghai)
```
#### FormatDateTime(t time.Time, timezone ...string) string
格式化日期时间2006-01-02 15:04:05
**参数:**
- `t`: 时间对象
- `layout`: 时间格式
- `timezone`: 可选,时区字符串
**返回:** 格式化后的时间字符串
#### ToTimezone(t time.Time, timezone string) (time.Time, error)
**使用方式:**
```go
// 通过 factory
str := fac.FormatDateTime(t, "Asia/Shanghai")
转换时区。
// 直接使用 tools
str := tools.FormatDateTime(t, tools.AsiaShanghai)
```
**参数:**
- `t`: 时间对象
- `timezone`: 目标时区
**返回:** 转换后的时间对象和错误信息
#### ToUnix(t time.Time) int64
转换为Unix时间戳
#### FromUnix(sec int64, timezone ...string) time.Time
从Unix时间戳创建时间。
#### ToUnixMilli(t time.Time) int64
转换为Unix毫秒时间戳。
#### FromUnixMilli(msec int64, timezone ...string) time.Time
从Unix毫秒时间戳创建时间。
#### AddDays(t time.Time, days int) time.Time
添加天数。
#### AddMonths(t time.Time, months int) time.Time
添加月数。
#### AddYears(t time.Time, years int) time.Time
添加年数。
#### StartOfDay(t time.Time, timezone ...string) time.Time
获取一天的开始时间。
#### EndOfDay(t time.Time, timezone ...string) time.Time
获取一天的结束时间。
#### StartOfMonth(t time.Time, timezone ...string) time.Time
获取月份的开始时间。
#### EndOfMonth(t time.Time, timezone ...string) time.Time
获取月份的结束时间。
#### StartOfYear(t time.Time, timezone ...string) time.Time
获取年份的开始时间。
#### EndOfYear(t time.Time, timezone ...string) time.Time
获取年份的结束时间。
#### DiffDays(t1, t2 time.Time) int
计算两个时间之间的天数差。
#### DiffHours(t1, t2 time.Time) int64
计算两个时间之间的小时差。
#### DiffMinutes(t1, t2 time.Time) int64
计算两个时间之间的分钟差。
#### DiffSeconds(t1, t2 time.Time) int64
计算两个时间之间的秒数差。
更多函数请参考 `factory` 包或 `tools` 包的 API 文档。
### UTC转换函数
@@ -391,7 +488,7 @@ CommonLayouts.RFC3339Nano = time.RFC3339Nano
## 完整示例
### 示例1基本使用
### 示例1通过 factory 使用(推荐)
```go
package main
@@ -399,27 +496,67 @@ package main
import (
"fmt"
"log"
"time"
"git.toowon.com/jimmy/go-common/datetime"
"git.toowon.com/jimmy/go-common/factory"
)
func main() {
// 创建工厂
fac, err := factory.NewFactoryFromFile("config.json")
if err != nil {
log.Fatal(err)
}
// 获取当前时间
now := fac.Now("Asia/Shanghai")
fmt.Printf("Current time: %s\n", fac.FormatDateTime(now))
// 解析时间
t, err := fac.ParseDateTime("2024-01-01 12:00:00", "Asia/Shanghai")
if err != nil {
log.Fatal(err)
}
// 格式化时间
fmt.Printf("Parsed time: %s\n", fac.FormatDateTime(t))
// 时间计算
tomorrow := fac.AddDays(now, 1)
fmt.Printf("Tomorrow: %s\n", fac.FormatDate(tomorrow))
}
```
### 示例2直接使用 tools 包
```go
package main
import (
"fmt"
"log"
"git.toowon.com/jimmy/go-common/tools"
)
func main() {
// 设置默认时区
datetime.SetDefaultTimeZone(datetime.AsiaShanghai)
err := tools.SetDefaultTimeZone(tools.AsiaShanghai)
if err != nil {
log.Fatal(err)
}
// 获取当前时间
now := datetime.Now()
fmt.Printf("Current time: %s\n", datetime.FormatDateTime(now))
now := tools.Now()
fmt.Printf("Current time: %s\n", tools.FormatDateTime(now))
// 时区转换
t, _ := datetime.ParseDateTime("2024-01-01 12:00:00")
t2, _ := datetime.ToTimezone(t, datetime.AmericaNewYork)
fmt.Printf("Time in New York: %s\n", datetime.FormatDateTime(t2))
t, _ := tools.ParseDateTime("2024-01-01 12:00:00")
t2, _ := tools.ToTimezone(t, tools.AmericaNewYork)
fmt.Printf("Time in New York: %s\n", tools.FormatDateTime(t2))
}
```
### 示例2UTC转换数据库存储场景
### 示例3UTC转换数据库存储场景
```go
package main
@@ -428,34 +565,32 @@ import (
"fmt"
"log"
"git.toowon.com/jimmy/go-common/datetime"
"git.toowon.com/jimmy/go-common/tools"
)
func main() {
// 从请求中获取时间(假设是上海时区)
requestTimeStr := "2024-01-01 12:00:00"
requestTimezone := datetime.AsiaShanghai
requestTimezone := tools.AsiaShanghai
// 转换为UTC时间用于数据库存储
dbTime, err := datetime.ParseDateTimeToUTC(requestTimeStr, requestTimezone)
dbTime, err := tools.ParseDateTimeToUTC(requestTimeStr, requestTimezone)
if err != nil {
log.Fatal(err)
}
fmt.Printf("Request time (Shanghai): %s\n", requestTimeStr)
fmt.Printf("Database time (UTC): %s\n", datetime.FormatDateTime(dbTime, datetime.UTC))
fmt.Printf("Database time (UTC): %s\n", tools.FormatDateTime(dbTime, tools.UTC))
// 从数据库读取UTC时间转换为用户时区显示
userTimezone := datetime.AsiaShanghai
displayTime, err := datetime.ToTimezone(dbTime, userTimezone)
userTimezone := tools.AsiaShanghai
displayTime, err := tools.ToTimezone(dbTime, userTimezone)
if err != nil {
log.Fatal(err)
}
fmt.Printf("Display time (Shanghai): %s\n", datetime.FormatDateTime(displayTime, userTimezone))
fmt.Printf("Display time (Shanghai): %s\n", tools.FormatDateTime(displayTime, userTimezone))
}
```
完整示例请参考
- `examples/datetime_example.go` - 基本使用示例
- `examples/datetime_utc_example.go` - UTC转换示例
完整示例请参考 `factory` 包中的 datetime 相关方法,通过 `factory` 调用 `tools` 包中的 datetime 功能。

View File

@@ -26,6 +26,11 @@
| **邮件** | `SendEmail()` | `fac.SendEmail(to, subject, body)` |
| **短信** | `SendSMS()` | `fac.SendSMS(phones, params)` |
| **存储** | `UploadFile()`, `GetFileURL()` | `fac.UploadFile(ctx, key, file)` |
| **日期时间** | `Now()`, `ParseDateTime()`, `FormatDateTime()` 等 | `fac.Now("Asia/Shanghai")` |
| **金额计算** | `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)` |
### 🔧 高级功能Get方法仅在必要时使用
@@ -176,7 +181,83 @@ db.Find(&users)
db.Create(&user)
```
### 8. Redis操作获取客户端对象
### 8. 日期时间操作(黑盒模式
```go
// 获取当前时间
now := fac.Now("Asia/Shanghai")
// 解析时间
t, _ := fac.ParseDateTime("2024-01-01 12:00:00", "Asia/Shanghai")
// 格式化时间
str := fac.FormatDateTime(now)
// 时间计算
tomorrow := fac.AddDays(now, 1)
startOfDay := fac.StartOfDay(now, "Asia/Shanghai")
endOfDay := fac.EndOfDay(now, "Asia/Shanghai")
// Unix时间戳
unix := fac.ToUnix(now)
t2 := fac.FromUnix(unix, "Asia/Shanghai")
```
### 9. 金额计算(黑盒模式)
```go
// 元转分
cents := fac.YuanToCents(100.5) // 10050
// 分转元
yuan := fac.CentsToYuan(10050) // 100.5
// 格式化显示
str := fac.FormatYuan(10050) // "100.50"
```
### 10. 版本信息(黑盒模式)
```go
version := fac.GetVersion()
fmt.Println("当前版本:", version)
```
### 11. HTTP响应黑盒模式
```go
import "net/http"
// 成功响应
fac.Success(w, data)
fac.Success(w, data, "操作成功")
// 分页响应
fac.SuccessPage(w, users, total, page, pageSize)
// 错误响应
fac.Error(w, 1001, "用户不存在")
fac.SystemError(w, "系统错误")
```
### 12. HTTP请求解析黑盒模式
```go
import "net/http"
// 解析JSON
var req UserRequest
fac.ParseJSON(r, &req)
// 获取查询参数
id := fac.GetQueryInt64(r, "id", 0)
keyword := fac.GetQuery(r, "keyword", "")
// 获取时区需要配合middleware.Timezone使用
timezone := fac.GetTimezone(r)
```
### 13. Redis操作获取客户端对象
```go
import (
@@ -481,6 +562,222 @@ func main() {
**返回:** 配置对象
### HTTP响应方法黑盒模式
#### Success(w http.ResponseWriter, data interface{}, message ...string)
发送成功响应。
**参数:**
- `w`: HTTP响应写入器
- `data`: 响应数据
- `message`: 可选,成功消息(如果不提供,使用默认消息)
**示例:**
```go
fac.Success(w, user) // 使用默认消息
fac.Success(w, user, "获取成功") // 自定义消息
```
#### Error(w http.ResponseWriter, code int, message string)
发送错误响应。
**参数:**
- `w`: HTTP响应写入器
- `code`: 业务错误码
- `message`: 错误消息
#### SystemError(w http.ResponseWriter, message string)
发送系统错误响应HTTP 500
**参数:**
- `w`: HTTP响应写入器
- `message`: 错误消息
#### SuccessPage(w http.ResponseWriter, data interface{}, total int64, page, pageSize int, message ...string)
发送分页成功响应。
**参数:**
- `w`: HTTP响应写入器
- `data`: 响应数据列表
- `total`: 总记录数
- `page`: 当前页码
- `pageSize`: 每页大小
- `message`: 可选,成功消息
### HTTP请求方法黑盒模式
#### ParseJSON(r *http.Request, v interface{}) error
解析JSON请求体。
**参数:**
- `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位整数参数。
#### GetFormValue(r *http.Request, key, defaultValue string) string
获取表单值。
#### GetTimezone(r *http.Request) string
从请求的context中获取时区需要配合middleware.Timezone使用
### 日期时间工具方法(黑盒模式)
#### Now(timezone ...string) time.Time
获取当前时间。
**参数:**
- `timezone`: 可选,时区字符串(如 "Asia/Shanghai"),不指定则使用默认时区
#### ParseDateTime(value string, timezone ...string) (time.Time, error)
解析日期时间字符串格式2006-01-02 15:04:05
#### ParseDate(value string, timezone ...string) (time.Time, error)
解析日期字符串格式2006-01-02
#### FormatDateTime(t time.Time, timezone ...string) string
格式化日期时间格式2006-01-02 15:04:05
#### FormatDate(t time.Time, timezone ...string) string
格式化日期格式2006-01-02
#### FormatTime(t time.Time, timezone ...string) string
格式化时间格式15:04:05
#### ToUnix(t time.Time) int64
转换为Unix时间戳
#### FromUnix(sec int64, timezone ...string) time.Time
从Unix时间戳创建时间。
#### ToUnixMilli(t time.Time) int64
转换为Unix毫秒时间戳。
#### FromUnixMilli(msec int64, timezone ...string) time.Time
从Unix毫秒时间戳创建时间。
#### AddDays(t time.Time, days int) time.Time
添加天数。
#### AddMonths(t time.Time, months int) time.Time
添加月数。
#### AddYears(t time.Time, years int) time.Time
添加年数。
#### StartOfDay(t time.Time, timezone ...string) time.Time
获取一天的开始时间00:00:00
#### EndOfDay(t time.Time, timezone ...string) time.Time
获取一天的结束时间23:59:59.999999999)。
#### StartOfMonth(t time.Time, timezone ...string) time.Time
获取月份的开始时间。
#### EndOfMonth(t time.Time, timezone ...string) time.Time
获取月份的结束时间。
#### StartOfYear(t time.Time, timezone ...string) time.Time
获取年份的开始时间。
#### EndOfYear(t time.Time, timezone ...string) time.Time
获取年份的结束时间。
#### DiffDays(t1, t2 time.Time) int
计算两个时间之间的天数差。
#### DiffHours(t1, t2 time.Time) int64
计算两个时间之间的小时差。
#### DiffMinutes(t1, t2 time.Time) int64
计算两个时间之间的分钟差。
#### DiffSeconds(t1, t2 time.Time) int64
计算两个时间之间的秒数差。
### 金额工具方法(黑盒模式)
#### GetMoneyCalculator() *tools.MoneyCalculator
获取金额计算器实例。
#### YuanToCents(yuan float64) int64
元转分。
**示例:**
```go
cents := fac.YuanToCents(100.5) // 返回 10050
```
#### CentsToYuan(cents int64) float64
分转元。
**示例:**
```go
yuan := fac.CentsToYuan(10050) // 返回 100.5
```
#### FormatYuan(cents int64) string
格式化显示金额分转元保留2位小数
**示例:**
```go
str := fac.FormatYuan(10050) // 返回 "100.50"
```
### 版本工具方法(黑盒模式)
#### GetVersion() string
获取版本号。
**说明:**
- 优先从环境变量 `DOCKER_TAG``VERSION` 中读取
- 如果没有设置环境变量,则使用默认版本号
## 设计优势
### 优势总结

View File

@@ -2,16 +2,17 @@
## 概述
HTTP Restful工具提供了标准化的HTTP请求和响应处理功能采用Handler黑盒模式封装了`ResponseWriter``Request`提供简洁的API无需每次都传递这两个参数
HTTP Restful工具提供了标准化的HTTP请求和响应处理功能提供公共方法供外部调用,保持低耦合
## 功能特性
- **黑盒模式**:封装`ResponseWriter``Request`提供简洁的API
- **低耦合设计**提供公共方法不封装Handler结构
- **标准化的响应结构**`{code, message, timestamp, data}`
- **分离HTTP状态码和业务状态码**
- **支持分页响应**
- **提供便捷的请求参数解析方法**
- **支持JSON请求体解析**
- **Factory黑盒模式**:推荐使用 `factory.Success()` 等方法
## 响应结构
@@ -26,6 +27,18 @@ HTTP Restful工具提供了标准化的HTTP请求和响应处理功能采用H
}
```
**结构体类型(暴露在 factory 中):**
```go
// 在 factory 包中可以直接使用
type Response struct {
Code int `json:"code"` // 业务状态码0表示成功
Message string `json:"message"` // 响应消息
Timestamp int64 `json:"timestamp"` // 时间戳
Data interface{} `json:"data"` // 响应数据
}
```
### 分页响应结构
```json
@@ -42,9 +55,116 @@ HTTP Restful工具提供了标准化的HTTP请求和响应处理功能采用H
}
```
**结构体类型(暴露在 factory 中):**
```go
// 在 factory 包中可以直接使用
type PageData struct {
List interface{} `json:"list"` // 数据列表
Total int64 `json:"total"` // 总记录数
Page int `json:"page"` // 当前页码
PageSize int `json:"pageSize"` // 每页大小
}
type PageResponse struct {
Code int `json:"code"`
Message string `json:"message"`
Timestamp int64 `json:"timestamp"`
Data *PageData `json:"data"`
}
```
### 使用暴露的结构体
外部项目可以直接使用 `factory.Response``factory.PageData` 等类型:
```go
import "git.toowon.com/jimmy/go-common/factory"
// 创建标准响应对象
response := factory.Response{
Code: 0,
Message: "success",
Data: userData,
}
// 创建分页数据对象
pageData := &factory.PageData{
List: users,
Total: 100,
Page: 1,
PageSize: 20,
}
// 传递给 Success 方法
fac.Success(w, pageData)
```
## 使用方法
### 1. 创建Handler
### 方式一使用Factory黑盒方法推荐
这是最简单的方式,直接使用 `factory.Success()` 等方法:
```go
import (
"net/http"
"git.toowon.com/jimmy/go-common/factory"
commonhttp "git.toowon.com/jimmy/go-common/http"
)
func GetUser(w http.ResponseWriter, r *http.Request) {
fac, _ := factory.NewFactoryFromFile("config.json")
// 获取查询参数(使用公共方法)
id := commonhttp.GetQueryInt64(r, "id", 0)
// 返回成功响应使用factory方法
fac.Success(w, data)
}
func CreateUser(w http.ResponseWriter, r *http.Request) {
fac, _ := factory.NewFactoryFromFile("config.json")
// 解析JSON使用公共方法
var req struct {
Name string `json:"name"`
}
if err := commonhttp.ParseJSON(r, &req); err != nil {
commonhttp.WriteJSON(w, http.StatusBadRequest, 400, "请求参数解析失败", nil)
return
}
// 返回成功响应使用factory方法
fac.Success(w, data, "创建成功")
}
func GetUserList(w http.ResponseWriter, r *http.Request) {
fac, _ := factory.NewFactoryFromFile("config.json")
// 获取分页参数使用factory方法推荐
pagination := fac.ParsePaginationRequest(r)
page := pagination.GetPage()
pageSize := pagination.GetSize()
// 获取查询参数使用factory方法推荐
keyword := fac.GetQuery(r, "keyword", "")
// 查询数据
list, total := getDataList(keyword, page, pageSize)
// 返回分页响应使用factory方法
fac.SuccessPage(w, list, total, page, pageSize)
}
// 注册路由
http.HandleFunc("/user", GetUser)
http.HandleFunc("/users", GetUserList)
```
### 方式二:直接使用公共方法
如果不想使用Factory可以直接使用 `http` 包的公共方法:
```go
import (
@@ -52,154 +172,110 @@ import (
commonhttp "git.toowon.com/jimmy/go-common/http"
)
// 方式1使用HandleFunc包装器推荐最简洁
func GetUser(h *commonhttp.Handler) {
id := h.GetQueryInt64("id", 0)
h.Success(data)
func GetUser(w http.ResponseWriter, r *http.Request) {
// 获取查询参数
id := commonhttp.GetQueryInt64(r, "id", 0)
// 返回成功响应
commonhttp.Success(w, data)
}
http.HandleFunc("/user", commonhttp.HandleFunc(GetUser))
// 方式2手动创建Handler需要更多控制时
http.HandleFunc("/user", func(w http.ResponseWriter, r *http.Request) {
h := commonhttp.NewHandler(w, r)
GetUser(h)
})
```
### 2. 成功响应
```go
func handler(h *commonhttp.Handler) {
// 简单成功响应data为nil
h.Success(nil)
// 带数据的成功响应
data := map[string]interface{}{
"id": 1,
"name": "test",
func CreateUser(w http.ResponseWriter, r *http.Request) {
// 解析JSON
var req struct {
Name string `json:"name"`
}
if err := commonhttp.ParseJSON(r, &req); err != nil {
commonhttp.WriteJSON(w, http.StatusBadRequest, 400, "请求参数解析失败", nil)
return
}
h.Success(data)
// 带消息的成功响应
h.SuccessWithMessage("操作成功", data)
// 返回成功响应
commonhttp.Success(w, data, "创建成功")
}
```
### 3. 错误响应
### 成功响应
```go
func handler(h *commonhttp.Handler) {
// 业务错误HTTP 200业务code非0
h.Error(1001, "用户不存在")
// 系统错误HTTP 500
h.SystemError("服务器内部错误")
// 其他HTTP错误状态码使用WriteJSON直接指定
// 请求错误HTTP 400
h.WriteJSON(http.StatusBadRequest, 400, "请求参数错误", nil)
// 未授权HTTP 401
h.WriteJSON(http.StatusUnauthorized, 401, "未登录", nil)
// 禁止访问HTTP 403
h.WriteJSON(http.StatusForbidden, 403, "无权限访问", nil)
// 未找到HTTP 404
h.WriteJSON(http.StatusNotFound, 404, "资源不存在", nil)
}
// 使用Factory推荐
fac.Success(w, data) // 只有数据,使用默认消息 "success"
fac.Success(w, data, "操作成功") // 数据+消息
// 或直接使用公共方法
commonhttp.Success(w, data) // 只有数据
commonhttp.Success(w, data, "操作成功") // 数据+消息
```
### 4. 分页响应
### 错误响应
```go
func handler(h *commonhttp.Handler) {
// 获取分页参数
pagination := h.ParsePaginationRequest()
page := pagination.GetPage()
pageSize := pagination.GetSize()
// 查询数据(示例)
list, total := getDataList(page, pageSize)
// 返回分页响应(使用默认消息)
h.SuccessPage(list, total, page, pageSize)
// 返回分页响应(自定义消息)
h.SuccessPage(list, total, page, pageSize, "查询成功")
}
// 使用Factory推荐
fac.Error(w, 1001, "用户不存在") // 业务错误HTTP 200业务code非0
fac.SystemError(w, "服务器内部错误") // 系统错误HTTP 500
// 或直接使用公共方法
commonhttp.Error(w, 1001, "用户不存在")
commonhttp.SystemError(w, "服务器内部错误")
commonhttp.WriteJSON(w, http.StatusBadRequest, 400, "请求参数错误", nil) // 自定义HTTP状态码仅公共方法
```
### 5. 解析请求
### 分页响应
```go
// 使用Factory推荐
fac.SuccessPage(w, list, total, page, pageSize)
fac.SuccessPage(w, list, total, page, pageSize, "查询成功")
// 或直接使用公共方法
commonhttp.SuccessPage(w, list, total, page, pageSize)
commonhttp.SuccessPage(w, list, total, page, pageSize, "查询成功")
```
### 解析请求
#### 解析JSON请求体
```go
func handler(h *commonhttp.Handler) {
type CreateUserRequest struct {
Name string `json:"name"`
Email string `json:"email"`
}
var req CreateUserRequest
if err := h.ParseJSON(&req); err != nil {
h.WriteJSON(http.StatusBadRequest, 400, "请求参数解析失败", nil)
return
}
// 使用req...
// 使用公共方法
var req struct {
Name string `json:"name"`
Email string `json:"email"`
}
if err := commonhttp.ParseJSON(r, &req); err != nil {
commonhttp.WriteJSON(w, http.StatusBadRequest, 400, "请求参数解析失败", nil)
return
}
```
#### 获取查询参数
```go
func handler(h *commonhttp.Handler) {
// 获取字符串参数
name := h.GetQuery("name", "")
email := h.GetQuery("email", "default@example.com")
// 获取整数参数
id := h.GetQueryInt("id", 0)
age := h.GetQueryInt("age", 18)
// 获取int64参数
userId := h.GetQueryInt64("userId", 0)
// 获取布尔参数
isActive := h.GetQueryBool("isActive", false)
// 获取浮点数参数
price := h.GetQueryFloat64("price", 0.0)
}
// 使用公共方法
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)
```
#### 获取表单参数
```go
func handler(h *commonhttp.Handler) {
// 获取表单字符串
name := h.GetFormValue("name", "")
// 获取表单整数
age := h.GetFormInt("age", 0)
// 获取表单int64
userId := h.GetFormInt64("userId", 0)
// 获取表单布尔值
isActive := h.GetFormBool("isActive", false)
}
// 使用公共方法
name := commonhttp.GetFormValue(r, "name", "")
age := commonhttp.GetFormInt(r, "age", 0)
userId := commonhttp.GetFormInt64(r, "userId", 0)
isActive := commonhttp.GetFormBool(r, "isActive", false)
```
#### 获取请求头
```go
func handler(h *commonhttp.Handler) {
token := h.GetHeader("Authorization", "")
contentType := h.GetHeader("Content-Type", "application/json")
}
// 使用公共方法
token := commonhttp.GetHeader(r, "Authorization", "")
contentType := commonhttp.GetHeader(r, "Content-Type", "application/json")
```
#### 获取分页参数
@@ -207,71 +283,55 @@ func handler(h *commonhttp.Handler) {
**方式1使用 PaginationRequest 结构(推荐)**
```go
func handler(h *commonhttp.Handler) {
// 定义请求结构(包含分页字段)
type ListUserRequest struct {
Keyword string `json:"keyword"`
commonhttp.PaginationRequest // 嵌入分页请求结构
}
// 从JSON请求体解析分页字段会自动解析
var req ListUserRequest
if err := h.ParseJSON(&req); err != nil {
h.WriteJSON(http.StatusBadRequest, 400, "请求参数解析失败", nil)
return
}
// 使用分页方法
page := req.GetPage() // 获取页码默认1
size := req.GetSize() // 获取每页数量默认20最大100优先使用page_size
offset := req.GetOffset() // 计算偏移量
// 定义请求结构(包含分页字段)
type ListUserRequest struct {
Keyword string `json:"keyword"`
commonhttp.PaginationRequest // 嵌入分页请求结构
}
// 或者从查询参数/form解析分页
func handler(h *commonhttp.Handler) {
pagination := h.ParsePaginationRequest()
page := pagination.GetPage()
size := pagination.GetSize()
offset := pagination.GetOffset()
// 从JSON请求体解析分页字段会自动解析)
var req ListUserRequest
if err := commonhttp.ParseJSON(r, &req); err != nil {
commonhttp.WriteJSON(w, http.StatusBadRequest, 400, "请求参数解析失败", nil)
return
}
// 使用分页方法
page := req.GetPage() // 获取页码默认1
size := req.GetSize() // 获取每页数量默认20最大100优先使用page_size
offset := req.GetOffset() // 计算偏移量
```
**方式2从查询参数/form解析分页**
```go
// 使用公共方法
pagination := commonhttp.ParsePaginationRequest(r)
page := pagination.GetPage()
size := pagination.GetSize()
offset := pagination.GetOffset()
```
#### 获取时区
```go
func handler(h *commonhttp.Handler) {
// 从请求的context中获取时区
// 如果使用了middleware.Timezone中间件可以从context中获取时区信息
// 如果未设置,返回默认时区 AsiaShanghai
timezone := h.GetTimezone()
}
```
### 6. 访问原始对象
如果需要访问原始的`ResponseWriter``Request`
```go
func handler(h *commonhttp.Handler) {
// 获取原始ResponseWriter
w := h.ResponseWriter()
// 获取原始Request
r := h.Request()
// 获取Context
ctx := h.Context()
}
// 使用公共方法
// 如果使用了middleware.Timezone中间件可以从context中获取时区信息
// 如果未设置,返回默认时区 AsiaShanghai
timezone := commonhttp.GetTimezone(r)
```
## 完整示例
### 使用Factory推荐
```go
package main
import (
"log"
"net/http"
"git.toowon.com/jimmy/go-common/factory"
commonhttp "git.toowon.com/jimmy/go-common/http"
)
@@ -283,91 +343,97 @@ type User struct {
}
// 用户列表接口
func GetUserList(h *commonhttp.Handler) {
// 获取分页参数
pagination := h.ParsePaginationRequest()
func GetUserList(w http.ResponseWriter, r *http.Request) {
fac, _ := factory.NewFactoryFromFile("config.json")
// 获取分页参数(使用公共方法)
pagination := commonhttp.ParsePaginationRequest(r)
page := pagination.GetPage()
pageSize := pagination.GetSize()
// 获取查询参数
keyword := h.GetQuery("keyword", "")
// 获取查询参数(使用公共方法)
keyword := commonhttp.GetQuery(r, "keyword", "")
// 查询数据
users, total := queryUsers(keyword, page, pageSize)
// 返回分页响应
h.SuccessPage(users, total, page, pageSize)
// 返回分页响应使用factory方法
fac.SuccessPage(w, users, total, page, pageSize)
}
// 创建用户接口
func CreateUser(h *commonhttp.Handler) {
// 解析请求体
func CreateUser(w http.ResponseWriter, r *http.Request) {
fac, _ := factory.NewFactoryFromFile("config.json")
// 解析请求体(使用公共方法)
var req struct {
Name string `json:"name"`
Email string `json:"email"`
}
if err := h.ParseJSON(&req); err != nil {
h.WriteJSON(http.StatusBadRequest, 400, "请求参数解析失败", nil)
if err := commonhttp.ParseJSON(r, &req); err != nil {
fac.WriteJSON(w, http.StatusBadRequest, 400, "请求参数解析失败", nil)
return
}
// 参数验证
if req.Name == "" {
h.Error(1001, "用户名不能为空")
fac.Error(w, 1001, "用户名不能为空")
return
}
// 创建用户
user, err := createUser(req.Name, req.Email)
if err != nil {
h.SystemError("创建用户失败")
fac.SystemError(w, "创建用户失败")
return
}
// 返回成功响应
h.SuccessWithMessage("创建成功", user)
// 返回成功响应使用factory方法
fac.Success(w, user, "创建成功")
}
// 获取用户详情接口
func GetUser(h *commonhttp.Handler) {
// 获取查询参数
id := h.GetQueryInt64("id", 0)
func GetUser(w http.ResponseWriter, r *http.Request) {
fac, _ := factory.NewFactoryFromFile("config.json")
// 获取查询参数使用factory方法推荐
id := fac.GetQueryInt64(r, "id", 0)
if id == 0 {
h.WriteJSON(http.StatusBadRequest, 400, "用户ID不能为空", nil)
commonhttp.WriteJSON(w, http.StatusBadRequest, 400, "用户ID不能为空", nil)
return
}
// 查询用户
user, err := getUserByID(id)
if err != nil {
h.SystemError("查询用户失败")
fac.SystemError(w, "查询用户失败")
return
}
if user == nil {
h.Error(1002, "用户不存在")
fac.Error(w, 1002, "用户不存在")
return
}
h.Success(user)
// 返回成功响应使用factory方法
fac.Success(w, user)
}
func main() {
// 使用HandleFunc包装器推荐
http.HandleFunc("/users", commonhttp.HandleFunc(func(h *commonhttp.Handler) {
switch h.Request().Method {
http.HandleFunc("/users", func(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case http.MethodGet:
GetUserList(h)
GetUserList(w, r)
case http.MethodPost:
CreateUser(h)
CreateUser(w, r)
default:
h.WriteJSON(http.StatusMethodNotAllowed, 405, "方法不支持", nil)
commonhttp.WriteJSON(w, http.StatusMethodNotAllowed, 405, "方法不支持", nil)
}
}))
})
http.HandleFunc("/user", commonhttp.HandleFunc(GetUser))
http.HandleFunc("/user", GetUser)
log.Println("Server started on :8080")
log.Fatal(http.ListenAndServe(":8080", nil))
@@ -376,53 +442,93 @@ func main() {
## API 参考
### Handler结构
### Factory HTTP响应结构体暴露给外部项目使用
Handler封装了`ResponseWriter``Request`提供更简洁的API。
#### Response
```go
type Handler struct {
w http.ResponseWriter
r *http.Request
}
```
标准响应结构体,外部项目可以直接使用 `factory.Response`
### 创建Handler
#### NewHandler(w http.ResponseWriter, r *http.Request) *Handler
创建Handler实例。
#### HandleFunc(fn func(*Handler)) http.HandlerFunc
将Handler函数转换为标准的http.HandlerFunc便捷包装器
**字段:**
- `Code`: 业务状态码0表示成功
- `Message`: 响应消息
- `Timestamp`: 时间戳Unix时间戳
- `Data`: 响应数据
**示例:**
```go
http.HandleFunc("/users", commonhttp.HandleFunc(func(h *commonhttp.Handler) {
h.Success(data)
}))
response := factory.Response{
Code: 0,
Message: "success",
Data: userData,
}
```
### Handler响应方法
#### PageData
#### (h *Handler) Success(data interface{})
分页数据结构体,外部项目可以直接使用 `factory.PageData`
**字段:**
- `List`: 数据列表
- `Total`: 总记录数
- `Page`: 当前页码
- `PageSize`: 每页大小
**示例:**
```go
pageData := &factory.PageData{
List: users,
Total: 100,
Page: 1,
PageSize: 20,
}
fac.Success(w, pageData)
```
#### PageResponse
分页响应结构体,外部项目可以直接使用 `factory.PageResponse`
**字段:**
- `Code`: 业务状态码
- `Message`: 响应消息
- `Timestamp`: 时间戳
- `Data`: 分页数据(*PageData
### Factory HTTP响应方法推荐使用
#### (f *Factory) Success(w http.ResponseWriter, data interface{}, message ...string)
成功响应HTTP 200业务code 0。
#### (h *Handler) SuccessWithMessage(message string, data interface{})
**参数:**
- `data`: 响应数据可以为nil
- `message`: 响应消息(可选),如果为空则使用默认消息 "success"
带消息的成功响应。
**示例:**
```go
fac.Success(w, data) // 只有数据,使用默认消息 "success"
fac.Success(w, data, "操作成功") // 数据+消息
```
#### (h *Handler) Error(code int, message string)
#### (f *Factory) Error(w http.ResponseWriter, code int, message string)
业务错误响应HTTP 200业务code非0。
#### (h *Handler) SystemError(message string)
**示例:**
```go
fac.Error(w, 1001, "用户不存在")
```
#### (f *Factory) SystemError(w http.ResponseWriter, message string)
系统错误响应HTTP 500业务code 500。
#### (h *Handler) WriteJSON(httpCode, code int, message string, data interface{})
**示例:**
```go
fac.SystemError(w, "服务器内部错误")
```
#### (f *Factory) WriteJSON(w http.ResponseWriter, httpCode, code int, message string, data interface{})
写入JSON响应自定义
@@ -432,7 +538,17 @@ http.HandleFunc("/users", commonhttp.HandleFunc(func(h *commonhttp.Handler) {
- `message`: 响应消息
- `data`: 响应数据
#### (h *Handler) SuccessPage(list interface{}, total int64, page, pageSize int, message ...string)
**说明:**
- 此方法不在 Factory 中,直接使用 `commonhttp.WriteJSON()`
- 用于需要自定义HTTP状态码的场景如 400, 401, 403, 404 等)
**示例:**
```go
commonhttp.WriteJSON(w, http.StatusBadRequest, 400, "请求参数错误", nil)
commonhttp.WriteJSON(w, http.StatusUnauthorized, 401, "未登录", nil)
```
#### (f *Factory) SuccessPage(w http.ResponseWriter, list interface{}, total int64, page, pageSize int, message ...string)
分页成功响应。
@@ -443,53 +559,81 @@ http.HandleFunc("/users", commonhttp.HandleFunc(func(h *commonhttp.Handler) {
- `pageSize`: 每页大小
- `message`: 响应消息(可选,如果为空则使用默认消息 "success"
### Handler请求解析方法
**示例:**
```go
fac.SuccessPage(w, users, total, page, pageSize)
fac.SuccessPage(w, users, total, page, pageSize, "查询成功")
```
#### (h *Handler) ParseJSON(v interface{}) error
### HTTP公共方法直接使用
#### WriteJSON(w http.ResponseWriter, httpCode, code int, message string, data interface{})
写入JSON响应自定义HTTP状态码和业务状态码
**说明:**
- 此方法不在 Factory 中,直接使用 `commonhttp.WriteJSON()`
- 用于需要自定义HTTP状态码的场景如 400, 401, 403, 404 等)
**示例:**
```go
commonhttp.WriteJSON(w, http.StatusBadRequest, 400, "请求参数错误", nil)
commonhttp.WriteJSON(w, http.StatusUnauthorized, 401, "未登录", nil)
```
#### ParseJSON(r *http.Request, v interface{}) error
解析JSON请求体。
#### (h *Handler) GetQuery(key, defaultValue string) string
**示例:**
```go
var req CreateUserRequest
if err := commonhttp.ParseJSON(r, &req); err != nil {
// 处理错误
}
```
#### GetQuery(r *http.Request, key, defaultValue string) string
获取查询参数(字符串)。
#### (h *Handler) GetQueryInt(key string, defaultValue int) int
#### GetQueryInt(r *http.Request, key string, defaultValue int) int
获取查询参数(整数)。
#### (h *Handler) GetQueryInt64(key string, defaultValue int64) int64
#### GetQueryInt64(r *http.Request, key string, defaultValue int64) int64
获取查询参数int64
#### (h *Handler) GetQueryBool(key string, defaultValue bool) bool
#### GetQueryBool(r *http.Request, key string, defaultValue bool) bool
获取查询参数(布尔值)。
#### (h *Handler) GetQueryFloat64(key string, defaultValue float64) float64
#### GetQueryFloat64(r *http.Request, key string, defaultValue float64) float64
获取查询参数(浮点数)。
#### (h *Handler) GetFormValue(key, defaultValue string) string
#### GetFormValue(r *http.Request, key, defaultValue string) string
获取表单值(字符串)。
#### (h *Handler) GetFormInt(key string, defaultValue int) int
#### GetFormInt(r *http.Request, key string, defaultValue int) int
获取表单值(整数)。
#### (h *Handler) GetFormInt64(key string, defaultValue int64) int64
#### GetFormInt64(r *http.Request, key string, defaultValue int64) int64
获取表单值int64
#### (h *Handler) GetFormBool(key string, defaultValue bool) bool
#### GetFormBool(r *http.Request, key string, defaultValue bool) bool
获取表单值(布尔值)。
#### (h *Handler) GetHeader(key, defaultValue string) string
#### GetHeader(r *http.Request, key, defaultValue string) string
获取请求头。
#### (h *Handler) ParsePaginationRequest() *PaginationRequest
#### ParsePaginationRequest(r *http.Request) *PaginationRequest
从请求中解析分页参数。
@@ -498,7 +642,7 @@ http.HandleFunc("/users", commonhttp.HandleFunc(func(h *commonhttp.Handler) {
- 优先级:查询参数 > form表单
- 如果请求体是JSON格式且包含分页字段建议先使用`ParseJSON`解析完整请求体到包含`PaginationRequest`的结构体中
#### (h *Handler) GetTimezone() string
#### GetTimezone(r *http.Request) string
从请求的context中获取时区。
@@ -506,19 +650,39 @@ http.HandleFunc("/users", commonhttp.HandleFunc(func(h *commonhttp.Handler) {
- 如果使用了middleware.Timezone中间件可以从context中获取时区信息
- 如果未设置,返回默认时区 AsiaShanghai
### Handler访问原始对象
#### Success(w http.ResponseWriter, data interface{}, message ...string)
#### (h *Handler) ResponseWriter() http.ResponseWriter
成功响应(公共方法)。
获取原始的ResponseWriter需要时使用
**参数:**
- `data`: 响应数据可以为nil
- `message`: 响应消息(可选),如果为空则使用默认消息 "success"
#### (h *Handler) Request() *http.Request
**示例:**
```go
commonhttp.Success(w, data) // 只有数据
commonhttp.Success(w, data, "操作成功") // 数据+消息
```
获取原始的Request需要时使用
#### Error(w http.ResponseWriter, code int, message string)
#### (h *Handler) Context() context.Context
错误响应(公共方法)。
获取请求的Context。
#### SystemError(w http.ResponseWriter, message string)
系统错误响应(公共方法)。
#### WriteJSON(w http.ResponseWriter, httpCode, code int, message string, data interface{})
写入JSON响应公共方法不在Factory中
**说明:**
- 用于需要自定义HTTP状态码的场景
- 直接使用 `commonhttp.WriteJSON()`,不在 Factory 中
#### SuccessPage(w http.ResponseWriter, list interface{}, total int64, page, pageSize int, message ...string)
分页成功响应(公共方法)。
### 分页请求结构
@@ -575,10 +739,14 @@ http.HandleFunc("/users", commonhttp.HandleFunc(func(h *commonhttp.Handler) {
- 使用`SystemError`返回系统错误HTTP 500
- 其他HTTP错误状态码400, 401, 403, 404等使用`WriteJSON`方法直接指定
5. **黑盒模式**
- 所有功能都通过Handler对象调用无需传递`w``r`参数
- 代码更简洁,减少调用方工作量
5. **推荐使用Factory**
- 使用 `factory.Success()` 等方法,代码更简洁
- 直接使用 `http` 包的公共方法,保持低耦合
- 不需要Handler结构减少不必要的封装
## 示例
完整示例请参考 `examples/http_handler_example.go`
完整示例请参考
- `examples/http_handler_example.go` - 使用Factory和公共方法
- `examples/http_pagination_example.go` - 分页示例
- `examples/factory_blackbox_example.go` - Factory黑盒模式示例

View File

@@ -136,7 +136,7 @@ import (
"net/http"
"git.toowon.com/jimmy/go-common/middleware"
commonhttp "git.toowon.com/jimmy/go-common/http"
"git.toowon.com/jimmy/go-common/datetime"
"git.toowon.com/jimmy/go-common/tools"
)
func handler(w http.ResponseWriter, r *http.Request) {
@@ -146,12 +146,12 @@ func handler(w http.ResponseWriter, r *http.Request) {
timezone := h.GetTimezone()
// 使用时区
now := datetime.Now(timezone)
datetime.FormatDateTime(now, timezone)
now := tools.Now(timezone)
tools.FormatDateTime(now, timezone)
h.Success(map[string]interface{}{
"timezone": timezone,
"time": datetime.FormatDateTime(now),
"time": tools.FormatDateTime(now),
})
}
@@ -168,7 +168,7 @@ func main() {
import (
"net/http"
"git.toowon.com/jimmy/go-common/middleware"
"git.toowon.com/jimmy/go-common/datetime"
"git.toowon.com/jimmy/go-common/tools"
)
func handler(w http.ResponseWriter, r *http.Request) {
@@ -177,7 +177,7 @@ func handler(w http.ResponseWriter, r *http.Request) {
func main() {
// 使用自定义默认时区
handler := middleware.TimezoneWithDefault(datetime.UTC)(http.HandlerFunc(handler))
handler := middleware.TimezoneWithDefault(tools.UTC)(http.HandlerFunc(handler))
http.Handle("/api", handler)
http.ListenAndServe(":8080", nil)
}
@@ -185,11 +185,43 @@ func main() {
#### 在业务代码中使用时区
**推荐方式:通过 factory 使用(黑盒模式)**
```go
import (
"net/http"
"git.toowon.com/jimmy/go-common/factory"
)
func GetUserList(w http.ResponseWriter, r *http.Request) {
fac, _ := factory.NewFactoryFromFile("config.json")
// 从请求中获取时区
timezone := fac.GetTimezone(r)
// 使用时区进行时间处理
now := fac.Now(timezone)
// 查询数据时使用时区
startTime := fac.StartOfDay(now, timezone)
endTime := fac.EndOfDay(now, timezone)
// 返回数据
fac.Success(w, map[string]interface{}{
"timezone": timezone,
"startTime": fac.FormatDateTime(startTime),
"endTime": fac.FormatDateTime(endTime),
})
}
```
**或者直接使用 tools 包:**
```go
import (
"net/http"
commonhttp "git.toowon.com/jimmy/go-common/http"
"git.toowon.com/jimmy/go-common/datetime"
"git.toowon.com/jimmy/go-common/tools"
)
func GetUserList(w http.ResponseWriter, r *http.Request) {
@@ -199,17 +231,17 @@ func GetUserList(w http.ResponseWriter, r *http.Request) {
timezone := h.GetTimezone()
// 使用时区进行时间处理
now := datetime.Now(timezone)
now := tools.Now(timezone)
// 查询数据时使用时区
startTime := datetime.StartOfDay(now, timezone)
endTime := datetime.EndOfDay(now, timezone)
startTime := tools.StartOfDay(now, timezone)
endTime := tools.EndOfDay(now, timezone)
// 返回数据
h.Success(map[string]interface{}{
"timezone": timezone,
"startTime": datetime.FormatDateTime(startTime),
"endTime": datetime.FormatDateTime(endTime),
"startTime": tools.FormatDateTime(startTime),
"endTime": tools.FormatDateTime(endTime),
})
}
```
@@ -658,7 +690,7 @@ import (
"git.toowon.com/jimmy/go-common/middleware"
"git.toowon.com/jimmy/go-common/logger"
commonhttp "git.toowon.com/jimmy/go-common/http"
"git.toowon.com/jimmy/go-common/datetime"
"git.toowon.com/jimmy/go-common/tools"
)
func apiHandler(w http.ResponseWriter, r *http.Request) {
@@ -666,12 +698,12 @@ func apiHandler(w http.ResponseWriter, r *http.Request) {
// 从Handler获取时区
timezone := h.GetTimezone()
now := datetime.Now(timezone)
now := tools.Now(timezone)
h.Success(map[string]interface{}{
"message": "Hello",
"timezone": timezone,
"time": datetime.FormatDateTime(now),
"time": tools.FormatDateTime(now),
})
}
@@ -756,7 +788,7 @@ import (
"git.toowon.com/jimmy/go-common/middleware"
commonhttp "git.toowon.com/jimmy/go-common/http"
"git.toowon.com/jimmy/go-common/datetime"
"git.toowon.com/jimmy/go-common/tools"
)
func apiHandler(w http.ResponseWriter, r *http.Request) {
@@ -764,12 +796,12 @@ func apiHandler(w http.ResponseWriter, r *http.Request) {
// 从Handler获取时区
timezone := h.GetTimezone()
now := datetime.Now(timezone)
now := tools.Now(timezone)
h.Success(map[string]interface{}{
"message": "Hello",
"timezone": timezone,
"time": datetime.FormatDateTime(now),
"time": tools.FormatDateTime(now),
})
}