Compare commits
7 Commits
v0.5.1
...
f8f4df4073
| Author | SHA1 | Date | |
|---|---|---|---|
| f8f4df4073 | |||
| 684923f9cb | |||
| 545c6ef6a4 | |||
| 5cfa0d7ce5 | |||
| f62e8ecebf | |||
| 339920a940 | |||
| b66f345281 |
35
MIGRATION.md
35
MIGRATION.md
@@ -105,14 +105,10 @@ go build -o bin/migrate cmd/migrate/main.go
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
#### 方式2:环境变量(推荐生产环境)
|
#### 方式2:环境变量指定配置文件路径(推荐生产环境)
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
# 使用 DATABASE_URL(最简单)
|
# 使用环境变量指定配置文件路径
|
||||||
export DATABASE_URL="mysql://root:password@localhost:3306/mydb"
|
|
||||||
./bin/migrate up
|
|
||||||
|
|
||||||
# 覆盖配置路径
|
|
||||||
export CONFIG_FILE="/etc/app/config.json"
|
export CONFIG_FILE="/etc/app/config.json"
|
||||||
export MIGRATIONS_DIR="/opt/app/migrations"
|
export MIGRATIONS_DIR="/opt/app/migrations"
|
||||||
./bin/migrate up
|
./bin/migrate up
|
||||||
@@ -122,8 +118,7 @@ export MIGRATIONS_DIR="/opt/app/migrations"
|
|||||||
|
|
||||||
1. 命令行参数 `-config` 和 `-dir`(最高)
|
1. 命令行参数 `-config` 和 `-dir`(最高)
|
||||||
2. 环境变量 `CONFIG_FILE` 和 `MIGRATIONS_DIR`
|
2. 环境变量 `CONFIG_FILE` 和 `MIGRATIONS_DIR`
|
||||||
3. 环境变量 `DATABASE_URL`
|
3. 默认值 `config.json` 和 `migrations`
|
||||||
4. 默认值 `config.json` 和 `migrations`
|
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -185,20 +180,20 @@ services:
|
|||||||
docker-compose exec app ./migrate up
|
docker-compose exec app ./migrate up
|
||||||
```
|
```
|
||||||
|
|
||||||
### 方式3:使用环境变量
|
### 方式3:使用环境变量指定配置文件路径
|
||||||
|
|
||||||
无需配置文件(适用于简单场景):
|
适用于多环境部署,通过环境变量指定不同环境的配置文件:
|
||||||
|
|
||||||
```yaml
|
```yaml
|
||||||
services:
|
services:
|
||||||
app:
|
app:
|
||||||
build: .
|
build: .
|
||||||
environment:
|
environment:
|
||||||
DATABASE_URL: mysql://root:password@db:3306/mydb
|
CONFIG_FILE: /app/config.prod.json
|
||||||
|
MIGRATIONS_DIR: /app/migrations
|
||||||
|
volumes:
|
||||||
|
- ./config.prod.json:/app/config.prod.json:ro
|
||||||
command: sh -c "./migrate up && ./server"
|
command: sh -c "./migrate up && ./server"
|
||||||
|
|
||||||
# 注意:DATABASE_URL 的值应该指向你的数据库服务
|
|
||||||
# 例如:mysql://user:pass@your-db-host:3306/dbname
|
|
||||||
```
|
```
|
||||||
|
|
||||||
### Dockerfile
|
### Dockerfile
|
||||||
@@ -336,10 +331,12 @@ jobs:
|
|||||||
go build -o bin/migrate cmd/migrate/main.go
|
go build -o bin/migrate cmd/migrate/main.go
|
||||||
go build -o bin/server cmd/server/main.go
|
go build -o bin/server cmd/server/main.go
|
||||||
|
|
||||||
|
- name: Create Config File
|
||||||
|
run: |
|
||||||
|
echo '${{ secrets.CONFIG_JSON }}' > config.json
|
||||||
|
|
||||||
- name: Run Migrations
|
- name: Run Migrations
|
||||||
env:
|
run: ./bin/migrate up -config config.json
|
||||||
DATABASE_URL: ${{ secrets.DATABASE_URL }}
|
|
||||||
run: ./bin/migrate up
|
|
||||||
|
|
||||||
- name: Deploy
|
- name: Deploy
|
||||||
run: ./bin/server
|
run: ./bin/server
|
||||||
@@ -500,11 +497,11 @@ go build -o bin/migrate cmd/migrate/main.go
|
|||||||
### 3. 生产环境
|
### 3. 生产环境
|
||||||
|
|
||||||
- 编译后部署,先执行迁移再启动应用
|
- 编译后部署,先执行迁移再启动应用
|
||||||
- 使用环境变量管理敏感信息
|
- 使用配置文件管理敏感信息
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
go build -o bin/migrate cmd/migrate/main.go
|
go build -o bin/migrate cmd/migrate/main.go
|
||||||
DATABASE_URL="mysql://..." ./bin/migrate up
|
./bin/migrate up -config config.json
|
||||||
./bin/server
|
./bin/server
|
||||||
```
|
```
|
||||||
|
|
||||||
|
|||||||
22
README.md
22
README.md
@@ -295,12 +295,24 @@ http.HandleFunc("/user", commonhttp.HandleFunc(GetUser))
|
|||||||
```
|
```
|
||||||
|
|
||||||
### 日期时间
|
### 日期时间
|
||||||
```go
|
**推荐方式:通过 factory 使用(黑盒模式)**
|
||||||
import "git.toowon.com/jimmy/go-common/datetime"
|
|
||||||
|
|
||||||
datetime.SetDefaultTimeZone(datetime.AsiaShanghai)
|
```go
|
||||||
now := datetime.Now()
|
import "git.toowon.com/jimmy/go-common/factory"
|
||||||
str := datetime.FormatDateTime(now)
|
|
||||||
|
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)
|
||||||
```
|
```
|
||||||
|
|
||||||
更多示例:[examples目录](./examples/)
|
更多示例:[examples目录](./examples/)
|
||||||
|
|||||||
@@ -13,6 +13,7 @@
|
|||||||
- [短信工具](./sms.md) - 阿里云短信发送
|
- [短信工具](./sms.md) - 阿里云短信发送
|
||||||
- [工厂工具](./factory.md) - 从配置直接创建已初始化客户端对象
|
- [工厂工具](./factory.md) - 从配置直接创建已初始化客户端对象
|
||||||
- [日志工具](./logger.md) - 统一的日志记录功能
|
- [日志工具](./logger.md) - 统一的日志记录功能
|
||||||
|
- [国际化工具](./i18n.md) - 多语言内容管理和国际化支持
|
||||||
|
|
||||||
## 快速开始
|
## 快速开始
|
||||||
|
|
||||||
@@ -57,28 +58,46 @@ CREATE TABLE users (id BIGINT PRIMARY KEY AUTO_INCREMENT, ...);
|
|||||||
|
|
||||||
#### 日期转换
|
#### 日期转换
|
||||||
|
|
||||||
```go
|
**推荐方式:通过 factory 使用(黑盒模式)**
|
||||||
import "git.toowon.com/jimmy/go-common/datetime"
|
|
||||||
|
|
||||||
datetime.SetDefaultTimeZone(datetime.AsiaShanghai)
|
```go
|
||||||
now := datetime.Now()
|
import "git.toowon.com/jimmy/go-common/factory"
|
||||||
str := datetime.FormatDateTime(now)
|
|
||||||
|
fac, _ := factory.NewFactoryFromFile("config.json")
|
||||||
|
now := fac.Now("Asia/Shanghai")
|
||||||
|
str := fac.FormatDateTime(now)
|
||||||
```
|
```
|
||||||
|
|
||||||
#### HTTP响应(Handler黑盒模式)
|
**或者直接使用 tools 包:**
|
||||||
|
|
||||||
|
```go
|
||||||
|
import "git.toowon.com/jimmy/go-common/tools"
|
||||||
|
|
||||||
|
tools.SetDefaultTimeZone(tools.AsiaShanghai)
|
||||||
|
now := tools.Now()
|
||||||
|
str := tools.FormatDateTime(now)
|
||||||
|
```
|
||||||
|
|
||||||
|
#### HTTP响应(Factory黑盒模式,推荐)
|
||||||
|
|
||||||
```go
|
```go
|
||||||
import (
|
import (
|
||||||
"net/http"
|
"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) {
|
func GetUser(w http.ResponseWriter, r *http.Request) {
|
||||||
id := h.GetQueryInt64("id", 0)
|
fac, _ := factory.NewFactoryFromFile("config.json")
|
||||||
h.Success(data)
|
|
||||||
|
// 获取查询参数(使用类型转换方法)
|
||||||
|
id := tools.ConvertInt64(r.URL.Query().Get("id"), 0)
|
||||||
|
|
||||||
|
// 返回成功响应
|
||||||
|
fac.Success(w, data)
|
||||||
}
|
}
|
||||||
|
|
||||||
http.HandleFunc("/user", commonhttp.HandleFunc(GetUser))
|
http.HandleFunc("/user", GetUser)
|
||||||
```
|
```
|
||||||
|
|
||||||
#### 中间件(生产级配置)
|
#### 中间件(生产级配置)
|
||||||
|
|||||||
439
docs/datetime.md
439
docs/datetime.md
@@ -4,6 +4,8 @@
|
|||||||
|
|
||||||
日期转换工具提供了丰富的日期时间处理功能,支持时区设定、格式转换、时间计算等常用操作。
|
日期转换工具提供了丰富的日期时间处理功能,支持时区设定、格式转换、时间计算等常用操作。
|
||||||
|
|
||||||
|
**重要说明**:日期时间功能位于 `tools` 包中,推荐通过 `factory` 包使用(黑盒模式),也可以直接使用 `tools` 包。
|
||||||
|
|
||||||
## 功能特性
|
## 功能特性
|
||||||
|
|
||||||
- 支持时区设定和转换
|
- 支持时区设定和转换
|
||||||
@@ -16,13 +18,34 @@
|
|||||||
|
|
||||||
## 使用方法
|
## 使用方法
|
||||||
|
|
||||||
### 1. 设置默认时区
|
### 方式1:通过 factory 使用(推荐,黑盒模式)
|
||||||
|
|
||||||
```go
|
```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 {
|
if err != nil {
|
||||||
log.Fatal(err)
|
log.Fatal(err)
|
||||||
}
|
}
|
||||||
@@ -30,166 +53,284 @@ if err != nil {
|
|||||||
|
|
||||||
### 2. 获取当前时间
|
### 2. 获取当前时间
|
||||||
|
|
||||||
|
**通过 factory:**
|
||||||
```go
|
```go
|
||||||
// 使用默认时区
|
// 使用默认时区
|
||||||
now := datetime.Now()
|
now := fac.Now()
|
||||||
|
|
||||||
// 使用指定时区
|
// 使用指定时区
|
||||||
now := datetime.Now(datetime.AsiaShanghai)
|
now := fac.Now("Asia/Shanghai")
|
||||||
now := datetime.Now("America/New_York")
|
now := fac.Now("America/New_York")
|
||||||
|
```
|
||||||
|
|
||||||
|
**直接使用 tools:**
|
||||||
|
```go
|
||||||
|
// 使用默认时区
|
||||||
|
now := tools.Now()
|
||||||
|
|
||||||
|
// 使用指定时区
|
||||||
|
now := tools.Now(tools.AsiaShanghai)
|
||||||
|
now := tools.Now("America/New_York")
|
||||||
```
|
```
|
||||||
|
|
||||||
### 3. 解析时间字符串
|
### 3. 解析时间字符串
|
||||||
|
|
||||||
|
**通过 factory:**
|
||||||
```go
|
```go
|
||||||
// 使用默认时区解析
|
// 使用默认时区解析
|
||||||
t, err := datetime.Parse("2006-01-02 15:04:05", "2024-01-01 12:00:00")
|
t, err := fac.ParseDateTime("2024-01-01 12:00:00")
|
||||||
if err != nil {
|
|
||||||
log.Fatal(err)
|
|
||||||
}
|
|
||||||
|
|
||||||
// 使用指定时区解析
|
// 使用指定时区解析
|
||||||
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 := tools.ParseDateTime("2024-01-01 12:00:00")
|
||||||
t, err := datetime.ParseDate("2024-01-01")
|
t, err := tools.ParseDate("2024-01-01")
|
||||||
```
|
```
|
||||||
|
|
||||||
### 4. 格式化时间
|
### 4. 格式化时间
|
||||||
|
|
||||||
|
**通过 factory:**
|
||||||
```go
|
```go
|
||||||
t := time.Now()
|
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 := tools.FormatDateTime(t) // "2006-01-02 15:04:05"
|
||||||
str := datetime.FormatDate(t) // "2006-01-02"
|
str := tools.FormatDate(t) // "2006-01-02"
|
||||||
str := datetime.FormatTime(t) // "15:04:05"
|
str := tools.FormatTime(t) // "15:04:05"
|
||||||
```
|
```
|
||||||
|
|
||||||
### 5. 时区转换
|
### 5. 时区转换
|
||||||
|
|
||||||
|
**通过 factory:**
|
||||||
```go
|
```go
|
||||||
t := time.Now()
|
t := time.Now()
|
||||||
|
t2, err := tools.ToTimezone(t, "Asia/Shanghai")
|
||||||
|
```
|
||||||
|
|
||||||
// 转换到指定时区
|
**直接使用 tools:**
|
||||||
t2, err := datetime.ToTimezone(t, datetime.AsiaShanghai)
|
```go
|
||||||
if err != nil {
|
t := time.Now()
|
||||||
log.Fatal(err)
|
t2, err := tools.ToTimezone(t, tools.AsiaShanghai)
|
||||||
}
|
|
||||||
```
|
```
|
||||||
|
|
||||||
### 6. Unix时间戳转换
|
### 6. Unix时间戳转换
|
||||||
|
|
||||||
|
**通过 factory:**
|
||||||
```go
|
```go
|
||||||
t := time.Now()
|
t := time.Now()
|
||||||
|
|
||||||
// 转换为Unix时间戳(秒)
|
// 转换为Unix时间戳(秒)
|
||||||
unix := datetime.ToUnix(t)
|
unix := fac.ToUnix(t)
|
||||||
|
|
||||||
// 从Unix时间戳创建时间
|
// 从Unix时间戳创建时间
|
||||||
t2 := datetime.FromUnix(unix)
|
t2 := fac.FromUnix(unix)
|
||||||
|
|
||||||
// 转换为Unix毫秒时间戳
|
// 转换为Unix毫秒时间戳
|
||||||
unixMilli := datetime.ToUnixMilli(t)
|
unixMilli := fac.ToUnixMilli(t)
|
||||||
|
|
||||||
// 从Unix毫秒时间戳创建时间
|
// 从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. 时间计算
|
### 7. 时间计算
|
||||||
|
|
||||||
|
**通过 factory:**
|
||||||
```go
|
```go
|
||||||
t := time.Now()
|
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. 时间范围获取
|
### 8. 时间范围获取
|
||||||
|
|
||||||
|
**通过 factory:**
|
||||||
```go
|
```go
|
||||||
t := time.Now()
|
t := time.Now()
|
||||||
|
|
||||||
// 获取一天的开始时间(00:00:00)
|
// 获取一天的开始时间(00:00:00)
|
||||||
start := datetime.StartOfDay(t)
|
start := fac.StartOfDay(t)
|
||||||
|
|
||||||
// 获取一天的结束时间(23:59:59.999999999)
|
// 获取一天的结束时间(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. 时间差计算
|
### 9. 时间差计算
|
||||||
|
|
||||||
|
**通过 factory:**
|
||||||
```go
|
```go
|
||||||
t1 := time.Now()
|
t1 := time.Now()
|
||||||
t2 := time.Now().Add(24 * time.Hour)
|
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时间(用于数据库存储)
|
### 10. 转换为UTC时间(用于数据库存储)
|
||||||
|
|
||||||
|
**直接使用 tools(factory 暂未提供):**
|
||||||
```go
|
```go
|
||||||
// 将任意时区的时间转换为UTC
|
// 将任意时区的时间转换为UTC
|
||||||
t := time.Now() // 当前时区的时间
|
t := time.Now() // 当前时区的时间
|
||||||
utcTime := datetime.ToUTC(t)
|
utcTime := tools.ToUTC(t)
|
||||||
|
|
||||||
// 从指定时区转换为UTC
|
// 从指定时区转换为UTC
|
||||||
t, _ := datetime.ParseDateTime("2024-01-01 12:00:00", datetime.AsiaShanghai)
|
t, _ := tools.ParseDateTime("2024-01-01 12:00:00", tools.AsiaShanghai)
|
||||||
utcTime, err := datetime.ToUTCFromTimezone(t, datetime.AsiaShanghai)
|
utcTime, err := tools.ToUTCFromTimezone(t, tools.AsiaShanghai)
|
||||||
|
|
||||||
// 解析时间字符串并直接转换为UTC
|
// 解析时间字符串并直接转换为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)
|
// 解析日期并转换为UTC(当天的00:00:00 UTC)
|
||||||
utcTime, err := datetime.ParseDateToUTC("2024-01-01", datetime.AsiaShanghai)
|
utcTime, err := tools.ParseDateToUTC("2024-01-01", tools.AsiaShanghai)
|
||||||
```
|
```
|
||||||
|
|
||||||
## API 参考
|
## API 参考
|
||||||
|
|
||||||
### 时区常量
|
### 时区常量
|
||||||
|
|
||||||
|
**通过 tools 包使用:**
|
||||||
|
|
||||||
```go
|
```go
|
||||||
|
import "git.toowon.com/jimmy/go-common/tools"
|
||||||
|
|
||||||
const (
|
const (
|
||||||
UTC = "UTC"
|
tools.UTC = "UTC"
|
||||||
AsiaShanghai = "Asia/Shanghai"
|
tools.AsiaShanghai = "Asia/Shanghai"
|
||||||
AmericaNewYork = "America/New_York"
|
tools.AmericaNewYork = "America/New_York"
|
||||||
EuropeLondon = "Europe/London"
|
tools.EuropeLondon = "Europe/London"
|
||||||
AsiaTokyo = "Asia/Tokyo"
|
tools.AsiaTokyo = "Asia/Tokyo"
|
||||||
)
|
)
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -208,15 +349,22 @@ CommonLayouts.RFC3339Nano = time.RFC3339Nano
|
|||||||
|
|
||||||
### 主要函数
|
### 主要函数
|
||||||
|
|
||||||
|
**注意**:以下函数可以通过 `factory` 或 `tools` 包调用。推荐使用 `factory` 的黑盒模式。
|
||||||
|
|
||||||
#### SetDefaultTimeZone(timezone string) error
|
#### SetDefaultTimeZone(timezone string) error
|
||||||
|
|
||||||
设置默认时区。
|
设置默认时区(仅 tools 包提供)。
|
||||||
|
|
||||||
**参数:**
|
**参数:**
|
||||||
- `timezone`: 时区字符串,如 "Asia/Shanghai"
|
- `timezone`: 时区字符串,如 "Asia/Shanghai"
|
||||||
|
|
||||||
**返回:** 错误信息
|
**返回:** 错误信息
|
||||||
|
|
||||||
|
**使用方式:**
|
||||||
|
```go
|
||||||
|
tools.SetDefaultTimeZone(tools.AsiaShanghai)
|
||||||
|
```
|
||||||
|
|
||||||
#### Now(timezone ...string) time.Time
|
#### 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`: 时间字符串
|
- `value`: 时间字符串
|
||||||
- `timezone`: 可选,时区字符串
|
- `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`: 时间对象
|
- `t`: 时间对象
|
||||||
- `layout`: 时间格式
|
|
||||||
- `timezone`: 可选,时区字符串
|
- `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)
|
||||||
|
```
|
||||||
|
|
||||||
**参数:**
|
更多函数请参考 `factory` 包或 `tools` 包的 API 文档。
|
||||||
- `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
|
|
||||||
|
|
||||||
计算两个时间之间的秒数差。
|
|
||||||
|
|
||||||
### UTC转换函数
|
### UTC转换函数
|
||||||
|
|
||||||
@@ -391,7 +488,7 @@ CommonLayouts.RFC3339Nano = time.RFC3339Nano
|
|||||||
|
|
||||||
## 完整示例
|
## 完整示例
|
||||||
|
|
||||||
### 示例1:基本使用
|
### 示例1:通过 factory 使用(推荐)
|
||||||
|
|
||||||
```go
|
```go
|
||||||
package main
|
package main
|
||||||
@@ -399,27 +496,67 @@ package main
|
|||||||
import (
|
import (
|
||||||
"fmt"
|
"fmt"
|
||||||
"log"
|
"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() {
|
func main() {
|
||||||
// 设置默认时区
|
// 设置默认时区
|
||||||
datetime.SetDefaultTimeZone(datetime.AsiaShanghai)
|
err := tools.SetDefaultTimeZone(tools.AsiaShanghai)
|
||||||
|
if err != nil {
|
||||||
|
log.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
// 获取当前时间
|
// 获取当前时间
|
||||||
now := datetime.Now()
|
now := tools.Now()
|
||||||
fmt.Printf("Current time: %s\n", datetime.FormatDateTime(now))
|
fmt.Printf("Current time: %s\n", tools.FormatDateTime(now))
|
||||||
|
|
||||||
// 时区转换
|
// 时区转换
|
||||||
t, _ := datetime.ParseDateTime("2024-01-01 12:00:00")
|
t, _ := tools.ParseDateTime("2024-01-01 12:00:00")
|
||||||
t2, _ := datetime.ToTimezone(t, datetime.AmericaNewYork)
|
t2, _ := tools.ToTimezone(t, tools.AmericaNewYork)
|
||||||
fmt.Printf("Time in New York: %s\n", datetime.FormatDateTime(t2))
|
fmt.Printf("Time in New York: %s\n", tools.FormatDateTime(t2))
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
### 示例2:UTC转换(数据库存储场景)
|
### 示例3:UTC转换(数据库存储场景)
|
||||||
|
|
||||||
```go
|
```go
|
||||||
package main
|
package main
|
||||||
@@ -428,34 +565,32 @@ import (
|
|||||||
"fmt"
|
"fmt"
|
||||||
"log"
|
"log"
|
||||||
|
|
||||||
"git.toowon.com/jimmy/go-common/datetime"
|
"git.toowon.com/jimmy/go-common/tools"
|
||||||
)
|
)
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
// 从请求中获取时间(假设是上海时区)
|
// 从请求中获取时间(假设是上海时区)
|
||||||
requestTimeStr := "2024-01-01 12:00:00"
|
requestTimeStr := "2024-01-01 12:00:00"
|
||||||
requestTimezone := datetime.AsiaShanghai
|
requestTimezone := tools.AsiaShanghai
|
||||||
|
|
||||||
// 转换为UTC时间(用于数据库存储)
|
// 转换为UTC时间(用于数据库存储)
|
||||||
dbTime, err := datetime.ParseDateTimeToUTC(requestTimeStr, requestTimezone)
|
dbTime, err := tools.ParseDateTimeToUTC(requestTimeStr, requestTimezone)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatal(err)
|
log.Fatal(err)
|
||||||
}
|
}
|
||||||
|
|
||||||
fmt.Printf("Request time (Shanghai): %s\n", requestTimeStr)
|
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时间,转换为用户时区显示
|
// 从数据库读取UTC时间,转换为用户时区显示
|
||||||
userTimezone := datetime.AsiaShanghai
|
userTimezone := tools.AsiaShanghai
|
||||||
displayTime, err := datetime.ToTimezone(dbTime, userTimezone)
|
displayTime, err := tools.ToTimezone(dbTime, userTimezone)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatal(err)
|
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))
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
完整示例请参考:
|
完整示例请参考 `factory` 包中的 datetime 相关方法,通过 `factory` 调用 `tools` 包中的 datetime 功能。
|
||||||
- `examples/datetime_example.go` - 基本使用示例
|
|
||||||
- `examples/datetime_utc_example.go` - UTC转换示例
|
|
||||||
|
|
||||||
|
|||||||
650
docs/factory.md
650
docs/factory.md
@@ -26,6 +26,13 @@
|
|||||||
| **邮件** | `SendEmail()` | `fac.SendEmail(to, subject, body)` |
|
| **邮件** | `SendEmail()` | `fac.SendEmail(to, subject, body)` |
|
||||||
| **短信** | `SendSMS()` | `fac.SendSMS(phones, params)` |
|
| **短信** | `SendSMS()` | `fac.SendSMS(phones, params)` |
|
||||||
| **存储** | `UploadFile()`, `GetFileURL()` | `fac.UploadFile(ctx, key, file)` |
|
| **存储** | `UploadFile()`, `GetFileURL()` | `fac.UploadFile(ctx, key, file)` |
|
||||||
|
| **日期时间** | `Now()`, `ParseDateTime()`, `FormatDateTime()` 等 | `fac.Now("Asia/Shanghai")` |
|
||||||
|
| **时间工具** | `GetTimestamp()`, `IsToday()`, `GetBeginOfWeek()` 等 | `fac.GetTimestamp()` |
|
||||||
|
| **加密工具** | `HashPassword()`, `MD5()`, `SHA256()`, `GenerateSMSCode()` 等 | `fac.HashPassword("password")` |
|
||||||
|
| **金额计算** | `YuanToCents()`, `CentsToYuan()`, `FormatYuan()` | `fac.YuanToCents(100.5)` |
|
||||||
|
| **版本信息** | `GetVersion()` | `fac.GetVersion()` |
|
||||||
|
| **HTTP响应** | `Success()`, `Error()`, `SuccessPage()` | `fac.Success(w, data)` |
|
||||||
|
| **HTTP请求** | `ParseJSON()`, `ConvertInt()`, `GetTimezone()` 等 | `fac.ParseJSON(r, &req)` |
|
||||||
|
|
||||||
### 🔧 高级功能:Get方法(仅在必要时使用)
|
### 🔧 高级功能:Get方法(仅在必要时使用)
|
||||||
|
|
||||||
@@ -176,7 +183,124 @@ db.Find(&users)
|
|||||||
db.Create(&user)
|
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
|
||||||
|
// 时间戳
|
||||||
|
timestamp := fac.GetTimestamp() // 当前时间戳(秒)
|
||||||
|
millisTimestamp := fac.GetMillisTimestamp() // 当前时间戳(毫秒)
|
||||||
|
utcTimestamp := fac.GetUTCTimestamp() // UTC时间戳
|
||||||
|
|
||||||
|
// 自定义格式格式化
|
||||||
|
str := fac.FormatTimeWithLayout(now, "2006年01月02日 15:04:05")
|
||||||
|
|
||||||
|
// 自定义格式解析
|
||||||
|
t, _ := fac.ParseTime("2024-01-01 12:00:00", "2006-01-02 15:04:05")
|
||||||
|
|
||||||
|
// 时间计算(补充)
|
||||||
|
nextHour := fac.AddHours(now, 1)
|
||||||
|
nextMinute := fac.AddMinutes(now, 30)
|
||||||
|
|
||||||
|
// 周相关
|
||||||
|
beginOfWeek := fac.GetBeginOfWeek(now)
|
||||||
|
endOfWeek := fac.GetEndOfWeek(now)
|
||||||
|
|
||||||
|
// 时间判断
|
||||||
|
if fac.IsToday(t) {
|
||||||
|
fmt.Println("是今天")
|
||||||
|
}
|
||||||
|
if fac.IsYesterday(t) {
|
||||||
|
fmt.Println("是昨天")
|
||||||
|
}
|
||||||
|
|
||||||
|
// 生成详细时间信息
|
||||||
|
timeInfo := fac.GenerateTimeInfoWithTimezone(now, "Asia/Shanghai")
|
||||||
|
fmt.Printf("UTC: %s, Local: %s, Unix: %d\n", timeInfo.UTC, timeInfo.Local, timeInfo.Unix)
|
||||||
|
```
|
||||||
|
|
||||||
|
### 10. 金额计算(黑盒模式)
|
||||||
|
|
||||||
|
```go
|
||||||
|
// 元转分
|
||||||
|
cents := fac.YuanToCents(100.5) // 10050
|
||||||
|
|
||||||
|
// 分转元
|
||||||
|
yuan := fac.CentsToYuan(10050) // 100.5
|
||||||
|
|
||||||
|
// 格式化显示
|
||||||
|
str := fac.FormatYuan(10050) // "100.50"
|
||||||
|
```
|
||||||
|
|
||||||
|
### 12. 版本信息(黑盒模式)
|
||||||
|
|
||||||
|
```go
|
||||||
|
version := fac.GetVersion()
|
||||||
|
fmt.Println("当前版本:", version)
|
||||||
|
```
|
||||||
|
|
||||||
|
### 13. 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, "系统错误")
|
||||||
|
```
|
||||||
|
|
||||||
|
### 14. HTTP请求解析(黑盒模式)
|
||||||
|
|
||||||
|
```go
|
||||||
|
import "net/http"
|
||||||
|
|
||||||
|
// 解析JSON
|
||||||
|
var req UserRequest
|
||||||
|
fac.ParseJSON(r, &req)
|
||||||
|
|
||||||
|
// 获取查询参数(使用类型转换方法)
|
||||||
|
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)
|
||||||
|
```
|
||||||
|
|
||||||
|
### 15. Redis操作(获取客户端对象)
|
||||||
|
|
||||||
```go
|
```go
|
||||||
import (
|
import (
|
||||||
@@ -481,6 +605,530 @@ 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`: 目标结构体指针
|
||||||
|
|
||||||
|
#### 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
|
||||||
|
|
||||||
|
获取当前时间。
|
||||||
|
|
||||||
|
**参数:**
|
||||||
|
- `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
|
||||||
|
|
||||||
|
计算两个时间之间的秒数差。
|
||||||
|
|
||||||
|
### 加密工具方法(黑盒模式)
|
||||||
|
|
||||||
|
#### 密码加密
|
||||||
|
|
||||||
|
##### HashPassword(password string) (string, error)
|
||||||
|
|
||||||
|
使用bcrypt加密密码。
|
||||||
|
|
||||||
|
**参数:**
|
||||||
|
- `password`: 原始密码
|
||||||
|
|
||||||
|
**返回:** 加密后的密码哈希值和错误信息
|
||||||
|
|
||||||
|
**示例:**
|
||||||
|
```go
|
||||||
|
hashedPassword, err := fac.HashPassword("myPassword")
|
||||||
|
```
|
||||||
|
|
||||||
|
##### CheckPassword(password, hash string) bool
|
||||||
|
|
||||||
|
验证密码。
|
||||||
|
|
||||||
|
**参数:**
|
||||||
|
- `password`: 原始密码
|
||||||
|
- `hash`: 加密后的密码哈希值
|
||||||
|
|
||||||
|
**返回:** 密码是否正确
|
||||||
|
|
||||||
|
**示例:**
|
||||||
|
```go
|
||||||
|
isValid := fac.CheckPassword("myPassword", hashedPassword)
|
||||||
|
```
|
||||||
|
|
||||||
|
#### 哈希计算
|
||||||
|
|
||||||
|
##### MD5(text string) string
|
||||||
|
|
||||||
|
计算MD5哈希值。
|
||||||
|
|
||||||
|
**参数:**
|
||||||
|
- `text`: 要计算哈希的文本
|
||||||
|
|
||||||
|
**返回:** MD5哈希值(十六进制字符串)
|
||||||
|
|
||||||
|
**示例:**
|
||||||
|
```go
|
||||||
|
hash := fac.MD5("text")
|
||||||
|
```
|
||||||
|
|
||||||
|
##### SHA256(text string) string
|
||||||
|
|
||||||
|
计算SHA256哈希值。
|
||||||
|
|
||||||
|
**参数:**
|
||||||
|
- `text`: 要计算哈希的文本
|
||||||
|
|
||||||
|
**返回:** SHA256哈希值(十六进制字符串)
|
||||||
|
|
||||||
|
**示例:**
|
||||||
|
```go
|
||||||
|
hash := fac.SHA256("text")
|
||||||
|
```
|
||||||
|
|
||||||
|
#### 随机字符串生成
|
||||||
|
|
||||||
|
##### GenerateRandomString(length int) string
|
||||||
|
|
||||||
|
生成指定长度的随机字符串。
|
||||||
|
|
||||||
|
**参数:**
|
||||||
|
- `length`: 字符串长度
|
||||||
|
|
||||||
|
**返回:** 随机字符串(包含大小写字母和数字)
|
||||||
|
|
||||||
|
**示例:**
|
||||||
|
```go
|
||||||
|
randomStr := fac.GenerateRandomString(16)
|
||||||
|
```
|
||||||
|
|
||||||
|
##### GenerateRandomNumber(length int) string
|
||||||
|
|
||||||
|
生成指定长度的随机数字字符串。
|
||||||
|
|
||||||
|
**参数:**
|
||||||
|
- `length`: 字符串长度
|
||||||
|
|
||||||
|
**返回:** 随机数字字符串
|
||||||
|
|
||||||
|
**示例:**
|
||||||
|
```go
|
||||||
|
randomNum := fac.GenerateRandomNumber(6)
|
||||||
|
```
|
||||||
|
|
||||||
|
#### 业务相关随机码生成
|
||||||
|
|
||||||
|
##### GenerateSMSCode() string
|
||||||
|
|
||||||
|
生成短信验证码。
|
||||||
|
|
||||||
|
**返回:** 6位数字验证码
|
||||||
|
|
||||||
|
**示例:**
|
||||||
|
```go
|
||||||
|
code := fac.GenerateSMSCode()
|
||||||
|
```
|
||||||
|
|
||||||
|
##### GenerateOrderNo(prefix string) string
|
||||||
|
|
||||||
|
生成订单号。
|
||||||
|
|
||||||
|
**参数:**
|
||||||
|
- `prefix`: 订单号前缀
|
||||||
|
|
||||||
|
**返回:** 订单号(格式:前缀+时间戳+6位随机数)
|
||||||
|
|
||||||
|
**示例:**
|
||||||
|
```go
|
||||||
|
orderNo := fac.GenerateOrderNo("ORD")
|
||||||
|
```
|
||||||
|
|
||||||
|
##### GeneratePaymentNo() string
|
||||||
|
|
||||||
|
生成支付单号。
|
||||||
|
|
||||||
|
**返回:** 支付单号(格式:PAY+时间戳+6位随机数)
|
||||||
|
|
||||||
|
**示例:**
|
||||||
|
```go
|
||||||
|
paymentNo := fac.GeneratePaymentNo()
|
||||||
|
```
|
||||||
|
|
||||||
|
##### GenerateRefundNo() string
|
||||||
|
|
||||||
|
生成退款单号。
|
||||||
|
|
||||||
|
**返回:** 退款单号(格式:RF+时间戳+6位随机数)
|
||||||
|
|
||||||
|
**示例:**
|
||||||
|
```go
|
||||||
|
refundNo := fac.GenerateRefundNo()
|
||||||
|
```
|
||||||
|
|
||||||
|
##### GenerateTransferNo() string
|
||||||
|
|
||||||
|
生成调拨单号。
|
||||||
|
|
||||||
|
**返回:** 调拨单号(格式:TF+时间戳+6位随机数)
|
||||||
|
|
||||||
|
**示例:**
|
||||||
|
```go
|
||||||
|
transferNo := fac.GenerateTransferNo()
|
||||||
|
```
|
||||||
|
|
||||||
|
### 时间工具方法(黑盒模式)
|
||||||
|
|
||||||
|
**说明**:Time 工具提供基础时间操作、时间戳、时间判断等功能,与 DateTime 工具的区别:
|
||||||
|
- **DateTime**:专注于时区相关、格式化、解析、UTC转换
|
||||||
|
- **Time**:专注于基础时间操作、时间戳、时间判断、时间信息生成
|
||||||
|
|
||||||
|
#### 时间戳方法
|
||||||
|
|
||||||
|
##### GetTimestamp() int64
|
||||||
|
|
||||||
|
获取当前时间戳(秒)。
|
||||||
|
|
||||||
|
##### GetMillisTimestamp() int64
|
||||||
|
|
||||||
|
获取当前时间戳(毫秒)。
|
||||||
|
|
||||||
|
##### GetUTCTimestamp() int64
|
||||||
|
|
||||||
|
获取UTC时间戳(秒)。
|
||||||
|
|
||||||
|
##### GetUTCTimestampFromTime(t time.Time) int64
|
||||||
|
|
||||||
|
从指定时间获取UTC时间戳(秒)。
|
||||||
|
|
||||||
|
#### 格式化方法(自定义格式)
|
||||||
|
|
||||||
|
##### FormatTimeWithLayout(t time.Time, layout string) string
|
||||||
|
|
||||||
|
格式化时间(自定义格式)。
|
||||||
|
|
||||||
|
**参数:**
|
||||||
|
- `t`: 时间对象
|
||||||
|
- `layout`: 时间格式,如 "2006-01-02 15:04:05",如果为空则使用默认格式
|
||||||
|
|
||||||
|
##### FormatTimeUTC(t time.Time) string
|
||||||
|
|
||||||
|
格式化时间为UTC字符串(ISO 8601格式)。
|
||||||
|
|
||||||
|
##### GetCurrentTime() string
|
||||||
|
|
||||||
|
获取当前时间字符串(使用默认格式 "2006-01-02 15:04:05")。
|
||||||
|
|
||||||
|
#### 解析方法(自定义格式)
|
||||||
|
|
||||||
|
##### ParseTime(timeStr, layout string) (time.Time, error)
|
||||||
|
|
||||||
|
解析时间字符串(自定义格式)。
|
||||||
|
|
||||||
|
**参数:**
|
||||||
|
- `timeStr`: 时间字符串
|
||||||
|
- `layout`: 时间格式,如 "2006-01-02 15:04:05",如果为空则使用默认格式
|
||||||
|
|
||||||
|
#### 时间计算(补充 DateTime 的 Add 系列)
|
||||||
|
|
||||||
|
##### AddHours(t time.Time, hours int) time.Time
|
||||||
|
|
||||||
|
增加小时数。
|
||||||
|
|
||||||
|
##### AddMinutes(t time.Time, minutes int) time.Time
|
||||||
|
|
||||||
|
增加分钟数。
|
||||||
|
|
||||||
|
#### 时间范围(周相关)
|
||||||
|
|
||||||
|
##### GetBeginOfWeek(t time.Time) time.Time
|
||||||
|
|
||||||
|
获取某周的开始时间(周一)。
|
||||||
|
|
||||||
|
##### GetEndOfWeek(t time.Time) time.Time
|
||||||
|
|
||||||
|
获取某周的结束时间(周日)。
|
||||||
|
|
||||||
|
#### 时间判断
|
||||||
|
|
||||||
|
##### IsToday(t time.Time) bool
|
||||||
|
|
||||||
|
判断是否为今天。
|
||||||
|
|
||||||
|
##### IsYesterday(t time.Time) bool
|
||||||
|
|
||||||
|
判断是否为昨天。
|
||||||
|
|
||||||
|
##### IsTomorrow(t time.Time) bool
|
||||||
|
|
||||||
|
判断是否为明天。
|
||||||
|
|
||||||
|
#### 时间信息生成
|
||||||
|
|
||||||
|
##### GenerateTimeInfoWithTimezone(t time.Time, timezone string) TimeInfo
|
||||||
|
|
||||||
|
生成详细时间信息(指定时区)。
|
||||||
|
|
||||||
|
**参数:**
|
||||||
|
- `t`: 时间对象
|
||||||
|
- `timezone`: 时区字符串,如 "Asia/Shanghai"
|
||||||
|
|
||||||
|
**返回:** TimeInfo 结构体,包含:
|
||||||
|
- `UTC`: UTC时间(RFC3339格式)
|
||||||
|
- `Local`: 本地时间(RFC3339格式)
|
||||||
|
- `Unix`: Unix时间戳(秒)
|
||||||
|
- `Timezone`: 时区名称
|
||||||
|
- `Offset`: 时区偏移量(小时)
|
||||||
|
- `RFC3339`: RFC3339格式时间
|
||||||
|
- `DateTime`: 日期时间格式(2006-01-02 15:04:05)
|
||||||
|
- `Date`: 日期格式(2006-01-02)
|
||||||
|
- `Time`: 时间格式(15:04:05)
|
||||||
|
|
||||||
|
### 金额工具方法(黑盒模式)
|
||||||
|
|
||||||
|
#### 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` 中读取
|
||||||
|
- 如果没有设置环境变量,则使用默认版本号
|
||||||
|
|
||||||
## 设计优势
|
## 设计优势
|
||||||
|
|
||||||
### 优势总结
|
### 优势总结
|
||||||
|
|||||||
719
docs/http.md
719
docs/http.md
@@ -2,16 +2,17 @@
|
|||||||
|
|
||||||
## 概述
|
## 概述
|
||||||
|
|
||||||
HTTP Restful工具提供了标准化的HTTP请求和响应处理功能,采用Handler黑盒模式,封装了`ResponseWriter`和`Request`,提供简洁的API,无需每次都传递这两个参数。
|
HTTP Restful工具提供了标准化的HTTP请求和响应处理功能,提供公共方法供外部调用,保持低耦合。
|
||||||
|
|
||||||
## 功能特性
|
## 功能特性
|
||||||
|
|
||||||
- **黑盒模式**:封装`ResponseWriter`和`Request`,提供简洁的API
|
- **低耦合设计**:提供公共方法,不封装Handler结构
|
||||||
- **标准化的响应结构**:`{code, message, timestamp, data}`
|
- **标准化的响应结构**:`{code, message, timestamp, data}`
|
||||||
- **分离HTTP状态码和业务状态码**
|
- **分离HTTP状态码和业务状态码**
|
||||||
- **支持分页响应**
|
- **支持分页响应**
|
||||||
- **提供便捷的请求参数解析方法**
|
- **提供便捷的请求参数解析方法**
|
||||||
- **支持JSON请求体解析**
|
- **支持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
|
```json
|
||||||
@@ -42,163 +55,239 @@ 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"
|
||||||
|
"git.toowon.com/jimmy/go-common/tools"
|
||||||
|
)
|
||||||
|
|
||||||
|
func GetUser(w http.ResponseWriter, r *http.Request) {
|
||||||
|
fac, _ := factory.NewFactoryFromFile("config.json")
|
||||||
|
|
||||||
|
// 获取查询参数(使用类型转换方法)
|
||||||
|
id := tools.ConvertInt64(r.URL.Query().Get("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.GetPageSize()
|
||||||
|
|
||||||
|
// 获取查询参数(直接使用HTTP原生方法)
|
||||||
|
keyword := r.URL.Query().Get("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
|
```go
|
||||||
import (
|
import (
|
||||||
"net/http"
|
"net/http"
|
||||||
commonhttp "git.toowon.com/jimmy/go-common/http"
|
commonhttp "git.toowon.com/jimmy/go-common/http"
|
||||||
|
"git.toowon.com/jimmy/go-common/tools"
|
||||||
)
|
)
|
||||||
|
|
||||||
// 方式1:使用HandleFunc包装器(推荐,最简洁)
|
func GetUser(w http.ResponseWriter, r *http.Request) {
|
||||||
func GetUser(h *commonhttp.Handler) {
|
// 获取查询参数
|
||||||
id := h.GetQueryInt64("id", 0)
|
id := tools.ConvertInt64(r.URL.Query().Get("id"), 0)
|
||||||
h.Success(data)
|
|
||||||
|
// 返回成功响应
|
||||||
|
commonhttp.Success(w, data)
|
||||||
}
|
}
|
||||||
|
|
||||||
http.HandleFunc("/user", commonhttp.HandleFunc(GetUser))
|
func CreateUser(w http.ResponseWriter, r *http.Request) {
|
||||||
|
// 解析JSON
|
||||||
// 方式2:手动创建Handler(需要更多控制时)
|
var req struct {
|
||||||
http.HandleFunc("/user", func(w http.ResponseWriter, r *http.Request) {
|
Name string `json:"name"`
|
||||||
h := commonhttp.NewHandler(w, r)
|
}
|
||||||
GetUser(h)
|
if err := commonhttp.ParseJSON(r, &req); err != nil {
|
||||||
})
|
commonhttp.WriteJSON(w, http.StatusBadRequest, 400, "请求参数解析失败", nil)
|
||||||
```
|
return
|
||||||
|
|
||||||
### 2. 成功响应
|
|
||||||
|
|
||||||
```go
|
|
||||||
func handler(h *commonhttp.Handler) {
|
|
||||||
// 简单成功响应(data为nil)
|
|
||||||
h.Success(nil)
|
|
||||||
|
|
||||||
// 带数据的成功响应
|
|
||||||
data := map[string]interface{}{
|
|
||||||
"id": 1,
|
|
||||||
"name": "test",
|
|
||||||
}
|
}
|
||||||
h.Success(data)
|
|
||||||
|
|
||||||
// 带消息的成功响应
|
// 返回成功响应
|
||||||
h.SuccessWithMessage("操作成功", data)
|
commonhttp.Success(w, data, "创建成功")
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
### 3. 错误响应
|
### 成功响应
|
||||||
|
|
||||||
```go
|
```go
|
||||||
func handler(h *commonhttp.Handler) {
|
// 使用Factory(推荐)
|
||||||
// 业务错误(HTTP 200,业务code非0)
|
fac.Success(w, data) // 只有数据,使用默认消息 "success"
|
||||||
h.Error(1001, "用户不存在")
|
fac.Success(w, data, "操作成功") // 数据+消息
|
||||||
|
|
||||||
// 系统错误(HTTP 500)
|
// 或直接使用公共方法
|
||||||
h.SystemError("服务器内部错误")
|
commonhttp.Success(w, data) // 只有数据
|
||||||
|
commonhttp.Success(w, data, "操作成功") // 数据+消息
|
||||||
// 其他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)
|
|
||||||
}
|
|
||||||
```
|
```
|
||||||
|
|
||||||
### 4. 分页响应
|
### 错误响应
|
||||||
|
|
||||||
```go
|
```go
|
||||||
func handler(h *commonhttp.Handler) {
|
// 使用Factory(推荐)
|
||||||
// 获取分页参数
|
fac.Error(w, 1001, "用户不存在") // 业务错误(HTTP 200,业务code非0)
|
||||||
pagination := h.ParsePaginationRequest()
|
fac.SystemError(w, "服务器内部错误") // 系统错误(HTTP 500)
|
||||||
page := pagination.GetPage()
|
|
||||||
pageSize := pagination.GetSize()
|
// 或直接使用公共方法
|
||||||
|
commonhttp.Error(w, 1001, "用户不存在")
|
||||||
// 查询数据(示例)
|
commonhttp.SystemError(w, "服务器内部错误")
|
||||||
list, total := getDataList(page, pageSize)
|
commonhttp.WriteJSON(w, http.StatusBadRequest, 400, "请求参数错误", nil) // 自定义HTTP状态码(仅公共方法)
|
||||||
|
|
||||||
// 返回分页响应(使用默认消息)
|
|
||||||
h.SuccessPage(list, total, page, pageSize)
|
|
||||||
|
|
||||||
// 返回分页响应(自定义消息)
|
|
||||||
h.SuccessPage(list, total, page, pageSize, "查询成功")
|
|
||||||
}
|
|
||||||
```
|
```
|
||||||
|
|
||||||
### 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请求体
|
#### 解析JSON请求体
|
||||||
|
|
||||||
```go
|
```go
|
||||||
func handler(h *commonhttp.Handler) {
|
// 使用公共方法
|
||||||
type CreateUserRequest struct {
|
var req struct {
|
||||||
Name string `json:"name"`
|
Name string `json:"name"`
|
||||||
Email string `json:"email"`
|
Email string `json:"email"`
|
||||||
}
|
}
|
||||||
|
|
||||||
var req CreateUserRequest
|
if err := commonhttp.ParseJSON(r, &req); err != nil {
|
||||||
if err := h.ParseJSON(&req); err != nil {
|
commonhttp.WriteJSON(w, http.StatusBadRequest, 400, "请求参数解析失败", nil)
|
||||||
h.WriteJSON(http.StatusBadRequest, 400, "请求参数解析失败", nil)
|
return
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
// 使用req...
|
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
#### 获取查询参数
|
#### 获取查询参数
|
||||||
|
|
||||||
```go
|
```go
|
||||||
func handler(h *commonhttp.Handler) {
|
import "git.toowon.com/jimmy/go-common/tools"
|
||||||
// 获取字符串参数
|
|
||||||
name := h.GetQuery("name", "")
|
// 字符串直接获取
|
||||||
email := h.GetQuery("email", "default@example.com")
|
name := r.URL.Query().Get("name")
|
||||||
|
|
||||||
// 获取整数参数
|
// 使用类型转换方法
|
||||||
id := h.GetQueryInt("id", 0)
|
id := tools.ConvertInt(r.URL.Query().Get("id"), 0)
|
||||||
age := h.GetQueryInt("age", 18)
|
userId := tools.ConvertInt64(r.URL.Query().Get("userId"), 0)
|
||||||
|
isActive := tools.ConvertBool(r.URL.Query().Get("isActive"), false)
|
||||||
// 获取int64参数
|
price := tools.ConvertFloat64(r.URL.Query().Get("price"), 0.0)
|
||||||
userId := h.GetQueryInt64("userId", 0)
|
|
||||||
|
|
||||||
// 获取布尔参数
|
|
||||||
isActive := h.GetQueryBool("isActive", false)
|
|
||||||
|
|
||||||
// 获取浮点数参数
|
|
||||||
price := h.GetQueryFloat64("price", 0.0)
|
|
||||||
}
|
|
||||||
```
|
```
|
||||||
|
|
||||||
#### 获取表单参数
|
#### 获取表单参数
|
||||||
|
|
||||||
```go
|
```go
|
||||||
func handler(h *commonhttp.Handler) {
|
import "git.toowon.com/jimmy/go-common/tools"
|
||||||
// 获取表单字符串
|
|
||||||
name := h.GetFormValue("name", "")
|
// 字符串直接获取
|
||||||
|
name := r.FormValue("name")
|
||||||
// 获取表单整数
|
|
||||||
age := h.GetFormInt("age", 0)
|
// 使用类型转换方法
|
||||||
|
age := tools.ConvertInt(r.FormValue("age"), 0)
|
||||||
// 获取表单int64
|
userId := tools.ConvertInt64(r.FormValue("userId"), 0)
|
||||||
userId := h.GetFormInt64("userId", 0)
|
isActive := tools.ConvertBool(r.FormValue("isActive"), false)
|
||||||
|
|
||||||
// 获取表单布尔值
|
|
||||||
isActive := h.GetFormBool("isActive", false)
|
|
||||||
}
|
|
||||||
```
|
```
|
||||||
|
|
||||||
#### 获取请求头
|
#### 获取请求头
|
||||||
|
|
||||||
```go
|
```go
|
||||||
func handler(h *commonhttp.Handler) {
|
// 直接使用HTTP原生方法
|
||||||
token := h.GetHeader("Authorization", "")
|
token := r.Header.Get("Authorization")
|
||||||
contentType := h.GetHeader("Content-Type", "application/json")
|
contentType := r.Header.Get("Content-Type")
|
||||||
|
if contentType == "" {
|
||||||
|
contentType = "application/json" // 设置默认值
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -207,72 +296,57 @@ func handler(h *commonhttp.Handler) {
|
|||||||
**方式1:使用 PaginationRequest 结构(推荐)**
|
**方式1:使用 PaginationRequest 结构(推荐)**
|
||||||
|
|
||||||
```go
|
```go
|
||||||
func handler(h *commonhttp.Handler) {
|
// 定义请求结构(包含分页字段)
|
||||||
// 定义请求结构(包含分页字段)
|
type ListUserRequest struct {
|
||||||
type ListUserRequest struct {
|
Keyword string `json:"keyword"`
|
||||||
Keyword string `json:"keyword"`
|
commonhttp.PaginationRequest // 嵌入分页请求结构
|
||||||
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() // 计算偏移量
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// 或者从查询参数/form解析分页
|
// 从JSON请求体解析(分页字段会自动解析)
|
||||||
func handler(h *commonhttp.Handler) {
|
var req ListUserRequest
|
||||||
pagination := h.ParsePaginationRequest()
|
if err := commonhttp.ParseJSON(r, &req); err != nil {
|
||||||
page := pagination.GetPage()
|
commonhttp.WriteJSON(w, http.StatusBadRequest, 400, "请求参数解析失败", nil)
|
||||||
size := pagination.GetSize()
|
return
|
||||||
offset := pagination.GetOffset()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 使用分页方法
|
||||||
|
page := req.GetPage() // 获取页码(默认1)
|
||||||
|
pageSize := req.GetPageSize() // 获取每页数量(默认20,最大100)
|
||||||
|
offset := req.GetOffset() // 计算偏移量
|
||||||
|
```
|
||||||
|
|
||||||
|
**方式2:从查询参数/form解析分页**
|
||||||
|
|
||||||
|
```go
|
||||||
|
// 使用公共方法
|
||||||
|
pagination := commonhttp.ParsePaginationRequest(r)
|
||||||
|
page := pagination.GetPage()
|
||||||
|
pageSize := pagination.GetPageSize()
|
||||||
|
offset := pagination.GetOffset()
|
||||||
```
|
```
|
||||||
|
|
||||||
#### 获取时区
|
#### 获取时区
|
||||||
|
|
||||||
```go
|
```go
|
||||||
func handler(h *commonhttp.Handler) {
|
// 使用公共方法
|
||||||
// 从请求的context中获取时区
|
// 如果使用了middleware.Timezone中间件,可以从context中获取时区信息
|
||||||
// 如果使用了middleware.Timezone中间件,可以从context中获取时区信息
|
// 如果未设置,返回默认时区 AsiaShanghai
|
||||||
// 如果未设置,返回默认时区 AsiaShanghai
|
timezone := commonhttp.GetTimezone(r)
|
||||||
timezone := h.GetTimezone()
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
### 6. 访问原始对象
|
|
||||||
|
|
||||||
如果需要访问原始的`ResponseWriter`或`Request`:
|
|
||||||
|
|
||||||
```go
|
|
||||||
func handler(h *commonhttp.Handler) {
|
|
||||||
// 获取原始ResponseWriter
|
|
||||||
w := h.ResponseWriter()
|
|
||||||
|
|
||||||
// 获取原始Request
|
|
||||||
r := h.Request()
|
|
||||||
|
|
||||||
// 获取Context
|
|
||||||
ctx := h.Context()
|
|
||||||
}
|
|
||||||
```
|
```
|
||||||
|
|
||||||
## 完整示例
|
## 完整示例
|
||||||
|
|
||||||
|
### 使用Factory(推荐)
|
||||||
|
|
||||||
```go
|
```go
|
||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"log"
|
"log"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
"git.toowon.com/jimmy/go-common/factory"
|
||||||
commonhttp "git.toowon.com/jimmy/go-common/http"
|
commonhttp "git.toowon.com/jimmy/go-common/http"
|
||||||
|
"git.toowon.com/jimmy/go-common/tools"
|
||||||
)
|
)
|
||||||
|
|
||||||
// 用户结构
|
// 用户结构
|
||||||
@@ -283,91 +357,97 @@ type User struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// 用户列表接口
|
// 用户列表接口
|
||||||
func GetUserList(h *commonhttp.Handler) {
|
func GetUserList(w http.ResponseWriter, r *http.Request) {
|
||||||
// 获取分页参数
|
fac, _ := factory.NewFactoryFromFile("config.json")
|
||||||
pagination := h.ParsePaginationRequest()
|
|
||||||
page := pagination.GetPage()
|
|
||||||
pageSize := pagination.GetSize()
|
|
||||||
|
|
||||||
// 获取查询参数
|
// 获取分页参数(使用公共方法)
|
||||||
keyword := h.GetQuery("keyword", "")
|
pagination := commonhttp.ParsePaginationRequest(r)
|
||||||
|
page := pagination.GetPage()
|
||||||
|
pageSize := pagination.GetPageSize()
|
||||||
|
|
||||||
|
// 获取查询参数(直接使用HTTP原生方法)
|
||||||
|
keyword := r.URL.Query().Get("keyword")
|
||||||
|
|
||||||
// 查询数据
|
// 查询数据
|
||||||
users, total := queryUsers(keyword, page, pageSize)
|
users, total := queryUsers(keyword, page, pageSize)
|
||||||
|
|
||||||
// 返回分页响应
|
// 返回分页响应(使用factory方法)
|
||||||
h.SuccessPage(users, total, page, pageSize)
|
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 {
|
var req struct {
|
||||||
Name string `json:"name"`
|
Name string `json:"name"`
|
||||||
Email string `json:"email"`
|
Email string `json:"email"`
|
||||||
}
|
}
|
||||||
|
|
||||||
if err := h.ParseJSON(&req); err != nil {
|
if err := commonhttp.ParseJSON(r, &req); err != nil {
|
||||||
h.WriteJSON(http.StatusBadRequest, 400, "请求参数解析失败", nil)
|
fac.WriteJSON(w, http.StatusBadRequest, 400, "请求参数解析失败", nil)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// 参数验证
|
// 参数验证
|
||||||
if req.Name == "" {
|
if req.Name == "" {
|
||||||
h.Error(1001, "用户名不能为空")
|
fac.Error(w, 1001, "用户名不能为空")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// 创建用户
|
// 创建用户
|
||||||
user, err := createUser(req.Name, req.Email)
|
user, err := createUser(req.Name, req.Email)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
h.SystemError("创建用户失败")
|
fac.SystemError(w, "创建用户失败")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// 返回成功响应
|
// 返回成功响应(使用factory方法)
|
||||||
h.SuccessWithMessage("创建成功", user)
|
fac.Success(w, user, "创建成功")
|
||||||
}
|
}
|
||||||
|
|
||||||
// 获取用户详情接口
|
// 获取用户详情接口
|
||||||
func GetUser(h *commonhttp.Handler) {
|
func GetUser(w http.ResponseWriter, r *http.Request) {
|
||||||
// 获取查询参数
|
fac, _ := factory.NewFactoryFromFile("config.json")
|
||||||
id := h.GetQueryInt64("id", 0)
|
|
||||||
|
// 获取查询参数(使用类型转换方法)
|
||||||
|
id := tools.ConvertInt64(r.URL.Query().Get("id"), 0)
|
||||||
|
|
||||||
if id == 0 {
|
if id == 0 {
|
||||||
h.WriteJSON(http.StatusBadRequest, 400, "用户ID不能为空", nil)
|
commonhttp.WriteJSON(w, http.StatusBadRequest, 400, "用户ID不能为空", nil)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// 查询用户
|
// 查询用户
|
||||||
user, err := getUserByID(id)
|
user, err := getUserByID(id)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
h.SystemError("查询用户失败")
|
fac.SystemError(w, "查询用户失败")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
if user == nil {
|
if user == nil {
|
||||||
h.Error(1002, "用户不存在")
|
fac.Error(w, 1002, "用户不存在")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
h.Success(user)
|
// 返回成功响应(使用factory方法)
|
||||||
|
fac.Success(w, user)
|
||||||
}
|
}
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
// 使用HandleFunc包装器(推荐)
|
http.HandleFunc("/users", func(w http.ResponseWriter, r *http.Request) {
|
||||||
http.HandleFunc("/users", commonhttp.HandleFunc(func(h *commonhttp.Handler) {
|
switch r.Method {
|
||||||
switch h.Request().Method {
|
|
||||||
case http.MethodGet:
|
case http.MethodGet:
|
||||||
GetUserList(h)
|
GetUserList(w, r)
|
||||||
case http.MethodPost:
|
case http.MethodPost:
|
||||||
CreateUser(h)
|
CreateUser(w, r)
|
||||||
default:
|
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.Println("Server started on :8080")
|
||||||
log.Fatal(http.ListenAndServe(":8080", nil))
|
log.Fatal(http.ListenAndServe(":8080", nil))
|
||||||
@@ -376,53 +456,93 @@ func main() {
|
|||||||
|
|
||||||
## API 参考
|
## API 参考
|
||||||
|
|
||||||
### Handler结构
|
### Factory HTTP响应结构体(暴露给外部项目使用)
|
||||||
|
|
||||||
Handler封装了`ResponseWriter`和`Request`,提供更简洁的API。
|
#### Response
|
||||||
|
|
||||||
```go
|
标准响应结构体,外部项目可以直接使用 `factory.Response`。
|
||||||
type Handler struct {
|
|
||||||
w http.ResponseWriter
|
|
||||||
r *http.Request
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
### 创建Handler
|
**字段:**
|
||||||
|
- `Code`: 业务状态码,0表示成功
|
||||||
#### NewHandler(w http.ResponseWriter, r *http.Request) *Handler
|
- `Message`: 响应消息
|
||||||
|
- `Timestamp`: 时间戳(Unix时间戳,秒)
|
||||||
创建Handler实例。
|
- `Data`: 响应数据
|
||||||
|
|
||||||
#### HandleFunc(fn func(*Handler)) http.HandlerFunc
|
|
||||||
|
|
||||||
将Handler函数转换为标准的http.HandlerFunc(便捷包装器)。
|
|
||||||
|
|
||||||
**示例:**
|
**示例:**
|
||||||
```go
|
```go
|
||||||
http.HandleFunc("/users", commonhttp.HandleFunc(func(h *commonhttp.Handler) {
|
response := factory.Response{
|
||||||
h.Success(data)
|
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。
|
成功响应,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。
|
业务错误响应,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。
|
系统错误响应,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响应(自定义)。
|
写入JSON响应(自定义)。
|
||||||
|
|
||||||
@@ -432,7 +552,17 @@ http.HandleFunc("/users", commonhttp.HandleFunc(func(h *commonhttp.Handler) {
|
|||||||
- `message`: 响应消息
|
- `message`: 响应消息
|
||||||
- `data`: 响应数据
|
- `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 +573,81 @@ http.HandleFunc("/users", commonhttp.HandleFunc(func(h *commonhttp.Handler) {
|
|||||||
- `pageSize`: 每页大小
|
- `pageSize`: 每页大小
|
||||||
- `message`: 响应消息(可选,如果为空则使用默认消息 "success")
|
- `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请求体。
|
解析JSON请求体。
|
||||||
|
|
||||||
#### (h *Handler) GetQuery(key, defaultValue string) string
|
**示例:**
|
||||||
|
```go
|
||||||
|
var req CreateUserRequest
|
||||||
|
if err := commonhttp.ParseJSON(r, &req); err != nil {
|
||||||
|
// 处理错误
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
获取查询参数(字符串)。
|
#### 获取查询参数和表单参数
|
||||||
|
|
||||||
#### (h *Handler) GetQueryInt(key string, defaultValue int) int
|
**推荐方式:使用类型转换工具**
|
||||||
|
|
||||||
获取查询参数(整数)。
|
```go
|
||||||
|
import "git.toowon.com/jimmy/go-common/tools"
|
||||||
|
|
||||||
#### (h *Handler) GetQueryInt64(key string, defaultValue int64) int64
|
// 字符串直接使用HTTP原生方法
|
||||||
|
name := r.URL.Query().Get("name")
|
||||||
|
if name == "" {
|
||||||
|
name = "default" // 设置默认值
|
||||||
|
}
|
||||||
|
|
||||||
获取查询参数(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)
|
||||||
|
|
||||||
#### (h *Handler) GetQueryBool(key string, defaultValue bool) bool
|
// 表单参数类似
|
||||||
|
age := tools.ConvertInt(r.FormValue("age"), 0)
|
||||||
|
```
|
||||||
|
|
||||||
获取查询参数(布尔值)。
|
**类型转换方法说明:**
|
||||||
|
|
||||||
#### (h *Handler) GetQueryFloat64(key string, defaultValue float64) float64
|
- `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
|
||||||
|
|
||||||
获取查询参数(浮点数)。
|
**获取请求头:**
|
||||||
|
|
||||||
#### (h *Handler) GetFormValue(key, defaultValue string) string
|
```go
|
||||||
|
// 直接使用HTTP原生方法
|
||||||
|
token := r.Header.Get("Authorization")
|
||||||
|
contentType := r.Header.Get("Content-Type")
|
||||||
|
```
|
||||||
|
|
||||||
获取表单值(字符串)。
|
#### ParsePaginationRequest(r *http.Request) *PaginationRequest
|
||||||
|
|
||||||
#### (h *Handler) GetFormInt(key string, defaultValue int) int
|
|
||||||
|
|
||||||
获取表单值(整数)。
|
|
||||||
|
|
||||||
#### (h *Handler) GetFormInt64(key string, defaultValue int64) int64
|
|
||||||
|
|
||||||
获取表单值(int64)。
|
|
||||||
|
|
||||||
#### (h *Handler) GetFormBool(key string, defaultValue bool) bool
|
|
||||||
|
|
||||||
获取表单值(布尔值)。
|
|
||||||
|
|
||||||
#### (h *Handler) GetHeader(key, defaultValue string) string
|
|
||||||
|
|
||||||
获取请求头。
|
|
||||||
|
|
||||||
#### (h *Handler) ParsePaginationRequest() *PaginationRequest
|
|
||||||
|
|
||||||
从请求中解析分页参数。
|
从请求中解析分页参数。
|
||||||
|
|
||||||
@@ -498,7 +656,7 @@ http.HandleFunc("/users", commonhttp.HandleFunc(func(h *commonhttp.Handler) {
|
|||||||
- 优先级:查询参数 > form表单
|
- 优先级:查询参数 > form表单
|
||||||
- 如果请求体是JSON格式且包含分页字段,建议先使用`ParseJSON`解析完整请求体到包含`PaginationRequest`的结构体中
|
- 如果请求体是JSON格式且包含分页字段,建议先使用`ParseJSON`解析完整请求体到包含`PaginationRequest`的结构体中
|
||||||
|
|
||||||
#### (h *Handler) GetTimezone() string
|
#### GetTimezone(r *http.Request) string
|
||||||
|
|
||||||
从请求的context中获取时区。
|
从请求的context中获取时区。
|
||||||
|
|
||||||
@@ -506,19 +664,39 @@ http.HandleFunc("/users", commonhttp.HandleFunc(func(h *commonhttp.Handler) {
|
|||||||
- 如果使用了middleware.Timezone中间件,可以从context中获取时区信息
|
- 如果使用了middleware.Timezone中间件,可以从context中获取时区信息
|
||||||
- 如果未设置,返回默认时区 AsiaShanghai
|
- 如果未设置,返回默认时区 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)
|
||||||
|
|
||||||
|
分页成功响应(公共方法)。
|
||||||
|
|
||||||
### 分页请求结构
|
### 分页请求结构
|
||||||
|
|
||||||
@@ -528,12 +706,11 @@ http.HandleFunc("/users", commonhttp.HandleFunc(func(h *commonhttp.Handler) {
|
|||||||
|
|
||||||
**字段:**
|
**字段:**
|
||||||
- `Page`: 页码(默认1)
|
- `Page`: 页码(默认1)
|
||||||
- `Size`: 每页数量(兼容旧版本)
|
- `PageSize`: 每页数量
|
||||||
- `PageSize`: 每页数量(推荐使用,优先于Size)
|
|
||||||
|
|
||||||
**方法:**
|
**方法:**
|
||||||
- `GetPage() int`: 获取页码,如果未设置则返回默认值1
|
- `GetPage() int`: 获取页码,如果未设置则返回默认值1
|
||||||
- `GetSize() int`: 获取每页数量,优先使用PageSize,如果未设置则使用Size,默认20,最大100
|
- `GetPageSize() int`: 获取每页数量,如果未设置则返回默认值20,最大限制100
|
||||||
- `GetOffset() int`: 计算数据库查询的偏移量
|
- `GetOffset() int`: 计算数据库查询的偏移量
|
||||||
|
|
||||||
#### ParsePaginationRequest(r *http.Request) *PaginationRequest
|
#### ParsePaginationRequest(r *http.Request) *PaginationRequest
|
||||||
@@ -575,10 +752,14 @@ http.HandleFunc("/users", commonhttp.HandleFunc(func(h *commonhttp.Handler) {
|
|||||||
- 使用`SystemError`返回系统错误(HTTP 500)
|
- 使用`SystemError`返回系统错误(HTTP 500)
|
||||||
- 其他HTTP错误状态码(400, 401, 403, 404等)使用`WriteJSON`方法直接指定
|
- 其他HTTP错误状态码(400, 401, 403, 404等)使用`WriteJSON`方法直接指定
|
||||||
|
|
||||||
5. **黑盒模式**:
|
5. **推荐使用Factory**:
|
||||||
- 所有功能都通过Handler对象调用,无需传递`w`和`r`参数
|
- 使用 `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黑盒模式示例
|
||||||
|
|||||||
510
docs/i18n.md
Normal file
510
docs/i18n.md
Normal file
@@ -0,0 +1,510 @@
|
|||||||
|
# 国际化工具文档
|
||||||
|
|
||||||
|
## 概述
|
||||||
|
|
||||||
|
国际化工具(i18n)提供多语言内容管理功能,支持从文件加载语言内容,通过语言代码和消息代码获取对应语言的内容。
|
||||||
|
|
||||||
|
## 功能特性
|
||||||
|
|
||||||
|
- **多语言支持**:支持加载多个语言文件
|
||||||
|
- **文件加载**:支持从目录或单个文件加载语言内容
|
||||||
|
- **语言回退**:当指定语言不存在时,自动回退到默认语言
|
||||||
|
- **参数替换**:支持在消息中使用格式化参数(类似 fmt.Sprintf)
|
||||||
|
- **并发安全**:使用读写锁保证并发安全
|
||||||
|
- **动态加载**:支持重新加载语言文件
|
||||||
|
|
||||||
|
## 快速开始
|
||||||
|
|
||||||
|
### 1. 创建语言文件
|
||||||
|
|
||||||
|
创建语言文件目录 `locales/`,并创建对应的语言文件:
|
||||||
|
|
||||||
|
**locales/zh-CN.json**:
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"user.not_found": {
|
||||||
|
"code": 100002,
|
||||||
|
"message": "用户不存在"
|
||||||
|
},
|
||||||
|
"user.login_success": {
|
||||||
|
"code": 0,
|
||||||
|
"message": "登录成功"
|
||||||
|
},
|
||||||
|
"user.welcome": {
|
||||||
|
"code": 0,
|
||||||
|
"message": "欢迎,%s"
|
||||||
|
},
|
||||||
|
"error.invalid_params": {
|
||||||
|
"code": 100001,
|
||||||
|
"message": "参数无效"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**locales/en-US.json**:
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"user.not_found": {
|
||||||
|
"code": 100002,
|
||||||
|
"message": "User not found"
|
||||||
|
},
|
||||||
|
"user.login_success": {
|
||||||
|
"code": 0,
|
||||||
|
"message": "Login successful"
|
||||||
|
},
|
||||||
|
"user.welcome": {
|
||||||
|
"code": 0,
|
||||||
|
"message": "Welcome, %s"
|
||||||
|
},
|
||||||
|
"error.invalid_params": {
|
||||||
|
"code": 100001,
|
||||||
|
"message": "Invalid parameters"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2. 初始化并使用
|
||||||
|
|
||||||
|
```go
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"git.toowon.com/jimmy/go-common/factory"
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
// 创建工厂实例
|
||||||
|
fac, _ := factory.NewFactoryFromFile("config.json")
|
||||||
|
|
||||||
|
// 初始化国际化工具,设置默认语言为中文
|
||||||
|
fac.InitI18n("zh-CN")
|
||||||
|
|
||||||
|
// 从目录加载所有语言文件
|
||||||
|
fac.LoadI18nFromDir("locales")
|
||||||
|
|
||||||
|
// 获取消息
|
||||||
|
msg := fac.GetMessage("zh-CN", "user.not_found")
|
||||||
|
// 返回: "用户不存在"
|
||||||
|
|
||||||
|
// 带参数的消息
|
||||||
|
msg = fac.GetMessage("zh-CN", "user.welcome", "Alice")
|
||||||
|
// 返回: "欢迎,Alice"
|
||||||
|
|
||||||
|
// 在HTTP handler中使用Error方法(推荐)
|
||||||
|
// fac.Error(w, r, 0, "user.not_found")
|
||||||
|
// 会自动从语言文件获取业务code和国际化消息
|
||||||
|
// 返回: {"code": 100002, "message": "用户不存在"}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## API 文档
|
||||||
|
|
||||||
|
### 初始化方法
|
||||||
|
|
||||||
|
#### InitI18n
|
||||||
|
|
||||||
|
初始化国际化工具,设置默认语言。
|
||||||
|
|
||||||
|
```go
|
||||||
|
fac.InitI18n(defaultLang string)
|
||||||
|
```
|
||||||
|
|
||||||
|
**参数**:
|
||||||
|
- `defaultLang`: 默认语言代码(如 "zh-CN", "en-US")
|
||||||
|
|
||||||
|
**示例**:
|
||||||
|
```go
|
||||||
|
fac.InitI18n("zh-CN")
|
||||||
|
```
|
||||||
|
|
||||||
|
### 加载方法
|
||||||
|
|
||||||
|
#### LoadI18nFromDir
|
||||||
|
|
||||||
|
从目录加载多个语言文件(推荐方式)。
|
||||||
|
|
||||||
|
```go
|
||||||
|
fac.LoadI18nFromDir(dirPath string) error
|
||||||
|
```
|
||||||
|
|
||||||
|
**参数**:
|
||||||
|
- `dirPath`: 语言文件目录路径
|
||||||
|
|
||||||
|
**文件命名规则**:
|
||||||
|
- 文件必须以 `.json` 结尾
|
||||||
|
- 文件名(去掉 `.json` 后缀)作为语言代码
|
||||||
|
- 例如:`zh-CN.json` 对应语言代码 `zh-CN`
|
||||||
|
|
||||||
|
**示例**:
|
||||||
|
```go
|
||||||
|
fac.LoadI18nFromDir("locales")
|
||||||
|
```
|
||||||
|
|
||||||
|
#### LoadI18nFromFile
|
||||||
|
|
||||||
|
从单个语言文件加载内容。
|
||||||
|
|
||||||
|
```go
|
||||||
|
fac.LoadI18nFromFile(filePath, lang string) error
|
||||||
|
```
|
||||||
|
|
||||||
|
**参数**:
|
||||||
|
- `filePath`: 语言文件路径(JSON格式)
|
||||||
|
- `lang`: 语言代码(如 "zh-CN", "en-US")
|
||||||
|
|
||||||
|
**示例**:
|
||||||
|
```go
|
||||||
|
fac.LoadI18nFromFile("locales/zh-CN.json", "zh-CN")
|
||||||
|
fac.LoadI18nFromFile("locales/en-US.json", "en-US")
|
||||||
|
```
|
||||||
|
|
||||||
|
### 错误响应方法
|
||||||
|
|
||||||
|
#### Error
|
||||||
|
|
||||||
|
错误响应(自动国际化,推荐使用)。
|
||||||
|
|
||||||
|
```go
|
||||||
|
fac.Error(w, r, code int, message string, args ...interface{})
|
||||||
|
```
|
||||||
|
|
||||||
|
**参数**:
|
||||||
|
- `w`: ResponseWriter
|
||||||
|
- `r`: HTTP请求(用于获取语言信息)
|
||||||
|
- `code`: 业务错误码(如果message是消息代码,此参数会被语言文件中的code覆盖)
|
||||||
|
- `message`: 错误消息或消息代码(如果i18n已初始化且message是消息代码格式,会自动获取国际化消息和业务code)
|
||||||
|
- `args`: 可选参数,用于格式化消息(类似 fmt.Sprintf,仅在message是消息代码时使用)
|
||||||
|
|
||||||
|
**使用逻辑**:
|
||||||
|
1. 如果i18n已初始化,且message看起来是消息代码(包含点号,如 "user.not_found"),
|
||||||
|
则从请求context中获取语言,并尝试从语言文件中获取国际化消息和业务code
|
||||||
|
2. 如果获取到国际化消息,使用语言文件中的code作为响应code,使用国际化消息作为响应message
|
||||||
|
3. 如果未获取到或i18n未初始化,使用传入的code和message
|
||||||
|
|
||||||
|
**示例**:
|
||||||
|
```go
|
||||||
|
// 方式1:传入消息代码(推荐,自动获取业务code和国际化消息)
|
||||||
|
fac.Error(w, r, 0, "user.not_found")
|
||||||
|
// 如果请求语言是 zh-CN,且语言文件中 "user.not_found" 的 code 是 100002,
|
||||||
|
// 返回: {"code": 100002, "message": "用户不存在"}
|
||||||
|
// 如果请求语言是 en-US,返回: {"code": 100002, "message": "User not found"}
|
||||||
|
// 注意:业务code在所有语言中保持一致
|
||||||
|
|
||||||
|
// 方式2:带参数的消息代码
|
||||||
|
fac.Error(w, r, 0, "user.welcome", "Alice")
|
||||||
|
// 如果消息内容是 "欢迎,%s",返回: {"code": 0, "message": "欢迎,Alice"}
|
||||||
|
|
||||||
|
// 方式3:直接传入消息文本(不使用国际化)
|
||||||
|
fac.Error(w, r, 500, "系统错误")
|
||||||
|
// 返回: {"code": 500, "message": "系统错误"}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 获取消息方法
|
||||||
|
|
||||||
|
#### GetMessage
|
||||||
|
|
||||||
|
获取指定语言和代码的消息内容(推荐使用)。
|
||||||
|
|
||||||
|
```go
|
||||||
|
fac.GetMessage(lang, code string, args ...interface{}) string
|
||||||
|
```
|
||||||
|
|
||||||
|
**参数**:
|
||||||
|
- `lang`: 语言代码(如 "zh-CN", "en-US")
|
||||||
|
- `code`: 消息代码(如 "user.not_found")
|
||||||
|
- `args`: 可选参数,用于格式化消息(类似 fmt.Sprintf)
|
||||||
|
|
||||||
|
**返回逻辑**:
|
||||||
|
1. 如果指定语言存在该code,返回对应内容
|
||||||
|
2. 如果指定语言不存在,尝试使用默认语言
|
||||||
|
3. 如果默认语言也不存在,返回code本身(作为fallback)
|
||||||
|
|
||||||
|
**示例**:
|
||||||
|
```go
|
||||||
|
// 简单消息
|
||||||
|
msg := fac.GetMessage("zh-CN", "user.not_found")
|
||||||
|
// 返回: "用户不存在"
|
||||||
|
|
||||||
|
// 带参数的消息
|
||||||
|
msg := fac.GetMessage("zh-CN", "user.welcome", "Alice")
|
||||||
|
// 如果消息内容是 "欢迎,%s",返回: "欢迎,Alice"
|
||||||
|
```
|
||||||
|
|
||||||
|
### GetLanguage
|
||||||
|
|
||||||
|
从请求的context中获取语言代码(推荐使用)。
|
||||||
|
|
||||||
|
```go
|
||||||
|
fac.GetLanguage(r *http.Request) string
|
||||||
|
```
|
||||||
|
|
||||||
|
**参数**:
|
||||||
|
- `r`: HTTP请求
|
||||||
|
|
||||||
|
**返回逻辑**:
|
||||||
|
1. 从请求context中获取语言(由middleware.Language中间件设置)
|
||||||
|
2. 如果未设置,返回默认语言 zh-CN
|
||||||
|
|
||||||
|
**示例**:
|
||||||
|
```go
|
||||||
|
lang := fac.GetLanguage(r)
|
||||||
|
// 可能返回: "zh-CN", "en-US" 等
|
||||||
|
```
|
||||||
|
|
||||||
|
### 高级功能
|
||||||
|
|
||||||
|
#### GetI18n
|
||||||
|
|
||||||
|
获取国际化工具对象(仅在需要高级功能时使用)。
|
||||||
|
|
||||||
|
```go
|
||||||
|
fac.GetI18n() (*i18n.I18n, error)
|
||||||
|
```
|
||||||
|
|
||||||
|
**返回**:国际化工具对象
|
||||||
|
|
||||||
|
**高级功能示例**:
|
||||||
|
```go
|
||||||
|
i18n, _ := fac.GetI18n()
|
||||||
|
|
||||||
|
// 检查语言是否存在
|
||||||
|
hasLang := i18n.HasLang("en-US")
|
||||||
|
|
||||||
|
// 获取所有支持的语言
|
||||||
|
langs := i18n.GetSupportedLangs()
|
||||||
|
|
||||||
|
// 重新加载语言文件
|
||||||
|
i18n.ReloadFromFile("locales/zh-CN.json", "zh-CN")
|
||||||
|
|
||||||
|
// 动态设置默认语言
|
||||||
|
i18n.SetDefaultLang("en-US")
|
||||||
|
```
|
||||||
|
|
||||||
|
## 使用场景
|
||||||
|
|
||||||
|
### 场景1:HTTP API 响应消息(推荐使用 Error 方法)
|
||||||
|
|
||||||
|
**推荐方式**:使用 `Error` 方法,自动从请求中获取语言并返回国际化消息和业务code:
|
||||||
|
|
||||||
|
```go
|
||||||
|
func handleLogin(w http.ResponseWriter, r *http.Request) {
|
||||||
|
fac, _ := factory.NewFactoryFromFile("config.json")
|
||||||
|
|
||||||
|
// 验证用户
|
||||||
|
user, err := validateUser(r)
|
||||||
|
if err != nil {
|
||||||
|
// 直接传入消息代码,自动获取业务code和国际化消息(推荐)
|
||||||
|
// 会自动从请求context获取语言(由middleware.Language中间件设置)
|
||||||
|
fac.Error(w, r, 0, "user.not_found")
|
||||||
|
// 返回: {"code": 100002, "message": "用户不存在"} 或 {"code": 100002, "message": "User not found"}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// 成功消息
|
||||||
|
lang := fac.GetLanguage(r)
|
||||||
|
msg := fac.GetMessage(lang, "user.login_success")
|
||||||
|
fac.Success(w, user, msg)
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 场景2:带参数的消息
|
||||||
|
|
||||||
|
```go
|
||||||
|
func handleWelcome(w http.ResponseWriter, r *http.Request) {
|
||||||
|
fac, _ := factory.NewFactoryFromFile("config.json")
|
||||||
|
lang := getLangFromRequest(r)
|
||||||
|
|
||||||
|
username := "Alice"
|
||||||
|
// 消息内容: "欢迎,%s"
|
||||||
|
msg := fac.GetMessage(lang, "user.welcome", username)
|
||||||
|
// 返回: "欢迎,Alice" 或 "Welcome, Alice"
|
||||||
|
|
||||||
|
fac.Success(w, nil, msg)
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 场景3:错误消息国际化(推荐使用 Error 方法)
|
||||||
|
|
||||||
|
**推荐方式**:使用 `Error` 方法,自动获取业务code和国际化消息:
|
||||||
|
|
||||||
|
```go
|
||||||
|
func handleError(w http.ResponseWriter, r *http.Request, messageCode string) {
|
||||||
|
fac, _ := factory.NewFactoryFromFile("config.json")
|
||||||
|
|
||||||
|
// 直接传入消息代码,自动获取业务code和国际化消息(推荐)
|
||||||
|
// 会自动从请求context获取语言并查找对应的国际化消息和业务code
|
||||||
|
fac.Error(w, r, 0, "error."+messageCode)
|
||||||
|
// 例如:fac.Error(w, r, 0, "error.invalid_params")
|
||||||
|
// 返回: {"code": 100001, "message": "参数无效"} 或 {"code": 100001, "message": "Invalid parameters"}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## 语言文件格式
|
||||||
|
|
||||||
|
语言文件必须是 JSON 格式,每个消息包含业务code和消息内容:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"user.not_found": {
|
||||||
|
"code": 100002,
|
||||||
|
"message": "用户不存在"
|
||||||
|
},
|
||||||
|
"user.login_success": {
|
||||||
|
"code": 0,
|
||||||
|
"message": "登录成功"
|
||||||
|
},
|
||||||
|
"user.welcome": {
|
||||||
|
"code": 0,
|
||||||
|
"message": "欢迎,%s"
|
||||||
|
},
|
||||||
|
"error.invalid_params": {
|
||||||
|
"code": 100001,
|
||||||
|
"message": "参数无效"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**注意事项**:
|
||||||
|
- key(消息代码)建议使用点号分隔的层级结构(如 `user.not_found`)
|
||||||
|
- value 是一个对象,包含:
|
||||||
|
- `code`: 业务错误码(整数),用于业务逻辑判断,所有语言的同一消息代码应使用相同的code
|
||||||
|
- `message`: 消息内容(字符串),支持格式化占位符(如 `%s`, `%d`)
|
||||||
|
- 所有语言文件应该包含相同的 key,确保所有语言都有对应的翻译
|
||||||
|
- **重要**:同一消息代码在所有语言文件中的 `code` 必须保持一致,只有 `message` 会根据语言变化
|
||||||
|
|
||||||
|
## 最佳实践
|
||||||
|
|
||||||
|
### 1. 消息代码命名规范
|
||||||
|
|
||||||
|
建议使用层级结构,便于管理和查找:
|
||||||
|
|
||||||
|
```
|
||||||
|
模块.功能.状态
|
||||||
|
例如:
|
||||||
|
- user.not_found
|
||||||
|
- user.login_success
|
||||||
|
- order.created
|
||||||
|
- order.paid
|
||||||
|
- error.invalid_params
|
||||||
|
- error.server_error
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2. 默认语言设置
|
||||||
|
|
||||||
|
建议将最常用的语言设置为默认语言,确保在语言不存在时有合理的回退:
|
||||||
|
|
||||||
|
```go
|
||||||
|
fac.InitI18n("zh-CN") // 中文作为默认语言
|
||||||
|
```
|
||||||
|
|
||||||
|
### 3. 语言代码规范
|
||||||
|
|
||||||
|
建议使用标准的语言代码格式:
|
||||||
|
- `zh-CN`: 简体中文
|
||||||
|
- `zh-TW`: 繁体中文
|
||||||
|
- `en-US`: 美式英语
|
||||||
|
- `en-GB`: 英式英语
|
||||||
|
- `ja-JP`: 日语
|
||||||
|
- `ko-KR`: 韩语
|
||||||
|
|
||||||
|
### 4. 文件组织
|
||||||
|
|
||||||
|
建议将所有语言文件放在统一的目录下:
|
||||||
|
|
||||||
|
```
|
||||||
|
project/
|
||||||
|
locales/
|
||||||
|
zh-CN.json
|
||||||
|
en-US.json
|
||||||
|
ja-JP.json
|
||||||
|
```
|
||||||
|
|
||||||
|
### 5. 参数使用
|
||||||
|
|
||||||
|
对于需要动态内容的消息,使用格式化参数:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"user.welcome": {
|
||||||
|
"code": 0,
|
||||||
|
"message": "欢迎,%s"
|
||||||
|
},
|
||||||
|
"order.total": {
|
||||||
|
"code": 0,
|
||||||
|
"message": "订单总额:%.2f 元"
|
||||||
|
},
|
||||||
|
"message.count": {
|
||||||
|
"code": 0,
|
||||||
|
"message": "您有 %d 条新消息"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
使用方式:
|
||||||
|
```go
|
||||||
|
// 使用 GetMessage
|
||||||
|
msg := fac.GetMessage("zh-CN", "user.welcome", "Alice")
|
||||||
|
msg := fac.GetMessage("zh-CN", "order.total", 99.99)
|
||||||
|
msg := fac.GetMessage("zh-CN", "message.count", 5)
|
||||||
|
|
||||||
|
// 使用 Error 方法(推荐)
|
||||||
|
fac.Error(w, r, 0, "user.welcome", "Alice")
|
||||||
|
fac.Error(w, r, 0, "message.count", 5)
|
||||||
|
```
|
||||||
|
|
||||||
|
### 6. 业务Code管理
|
||||||
|
|
||||||
|
**重要原则**:同一消息代码在所有语言文件中的业务code必须保持一致。
|
||||||
|
|
||||||
|
```json
|
||||||
|
// zh-CN.json
|
||||||
|
{
|
||||||
|
"user.not_found": {
|
||||||
|
"code": 100002, // 业务code
|
||||||
|
"message": "用户不存在"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// en-US.json
|
||||||
|
{
|
||||||
|
"user.not_found": {
|
||||||
|
"code": 100002, // 必须与zh-CN.json中的code相同
|
||||||
|
"message": "User not found" // 只有message会根据语言变化
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
这样设计的好处:
|
||||||
|
- 调用端可以根据返回的 `code` 进行业务逻辑判断,不受语言影响
|
||||||
|
- 所有语言的同一错误使用相同的业务code,便于统一管理
|
||||||
|
|
||||||
|
## 常见问题
|
||||||
|
|
||||||
|
### Q1: 如果语言文件不存在会怎样?
|
||||||
|
|
||||||
|
A: 如果语言文件不存在,`LoadI18nFromFile` 或 `LoadI18nFromDir` 会返回错误。建议在初始化时检查错误。
|
||||||
|
|
||||||
|
### Q2: 如果消息代码不存在会怎样?
|
||||||
|
|
||||||
|
A: `GetMessage` 和 `Error` 会按以下顺序查找:
|
||||||
|
1. 指定语言的消息
|
||||||
|
2. 默认语言的消息
|
||||||
|
3. 如果都不存在:
|
||||||
|
- `GetMessage` 返回消息代码本身(作为fallback)
|
||||||
|
- `Error` 使用传入的code参数和消息代码作为message
|
||||||
|
|
||||||
|
### Q5: 业务code在不同语言中必须相同吗?
|
||||||
|
|
||||||
|
A: **是的,必须相同**。同一消息代码在所有语言文件中的业务code必须保持一致,只有message内容会根据语言变化。这样调用端可以根据code进行业务逻辑判断,不受语言影响。
|
||||||
|
|
||||||
|
### Q3: 如何支持动态加载语言文件?
|
||||||
|
|
||||||
|
A: 可以使用 `GetI18n()` 获取对象,然后调用 `ReloadFromFile()` 或 `ReloadFromDir()` 方法。
|
||||||
|
|
||||||
|
### Q4: 是否支持嵌套的消息结构?
|
||||||
|
|
||||||
|
A: 当前版本只支持扁平结构(key-value),不支持嵌套。如果需要嵌套结构,建议使用点号分隔的层级命名(如 `user.profile.name`)。
|
||||||
|
|
||||||
|
## 完整示例
|
||||||
|
|
||||||
|
参考 [examples/i18n_example.go](../examples/i18n_example.go)
|
||||||
@@ -136,7 +136,7 @@ import (
|
|||||||
"net/http"
|
"net/http"
|
||||||
"git.toowon.com/jimmy/go-common/middleware"
|
"git.toowon.com/jimmy/go-common/middleware"
|
||||||
commonhttp "git.toowon.com/jimmy/go-common/http"
|
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) {
|
func handler(w http.ResponseWriter, r *http.Request) {
|
||||||
@@ -146,12 +146,12 @@ func handler(w http.ResponseWriter, r *http.Request) {
|
|||||||
timezone := h.GetTimezone()
|
timezone := h.GetTimezone()
|
||||||
|
|
||||||
// 使用时区
|
// 使用时区
|
||||||
now := datetime.Now(timezone)
|
now := tools.Now(timezone)
|
||||||
datetime.FormatDateTime(now, timezone)
|
tools.FormatDateTime(now, timezone)
|
||||||
|
|
||||||
h.Success(map[string]interface{}{
|
h.Success(map[string]interface{}{
|
||||||
"timezone": timezone,
|
"timezone": timezone,
|
||||||
"time": datetime.FormatDateTime(now),
|
"time": tools.FormatDateTime(now),
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -168,7 +168,7 @@ func main() {
|
|||||||
import (
|
import (
|
||||||
"net/http"
|
"net/http"
|
||||||
"git.toowon.com/jimmy/go-common/middleware"
|
"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) {
|
func handler(w http.ResponseWriter, r *http.Request) {
|
||||||
@@ -177,7 +177,7 @@ func handler(w http.ResponseWriter, r *http.Request) {
|
|||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
// 使用自定义默认时区
|
// 使用自定义默认时区
|
||||||
handler := middleware.TimezoneWithDefault(datetime.UTC)(http.HandlerFunc(handler))
|
handler := middleware.TimezoneWithDefault(tools.UTC)(http.HandlerFunc(handler))
|
||||||
http.Handle("/api", handler)
|
http.Handle("/api", handler)
|
||||||
http.ListenAndServe(":8080", nil)
|
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
|
```go
|
||||||
import (
|
import (
|
||||||
"net/http"
|
"net/http"
|
||||||
commonhttp "git.toowon.com/jimmy/go-common/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) {
|
func GetUserList(w http.ResponseWriter, r *http.Request) {
|
||||||
@@ -199,17 +231,17 @@ func GetUserList(w http.ResponseWriter, r *http.Request) {
|
|||||||
timezone := h.GetTimezone()
|
timezone := h.GetTimezone()
|
||||||
|
|
||||||
// 使用时区进行时间处理
|
// 使用时区进行时间处理
|
||||||
now := datetime.Now(timezone)
|
now := tools.Now(timezone)
|
||||||
|
|
||||||
// 查询数据时使用时区
|
// 查询数据时使用时区
|
||||||
startTime := datetime.StartOfDay(now, timezone)
|
startTime := tools.StartOfDay(now, timezone)
|
||||||
endTime := datetime.EndOfDay(now, timezone)
|
endTime := tools.EndOfDay(now, timezone)
|
||||||
|
|
||||||
// 返回数据
|
// 返回数据
|
||||||
h.Success(map[string]interface{}{
|
h.Success(map[string]interface{}{
|
||||||
"timezone": timezone,
|
"timezone": timezone,
|
||||||
"startTime": datetime.FormatDateTime(startTime),
|
"startTime": tools.FormatDateTime(startTime),
|
||||||
"endTime": datetime.FormatDateTime(endTime),
|
"endTime": tools.FormatDateTime(endTime),
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
@@ -658,7 +690,7 @@ import (
|
|||||||
"git.toowon.com/jimmy/go-common/middleware"
|
"git.toowon.com/jimmy/go-common/middleware"
|
||||||
"git.toowon.com/jimmy/go-common/logger"
|
"git.toowon.com/jimmy/go-common/logger"
|
||||||
commonhttp "git.toowon.com/jimmy/go-common/http"
|
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) {
|
func apiHandler(w http.ResponseWriter, r *http.Request) {
|
||||||
@@ -666,12 +698,12 @@ func apiHandler(w http.ResponseWriter, r *http.Request) {
|
|||||||
|
|
||||||
// 从Handler获取时区
|
// 从Handler获取时区
|
||||||
timezone := h.GetTimezone()
|
timezone := h.GetTimezone()
|
||||||
now := datetime.Now(timezone)
|
now := tools.Now(timezone)
|
||||||
|
|
||||||
h.Success(map[string]interface{}{
|
h.Success(map[string]interface{}{
|
||||||
"message": "Hello",
|
"message": "Hello",
|
||||||
"timezone": timezone,
|
"timezone": timezone,
|
||||||
"time": datetime.FormatDateTime(now),
|
"time": tools.FormatDateTime(now),
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -756,7 +788,7 @@ import (
|
|||||||
|
|
||||||
"git.toowon.com/jimmy/go-common/middleware"
|
"git.toowon.com/jimmy/go-common/middleware"
|
||||||
commonhttp "git.toowon.com/jimmy/go-common/http"
|
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) {
|
func apiHandler(w http.ResponseWriter, r *http.Request) {
|
||||||
@@ -764,12 +796,12 @@ func apiHandler(w http.ResponseWriter, r *http.Request) {
|
|||||||
|
|
||||||
// 从Handler获取时区
|
// 从Handler获取时区
|
||||||
timezone := h.GetTimezone()
|
timezone := h.GetTimezone()
|
||||||
now := datetime.Now(timezone)
|
now := tools.Now(timezone)
|
||||||
|
|
||||||
h.Success(map[string]interface{}{
|
h.Success(map[string]interface{}{
|
||||||
"message": "Hello",
|
"message": "Hello",
|
||||||
"timezone": timezone,
|
"timezone": timezone,
|
||||||
"time": datetime.FormatDateTime(now),
|
"time": tools.FormatDateTime(now),
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -89,7 +89,7 @@ err := migration.RunMigrationsFromConfigWithCommand("config.json", "migrations",
|
|||||||
```
|
```
|
||||||
|
|
||||||
**参数说明**:
|
**参数说明**:
|
||||||
- `configFile`: 配置文件路径,空字符串时自动查找(config.json, ../config.json)或使用环境变量 DATABASE_URL
|
- `configFile`: 配置文件路径,空字符串时自动查找(config.json, ../config.json)
|
||||||
- `migrationsDir`: 迁移文件目录,空字符串时使用默认值 "migrations"
|
- `migrationsDir`: 迁移文件目录,空字符串时使用默认值 "migrations"
|
||||||
- `command`: 命令,支持 "up", "down", "status"
|
- `command`: 命令,支持 "up", "down", "status"
|
||||||
|
|
||||||
|
|||||||
179
email/email.go
179
email/email.go
@@ -17,37 +17,43 @@ type Email struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// NewEmail 创建邮件发送器
|
// NewEmail 创建邮件发送器
|
||||||
func NewEmail(cfg *config.EmailConfig) (*Email, error) {
|
func NewEmail(cfg *config.Config) *Email {
|
||||||
if cfg == nil {
|
if cfg == nil || cfg.Email == nil {
|
||||||
|
return &Email{config: nil}
|
||||||
|
}
|
||||||
|
return &Email{config: cfg.Email}
|
||||||
|
}
|
||||||
|
|
||||||
|
// getEmailConfig 获取邮件配置(内部方法)
|
||||||
|
func (e *Email) getEmailConfig() (*config.EmailConfig, error) {
|
||||||
|
if e.config == nil {
|
||||||
return nil, fmt.Errorf("email config is nil")
|
return nil, fmt.Errorf("email config is nil")
|
||||||
}
|
}
|
||||||
|
|
||||||
if cfg.Host == "" {
|
if e.config.Host == "" {
|
||||||
return nil, fmt.Errorf("email host is required")
|
return nil, fmt.Errorf("email host is required")
|
||||||
}
|
}
|
||||||
|
|
||||||
if cfg.Username == "" {
|
if e.config.Username == "" {
|
||||||
return nil, fmt.Errorf("email username is required")
|
return nil, fmt.Errorf("email username is required")
|
||||||
}
|
}
|
||||||
|
|
||||||
if cfg.Password == "" {
|
if e.config.Password == "" {
|
||||||
return nil, fmt.Errorf("email password is required")
|
return nil, fmt.Errorf("email password is required")
|
||||||
}
|
}
|
||||||
|
|
||||||
// 设置默认值
|
// 设置默认值
|
||||||
if cfg.Port == 0 {
|
if e.config.Port == 0 {
|
||||||
cfg.Port = 587
|
e.config.Port = 587
|
||||||
}
|
}
|
||||||
if cfg.From == "" {
|
if e.config.From == "" {
|
||||||
cfg.From = cfg.Username
|
e.config.From = e.config.Username
|
||||||
}
|
}
|
||||||
if cfg.Timeout == 0 {
|
if e.config.Timeout == 0 {
|
||||||
cfg.Timeout = 30
|
e.config.Timeout = 30
|
||||||
}
|
}
|
||||||
|
|
||||||
return &Email{
|
return e.config, nil
|
||||||
config: cfg,
|
|
||||||
}, nil
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Message 邮件消息
|
// Message 邮件消息
|
||||||
@@ -69,66 +75,91 @@ type Message struct {
|
|||||||
|
|
||||||
// HTMLBody HTML正文(可选,如果设置了会优先使用)
|
// HTMLBody HTML正文(可选,如果设置了会优先使用)
|
||||||
HTMLBody string
|
HTMLBody string
|
||||||
|
|
||||||
// Attachments 附件列表(可选)
|
|
||||||
Attachments []Attachment
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Attachment 附件
|
// SendEmail 发送邮件
|
||||||
type Attachment struct {
|
// to: 收件人列表
|
||||||
// Filename 文件名
|
// subject: 邮件主题
|
||||||
Filename string
|
// body: 邮件正文(纯文本)
|
||||||
|
// htmlBody: HTML正文(可选,如果设置了会优先使用)
|
||||||
|
func (e *Email) SendEmail(to []string, subject, body string, htmlBody ...string) error {
|
||||||
|
cfg, err := e.getEmailConfig()
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
// Content 文件内容
|
msg := &Message{
|
||||||
Content []byte
|
To: to,
|
||||||
|
Subject: subject,
|
||||||
|
Body: body,
|
||||||
|
}
|
||||||
|
|
||||||
// ContentType 文件类型(如:application/pdf)
|
if len(htmlBody) > 0 && htmlBody[0] != "" {
|
||||||
ContentType string
|
msg.HTMLBody = htmlBody[0]
|
||||||
|
}
|
||||||
|
|
||||||
|
return e.send(msg, cfg)
|
||||||
}
|
}
|
||||||
|
|
||||||
// SendRaw 发送原始邮件内容
|
// send 发送邮件(内部方法)
|
||||||
// recipients: 收件人列表(To、Cc、Bcc的合并列表)
|
func (e *Email) send(msg *Message, cfg *config.EmailConfig) error {
|
||||||
// body: 完整的邮件内容(MIME格式),由外部构建
|
if msg == nil {
|
||||||
func (e *Email) SendRaw(recipients []string, body []byte) error {
|
return fmt.Errorf("message is nil")
|
||||||
if len(recipients) == 0 {
|
}
|
||||||
|
|
||||||
|
if len(msg.To) == 0 {
|
||||||
return fmt.Errorf("recipients are required")
|
return fmt.Errorf("recipients are required")
|
||||||
}
|
}
|
||||||
|
|
||||||
if len(body) == 0 {
|
if msg.Subject == "" {
|
||||||
return fmt.Errorf("email body is required")
|
return fmt.Errorf("subject is required")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if msg.Body == "" && msg.HTMLBody == "" {
|
||||||
|
return fmt.Errorf("body or HTMLBody is required")
|
||||||
|
}
|
||||||
|
|
||||||
|
// 构建邮件内容
|
||||||
|
emailBody, err := e.buildEmailBody(msg, cfg)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("failed to build email body: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// 合并收件人列表
|
||||||
|
recipients := append(msg.To, msg.Cc...)
|
||||||
|
recipients = append(recipients, msg.Bcc...)
|
||||||
|
|
||||||
// 连接SMTP服务器
|
// 连接SMTP服务器
|
||||||
addr := fmt.Sprintf("%s:%d", e.config.Host, e.config.Port)
|
addr := net.JoinHostPort(cfg.Host, fmt.Sprintf("%d", cfg.Port))
|
||||||
auth := smtp.PlainAuth("", e.config.Username, e.config.Password, e.config.Host)
|
auth := smtp.PlainAuth("", cfg.Username, cfg.Password, cfg.Host)
|
||||||
|
|
||||||
// 创建连接
|
// 创建连接
|
||||||
conn, err := net.DialTimeout("tcp", addr, time.Duration(e.config.Timeout)*time.Second)
|
conn, err := net.DialTimeout("tcp", addr, time.Duration(cfg.Timeout)*time.Second)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("failed to connect to SMTP server: %w", err)
|
return fmt.Errorf("failed to connect to SMTP server: %w", err)
|
||||||
}
|
}
|
||||||
defer conn.Close()
|
defer conn.Close()
|
||||||
|
|
||||||
// 创建SMTP客户端
|
// 创建SMTP客户端
|
||||||
client, err := smtp.NewClient(conn, e.config.Host)
|
client, err := smtp.NewClient(conn, cfg.Host)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("failed to create SMTP client: %w", err)
|
return fmt.Errorf("failed to create SMTP client: %w", err)
|
||||||
}
|
}
|
||||||
defer client.Close()
|
defer client.Close()
|
||||||
|
|
||||||
// TLS/SSL处理
|
// TLS/SSL处理
|
||||||
if e.config.UseSSL {
|
if cfg.UseSSL {
|
||||||
// SSL模式(端口通常是465)
|
// SSL模式(端口通常是465)
|
||||||
tlsConfig := &tls.Config{
|
tlsConfig := &tls.Config{
|
||||||
ServerName: e.config.Host,
|
ServerName: cfg.Host,
|
||||||
}
|
}
|
||||||
if err := client.StartTLS(tlsConfig); err != nil {
|
if err := client.StartTLS(tlsConfig); err != nil {
|
||||||
return fmt.Errorf("failed to start TLS: %w", err)
|
return fmt.Errorf("failed to start TLS: %w", err)
|
||||||
}
|
}
|
||||||
} else if e.config.UseTLS {
|
} else if cfg.UseTLS {
|
||||||
// TLS模式(STARTTLS,端口通常是587)
|
// TLS模式(STARTTLS,端口通常是587)
|
||||||
tlsConfig := &tls.Config{
|
tlsConfig := &tls.Config{
|
||||||
ServerName: e.config.Host,
|
ServerName: cfg.Host,
|
||||||
}
|
}
|
||||||
if err := client.StartTLS(tlsConfig); err != nil {
|
if err := client.StartTLS(tlsConfig); err != nil {
|
||||||
return fmt.Errorf("failed to start TLS: %w", err)
|
return fmt.Errorf("failed to start TLS: %w", err)
|
||||||
@@ -141,7 +172,7 @@ func (e *Email) SendRaw(recipients []string, body []byte) error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// 设置发件人
|
// 设置发件人
|
||||||
if err := client.Mail(e.config.From); err != nil {
|
if err := client.Mail(cfg.From); err != nil {
|
||||||
return fmt.Errorf("failed to set sender: %w", err)
|
return fmt.Errorf("failed to set sender: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -158,7 +189,7 @@ func (e *Email) SendRaw(recipients []string, body []byte) error {
|
|||||||
return fmt.Errorf("failed to get data writer: %w", err)
|
return fmt.Errorf("failed to get data writer: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
_, err = writer.Write(body)
|
_, err = writer.Write(emailBody)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
writer.Close()
|
writer.Close()
|
||||||
return fmt.Errorf("failed to write email body: %w", err)
|
return fmt.Errorf("failed to write email body: %w", err)
|
||||||
@@ -177,47 +208,14 @@ func (e *Email) SendRaw(recipients []string, body []byte) error {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// Send 发送邮件(使用Message结构,内部会构建邮件内容)
|
|
||||||
// 注意:如果需要完全控制邮件内容,请使用SendRaw方法
|
|
||||||
func (e *Email) Send(msg *Message) error {
|
|
||||||
if msg == nil {
|
|
||||||
return fmt.Errorf("message is nil")
|
|
||||||
}
|
|
||||||
|
|
||||||
if len(msg.To) == 0 {
|
|
||||||
return fmt.Errorf("recipients are required")
|
|
||||||
}
|
|
||||||
|
|
||||||
if msg.Subject == "" {
|
|
||||||
return fmt.Errorf("subject is required")
|
|
||||||
}
|
|
||||||
|
|
||||||
if msg.Body == "" && msg.HTMLBody == "" {
|
|
||||||
return fmt.Errorf("body or HTMLBody is required")
|
|
||||||
}
|
|
||||||
|
|
||||||
// 构建邮件内容
|
|
||||||
emailBody, err := e.buildEmailBody(msg)
|
|
||||||
if err != nil {
|
|
||||||
return fmt.Errorf("failed to build email body: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
// 合并收件人列表
|
|
||||||
recipients := append(msg.To, msg.Cc...)
|
|
||||||
recipients = append(recipients, msg.Bcc...)
|
|
||||||
|
|
||||||
// 使用SendRaw发送
|
|
||||||
return e.SendRaw(recipients, emailBody)
|
|
||||||
}
|
|
||||||
|
|
||||||
// buildEmailBody 构建邮件内容
|
// buildEmailBody 构建邮件内容
|
||||||
func (e *Email) buildEmailBody(msg *Message) ([]byte, error) {
|
func (e *Email) buildEmailBody(msg *Message, cfg *config.EmailConfig) ([]byte, error) {
|
||||||
var buf bytes.Buffer
|
var buf bytes.Buffer
|
||||||
|
|
||||||
// 邮件头
|
// 邮件头
|
||||||
from := e.config.From
|
from := cfg.From
|
||||||
if e.config.FromName != "" {
|
if cfg.FromName != "" {
|
||||||
from = fmt.Sprintf("%s <%s>", e.config.FromName, e.config.From)
|
from = fmt.Sprintf("%s <%s>", cfg.FromName, cfg.From)
|
||||||
}
|
}
|
||||||
buf.WriteString(fmt.Sprintf("From: %s\r\n", from))
|
buf.WriteString(fmt.Sprintf("From: %s\r\n", from))
|
||||||
|
|
||||||
@@ -281,26 +279,3 @@ func joinEmails(emails []string) string {
|
|||||||
return result
|
return result
|
||||||
}
|
}
|
||||||
|
|
||||||
// SendSimple 发送简单邮件(便捷方法)
|
|
||||||
// to: 收件人
|
|
||||||
// subject: 主题
|
|
||||||
// body: 正文
|
|
||||||
func (e *Email) SendSimple(to []string, subject, body string) error {
|
|
||||||
return e.Send(&Message{
|
|
||||||
To: to,
|
|
||||||
Subject: subject,
|
|
||||||
Body: body,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
// SendHTML 发送HTML邮件(便捷方法)
|
|
||||||
// to: 收件人
|
|
||||||
// subject: 主题
|
|
||||||
// htmlBody: HTML正文
|
|
||||||
func (e *Email) SendHTML(to []string, subject, htmlBody string) error {
|
|
||||||
return e.Send(&Message{
|
|
||||||
To: to,
|
|
||||||
Subject: subject,
|
|
||||||
HTMLBody: htmlBody,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -1,56 +0,0 @@
|
|||||||
package main
|
|
||||||
|
|
||||||
import (
|
|
||||||
"fmt"
|
|
||||||
"log"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"git.toowon.com/jimmy/go-common/datetime"
|
|
||||||
)
|
|
||||||
|
|
||||||
func main() {
|
|
||||||
// 设置默认时区
|
|
||||||
err := datetime.SetDefaultTimeZone(datetime.AsiaShanghai)
|
|
||||||
if err != nil {
|
|
||||||
log.Fatal(err)
|
|
||||||
}
|
|
||||||
|
|
||||||
// 获取当前时间
|
|
||||||
now := datetime.Now()
|
|
||||||
fmt.Printf("Current time: %s\n", datetime.FormatDateTime(now))
|
|
||||||
|
|
||||||
// 解析时间字符串
|
|
||||||
t, err := datetime.ParseDateTime("2024-01-01 12:00:00")
|
|
||||||
if err != nil {
|
|
||||||
log.Fatal(err)
|
|
||||||
}
|
|
||||||
fmt.Printf("Parsed time: %s\n", datetime.FormatDateTime(t))
|
|
||||||
|
|
||||||
// 时区转换
|
|
||||||
t2, err := datetime.ToTimezone(t, datetime.AmericaNewYork)
|
|
||||||
if err != nil {
|
|
||||||
log.Fatal(err)
|
|
||||||
}
|
|
||||||
fmt.Printf("Time in New York: %s\n", datetime.FormatDateTime(t2))
|
|
||||||
|
|
||||||
// Unix时间戳
|
|
||||||
unix := datetime.ToUnix(now)
|
|
||||||
fmt.Printf("Unix timestamp: %d\n", unix)
|
|
||||||
t3 := datetime.FromUnix(unix)
|
|
||||||
fmt.Printf("From Unix: %s\n", datetime.FormatDateTime(t3))
|
|
||||||
|
|
||||||
// 时间计算
|
|
||||||
tomorrow := datetime.AddDays(now, 1)
|
|
||||||
fmt.Printf("Tomorrow: %s\n", datetime.FormatDate(tomorrow))
|
|
||||||
|
|
||||||
// 时间范围
|
|
||||||
startOfDay := datetime.StartOfDay(now)
|
|
||||||
endOfDay := datetime.EndOfDay(now)
|
|
||||||
fmt.Printf("Start of day: %s\n", datetime.FormatDateTime(startOfDay))
|
|
||||||
fmt.Printf("End of day: %s\n", datetime.FormatDateTime(endOfDay))
|
|
||||||
|
|
||||||
// 时间差
|
|
||||||
diff := datetime.DiffDays(now, tomorrow)
|
|
||||||
fmt.Printf("Days difference: %d\n", diff)
|
|
||||||
}
|
|
||||||
|
|
||||||
@@ -1,74 +0,0 @@
|
|||||||
package main
|
|
||||||
|
|
||||||
import (
|
|
||||||
"fmt"
|
|
||||||
"log"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"git.toowon.com/jimmy/go-common/datetime"
|
|
||||||
)
|
|
||||||
|
|
||||||
func main() {
|
|
||||||
// 示例1:将当前时间转换为UTC
|
|
||||||
fmt.Println("=== Example 1: Convert Current Time to UTC ===")
|
|
||||||
now := time.Now()
|
|
||||||
utcTime := datetime.ToUTC(now)
|
|
||||||
fmt.Printf("Local time: %s\n", datetime.FormatDateTime(now))
|
|
||||||
fmt.Printf("UTC time: %s\n", datetime.FormatDateTime(utcTime))
|
|
||||||
|
|
||||||
// 示例2:从指定时区转换为UTC
|
|
||||||
fmt.Println("\n=== Example 2: Convert from Specific Timezone to UTC ===")
|
|
||||||
// 解析上海时区的时间
|
|
||||||
shanghaiTime, err := datetime.ParseDateTime("2024-01-01 12:00:00", datetime.AsiaShanghai)
|
|
||||||
if err != nil {
|
|
||||||
log.Fatal(err)
|
|
||||||
}
|
|
||||||
fmt.Printf("Shanghai time: %s\n", datetime.FormatDateTime(shanghaiTime, datetime.AsiaShanghai))
|
|
||||||
|
|
||||||
// 转换为UTC
|
|
||||||
utcTime2, err := datetime.ToUTCFromTimezone(shanghaiTime, datetime.AsiaShanghai)
|
|
||||||
if err != nil {
|
|
||||||
log.Fatal(err)
|
|
||||||
}
|
|
||||||
fmt.Printf("UTC time: %s\n", datetime.FormatDateTime(utcTime2, datetime.UTC))
|
|
||||||
|
|
||||||
// 示例3:解析时间字符串并直接转换为UTC
|
|
||||||
fmt.Println("\n=== Example 3: Parse and Convert to UTC ===")
|
|
||||||
utcTime3, err := datetime.ParseDateTimeToUTC("2024-01-01 12:00:00", datetime.AsiaShanghai)
|
|
||||||
if err != nil {
|
|
||||||
log.Fatal(err)
|
|
||||||
}
|
|
||||||
fmt.Printf("Parsed from Shanghai timezone, UTC: %s\n", datetime.FormatDateTime(utcTime3, datetime.UTC))
|
|
||||||
|
|
||||||
// 示例4:解析日期并转换为UTC
|
|
||||||
fmt.Println("\n=== Example 4: Parse Date and Convert to UTC ===")
|
|
||||||
utcTime4, err := datetime.ParseDateToUTC("2024-01-01", datetime.AsiaShanghai)
|
|
||||||
if err != nil {
|
|
||||||
log.Fatal(err)
|
|
||||||
}
|
|
||||||
fmt.Printf("Date parsed from Shanghai timezone, UTC: %s\n", datetime.FormatDateTime(utcTime4, datetime.UTC))
|
|
||||||
|
|
||||||
// 示例5:数据库存储场景
|
|
||||||
fmt.Println("\n=== Example 5: Database Storage Scenario ===")
|
|
||||||
// 从请求中获取时间(假设是上海时区)
|
|
||||||
requestTimeStr := "2024-01-01 12:00:00"
|
|
||||||
requestTimezone := datetime.AsiaShanghai
|
|
||||||
|
|
||||||
// 转换为UTC时间(用于数据库存储)
|
|
||||||
dbTime, err := datetime.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))
|
|
||||||
|
|
||||||
// 从数据库读取UTC时间,转换为用户时区显示
|
|
||||||
userTimezone := datetime.AsiaShanghai
|
|
||||||
displayTime, err := datetime.ToTimezone(dbTime, userTimezone)
|
|
||||||
if err != nil {
|
|
||||||
log.Fatal(err)
|
|
||||||
}
|
|
||||||
fmt.Printf("Display time (Shanghai): %s\n", datetime.FormatDateTime(displayTime, userTimezone))
|
|
||||||
}
|
|
||||||
|
|
||||||
@@ -7,7 +7,6 @@ import (
|
|||||||
"time"
|
"time"
|
||||||
|
|
||||||
"git.toowon.com/jimmy/go-common/factory"
|
"git.toowon.com/jimmy/go-common/factory"
|
||||||
commonhttp "git.toowon.com/jimmy/go-common/http"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
// 示例:Factory黑盒模式 - 最简化的使用方式
|
// 示例:Factory黑盒模式 - 最简化的使用方式
|
||||||
@@ -44,8 +43,6 @@ func main() {
|
|||||||
|
|
||||||
// 用户列表
|
// 用户列表
|
||||||
func handleUsers(w http.ResponseWriter, r *http.Request) {
|
func handleUsers(w http.ResponseWriter, r *http.Request) {
|
||||||
h := commonhttp.NewHandler(w, r)
|
|
||||||
|
|
||||||
// 创建工厂(在处理器中也可以复用)
|
// 创建工厂(在处理器中也可以复用)
|
||||||
fac, _ := factory.NewFactoryFromFile("config.json")
|
fac, _ := factory.NewFactoryFromFile("config.json")
|
||||||
ctx := context.Background()
|
ctx := context.Background()
|
||||||
@@ -59,7 +56,7 @@ func handleUsers(w http.ResponseWriter, r *http.Request) {
|
|||||||
cacheKey := "users:list"
|
cacheKey := "users:list"
|
||||||
cached, _ := fac.RedisGet(ctx, cacheKey)
|
cached, _ := fac.RedisGet(ctx, cacheKey)
|
||||||
if cached != "" {
|
if cached != "" {
|
||||||
h.Success(cached)
|
fac.Success(w, cached)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -72,12 +69,11 @@ func handleUsers(w http.ResponseWriter, r *http.Request) {
|
|||||||
// 4. 缓存结果
|
// 4. 缓存结果
|
||||||
fac.RedisSet(ctx, cacheKey, users, 5*time.Minute)
|
fac.RedisSet(ctx, cacheKey, users, 5*time.Minute)
|
||||||
|
|
||||||
h.Success(users)
|
fac.Success(w, users)
|
||||||
}
|
}
|
||||||
|
|
||||||
// 文件上传
|
// 文件上传
|
||||||
func handleUpload(w http.ResponseWriter, r *http.Request) {
|
func handleUpload(w http.ResponseWriter, r *http.Request) {
|
||||||
h := commonhttp.NewHandler(w, r)
|
|
||||||
fac, _ := factory.NewFactoryFromFile("config.json")
|
fac, _ := factory.NewFactoryFromFile("config.json")
|
||||||
ctx := context.Background()
|
ctx := context.Background()
|
||||||
|
|
||||||
@@ -85,7 +81,7 @@ func handleUpload(w http.ResponseWriter, r *http.Request) {
|
|||||||
file, header, err := r.FormFile("file")
|
file, header, err := r.FormFile("file")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
fac.LogError("文件上传失败: %v", err)
|
fac.LogError("文件上传失败: %v", err)
|
||||||
h.Error(400, "文件上传失败")
|
fac.Error(w, 400, "文件上传失败")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
defer file.Close()
|
defer file.Close()
|
||||||
@@ -95,7 +91,7 @@ func handleUpload(w http.ResponseWriter, r *http.Request) {
|
|||||||
url, err := fac.UploadFile(ctx, objectKey, file, header.Header.Get("Content-Type"))
|
url, err := fac.UploadFile(ctx, objectKey, file, header.Header.Get("Content-Type"))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
fac.LogError("文件上传到存储失败: %v", err)
|
fac.LogError("文件上传到存储失败: %v", err)
|
||||||
h.Error(500, "文件上传失败")
|
fac.Error(w, 500, "文件上传失败")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -106,7 +102,7 @@ func handleUpload(w http.ResponseWriter, r *http.Request) {
|
|||||||
"url": url,
|
"url": url,
|
||||||
}, "文件上传成功")
|
}, "文件上传成功")
|
||||||
|
|
||||||
h.Success(map[string]interface{}{
|
fac.Success(w, map[string]interface{}{
|
||||||
"url": url,
|
"url": url,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@@ -122,16 +118,14 @@ func authMiddleware(next http.Handler) http.Handler {
|
|||||||
// 获取token
|
// 获取token
|
||||||
token := r.Header.Get("Authorization")
|
token := r.Header.Get("Authorization")
|
||||||
if token == "" {
|
if token == "" {
|
||||||
h := commonhttp.NewHandler(w, r)
|
fac.Error(w, 401, "未授权")
|
||||||
h.Error(401, "未授权")
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// 从Redis验证token(黑盒方法)
|
// 从Redis验证token(黑盒方法)
|
||||||
userID, err := fac.RedisGet(ctx, "token:"+token)
|
userID, err := fac.RedisGet(ctx, "token:"+token)
|
||||||
if err != nil || userID == "" {
|
if err != nil || userID == "" {
|
||||||
h := commonhttp.NewHandler(w, r)
|
fac.Error(w, 401, "token无效")
|
||||||
h.Error(401, "token无效")
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -4,7 +4,9 @@ import (
|
|||||||
"log"
|
"log"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
|
||||||
|
"git.toowon.com/jimmy/go-common/factory"
|
||||||
commonhttp "git.toowon.com/jimmy/go-common/http"
|
commonhttp "git.toowon.com/jimmy/go-common/http"
|
||||||
|
"git.toowon.com/jimmy/go-common/tools"
|
||||||
)
|
)
|
||||||
|
|
||||||
// 用户结构
|
// 用户结构
|
||||||
@@ -14,15 +16,17 @@ type User struct {
|
|||||||
Email string `json:"email"`
|
Email string `json:"email"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// 获取用户列表(使用Handler黑盒模式)
|
// 获取用户列表(使用公共方法和factory)
|
||||||
func GetUserList(h *commonhttp.Handler) {
|
func GetUserList(w http.ResponseWriter, r *http.Request) {
|
||||||
// 获取分页参数(简洁方式)
|
fac, _ := factory.NewFactoryFromFile("config.json")
|
||||||
pagination := h.ParsePaginationRequest()
|
|
||||||
page := pagination.GetPage()
|
|
||||||
pageSize := pagination.GetSize()
|
|
||||||
|
|
||||||
// 获取查询参数(简洁方式)
|
// 获取分页参数(使用公共方法)
|
||||||
_ = h.GetQuery("keyword", "") // 示例:获取查询参数
|
pagination := commonhttp.ParsePaginationRequest(r)
|
||||||
|
page := pagination.GetPage()
|
||||||
|
pageSize := pagination.GetPageSize()
|
||||||
|
|
||||||
|
// 获取查询参数(使用公共方法)
|
||||||
|
_ = r.URL.Query().Get("keyword") // 示例:获取查询参数
|
||||||
|
|
||||||
// 模拟查询数据
|
// 模拟查询数据
|
||||||
users := []User{
|
users := []User{
|
||||||
@@ -31,26 +35,28 @@ func GetUserList(h *commonhttp.Handler) {
|
|||||||
}
|
}
|
||||||
total := int64(100)
|
total := int64(100)
|
||||||
|
|
||||||
// 返回分页响应(简洁方式)
|
// 返回分页响应(使用factory方法)
|
||||||
h.SuccessPage(users, total, page, pageSize)
|
fac.SuccessPage(w, users, total, page, pageSize)
|
||||||
}
|
}
|
||||||
|
|
||||||
// 创建用户(使用Handler黑盒模式)
|
// 创建用户(使用公共方法和factory)
|
||||||
func CreateUser(h *commonhttp.Handler) {
|
func CreateUser(w http.ResponseWriter, r *http.Request) {
|
||||||
// 解析请求体(简洁方式)
|
fac, _ := factory.NewFactoryFromFile("config.json")
|
||||||
|
|
||||||
|
// 解析请求体(使用公共方法)
|
||||||
var req struct {
|
var req struct {
|
||||||
Name string `json:"name"`
|
Name string `json:"name"`
|
||||||
Email string `json:"email"`
|
Email string `json:"email"`
|
||||||
}
|
}
|
||||||
|
|
||||||
if err := h.ParseJSON(&req); err != nil {
|
if err := commonhttp.ParseJSON(r, &req); err != nil {
|
||||||
h.WriteJSON(http.StatusBadRequest, 400, "请求参数解析失败", nil)
|
commonhttp.WriteJSON(w, http.StatusBadRequest, 400, "请求参数解析失败", nil)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// 参数验证
|
// 参数验证
|
||||||
if req.Name == "" {
|
if req.Name == "" {
|
||||||
h.Error(1001, "用户名不能为空")
|
fac.Error(w, 1001, "用户名不能为空")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -61,49 +67,46 @@ func CreateUser(h *commonhttp.Handler) {
|
|||||||
Email: req.Email,
|
Email: req.Email,
|
||||||
}
|
}
|
||||||
|
|
||||||
// 返回成功响应(简洁方式)
|
// 返回成功响应(使用factory方法,统一Success方法)
|
||||||
h.SuccessWithMessage("创建成功", user)
|
fac.Success(w, user, "创建成功")
|
||||||
}
|
}
|
||||||
|
|
||||||
// 获取用户详情(使用Handler黑盒模式)
|
// 获取用户详情(使用公共方法和factory)
|
||||||
func GetUser(h *commonhttp.Handler) {
|
func GetUser(w http.ResponseWriter, r *http.Request) {
|
||||||
// 获取查询参数(简洁方式)
|
fac, _ := factory.NewFactoryFromFile("config.json")
|
||||||
id := h.GetQueryInt64("id", 0)
|
|
||||||
|
// 获取查询参数(使用公共方法)
|
||||||
|
id := tools.ConvertInt64(r.URL.Query().Get("id"), 0)
|
||||||
|
|
||||||
if id == 0 {
|
if id == 0 {
|
||||||
h.WriteJSON(http.StatusBadRequest, 400, "用户ID不能为空", nil)
|
commonhttp.WriteJSON(w, http.StatusBadRequest, 400, "用户ID不能为空", nil)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// 模拟查询用户
|
// 模拟查询用户
|
||||||
if id == 1 {
|
if id == 1 {
|
||||||
user := User{ID: 1, Name: "User1", Email: "user1@example.com"}
|
user := User{ID: 1, Name: "User1", Email: "user1@example.com"}
|
||||||
h.Success(user)
|
fac.Success(w, user)
|
||||||
} else {
|
} else {
|
||||||
h.Error(1002, "用户不存在")
|
fac.Error(w, 1002, "用户不存在")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
// 方式1:使用HandleFunc包装器(推荐,最简洁)
|
// 使用标准http.HandleFunc
|
||||||
http.HandleFunc("/users", commonhttp.HandleFunc(func(h *commonhttp.Handler) {
|
http.HandleFunc("/users", func(w http.ResponseWriter, r *http.Request) {
|
||||||
switch h.Request().Method {
|
switch r.Method {
|
||||||
case http.MethodGet:
|
case http.MethodGet:
|
||||||
GetUserList(h)
|
GetUserList(w, r)
|
||||||
case http.MethodPost:
|
case http.MethodPost:
|
||||||
CreateUser(h)
|
CreateUser(w, r)
|
||||||
default:
|
default:
|
||||||
h.WriteJSON(http.StatusMethodNotAllowed, 405, "方法不支持", nil)
|
commonhttp.WriteJSON(w, http.StatusMethodNotAllowed, 405, "方法不支持", nil)
|
||||||
}
|
}
|
||||||
}))
|
|
||||||
|
|
||||||
// 方式2:手动创建Handler(需要更多控制时)
|
|
||||||
http.HandleFunc("/user", func(w http.ResponseWriter, r *http.Request) {
|
|
||||||
h := commonhttp.NewHandler(w, r)
|
|
||||||
GetUser(h)
|
|
||||||
})
|
})
|
||||||
|
|
||||||
|
http.HandleFunc("/user", GetUser)
|
||||||
|
|
||||||
log.Println("Server started on :8080")
|
log.Println("Server started on :8080")
|
||||||
log.Fatal(http.ListenAndServe(":8080", nil))
|
log.Fatal(http.ListenAndServe(":8080", nil))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -4,13 +4,14 @@ import (
|
|||||||
"log"
|
"log"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
|
||||||
|
"git.toowon.com/jimmy/go-common/factory"
|
||||||
commonhttp "git.toowon.com/jimmy/go-common/http"
|
commonhttp "git.toowon.com/jimmy/go-common/http"
|
||||||
)
|
)
|
||||||
|
|
||||||
// ListUserRequest 用户列表请求(包含分页字段)
|
// ListUserRequest 用户列表请求(包含分页字段)
|
||||||
type ListUserRequest struct {
|
type ListUserRequest struct {
|
||||||
Keyword string `json:"keyword"`
|
Keyword string `json:"keyword"`
|
||||||
commonhttp.PaginationRequest // 嵌入分页请求结构
|
commonhttp.PaginationRequest // 嵌入分页请求结构
|
||||||
}
|
}
|
||||||
|
|
||||||
// User 用户结构
|
// User 用户结构
|
||||||
@@ -20,27 +21,28 @@ type User struct {
|
|||||||
Email string `json:"email"`
|
Email string `json:"email"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// 获取用户列表(使用Handler和PaginationRequest)
|
// 获取用户列表(使用公共方法和factory)
|
||||||
func GetUserList(h *commonhttp.Handler) {
|
func GetUserList(w http.ResponseWriter, r *http.Request) {
|
||||||
|
fac, _ := factory.NewFactoryFromFile("config.json")
|
||||||
var req ListUserRequest
|
var req ListUserRequest
|
||||||
|
|
||||||
// 方式1:从JSON请求体解析(分页字段会自动解析)
|
// 方式1:从JSON请求体解析(分页字段会自动解析)
|
||||||
if h.Request().Method == http.MethodPost {
|
if r.Method == http.MethodPost {
|
||||||
if err := h.ParseJSON(&req); err != nil {
|
if err := commonhttp.ParseJSON(r, &req); err != nil {
|
||||||
h.WriteJSON(http.StatusBadRequest, 400, "请求参数解析失败", nil)
|
commonhttp.WriteJSON(w, http.StatusBadRequest, 400, "请求参数解析失败", nil)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
// 方式2:从查询参数解析分页
|
// 方式2:从查询参数解析分页
|
||||||
pagination := h.ParsePaginationRequest()
|
pagination := commonhttp.ParsePaginationRequest(r)
|
||||||
req.PaginationRequest = *pagination
|
req.PaginationRequest = *pagination
|
||||||
req.Keyword = h.GetQuery("keyword", "")
|
req.Keyword = r.URL.Query().Get("keyword")
|
||||||
}
|
}
|
||||||
|
|
||||||
// 使用分页方法
|
// 使用分页方法
|
||||||
page := req.GetPage() // 获取页码(默认1)
|
page := req.GetPage() // 获取页码(默认1)
|
||||||
size := req.GetSize() // 获取每页数量(默认20,最大100)
|
pageSize := req.GetPageSize() // 获取每页数量(默认20,最大100)
|
||||||
_ = req.GetOffset() // 计算偏移量
|
_ = req.GetOffset() // 计算偏移量
|
||||||
|
|
||||||
// 模拟查询数据
|
// 模拟查询数据
|
||||||
users := []User{
|
users := []User{
|
||||||
@@ -49,12 +51,12 @@ func GetUserList(h *commonhttp.Handler) {
|
|||||||
}
|
}
|
||||||
total := int64(100)
|
total := int64(100)
|
||||||
|
|
||||||
// 返回分页响应
|
// 返回分页响应(使用factory方法)
|
||||||
h.SuccessPage(users, total, page, size)
|
fac.SuccessPage(w, users, total, page, pageSize)
|
||||||
}
|
}
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
http.HandleFunc("/users", commonhttp.HandleFunc(GetUserList))
|
http.HandleFunc("/users", GetUserList)
|
||||||
|
|
||||||
log.Println("Server started on :8080")
|
log.Println("Server started on :8080")
|
||||||
log.Fatal(http.ListenAndServe(":8080", nil))
|
log.Fatal(http.ListenAndServe(":8080", nil))
|
||||||
|
|||||||
101
examples/i18n_example.go
Normal file
101
examples/i18n_example.go
Normal file
@@ -0,0 +1,101 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"log"
|
||||||
|
|
||||||
|
"git.toowon.com/jimmy/go-common/factory"
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
// 创建工厂实例
|
||||||
|
fac, err := factory.NewFactoryFromFile("config.json")
|
||||||
|
if err != nil {
|
||||||
|
log.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ====== 方式1:从目录加载多个语言文件(推荐) ======
|
||||||
|
// 目录结构:
|
||||||
|
// locales/
|
||||||
|
// zh-CN.json
|
||||||
|
// en-US.json
|
||||||
|
// ja-JP.json
|
||||||
|
|
||||||
|
fac.InitI18n("zh-CN") // 设置默认语言为中文
|
||||||
|
if err := fac.LoadI18nFromDir("locales"); err != nil {
|
||||||
|
log.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// 使用示例
|
||||||
|
fmt.Println("=== 示例1:简单消息 ===")
|
||||||
|
msg1 := fac.GetMessage("zh-CN", "user.not_found")
|
||||||
|
fmt.Printf("中文: %s\n", msg1)
|
||||||
|
|
||||||
|
msg2 := fac.GetMessage("en-US", "user.not_found")
|
||||||
|
fmt.Printf("英文: %s\n", msg2)
|
||||||
|
|
||||||
|
// ====== 方式2:从单个文件加载 ======
|
||||||
|
fmt.Println("\n=== 示例2:从单个文件加载 ===")
|
||||||
|
fac2, _ := factory.NewFactoryFromFile("config.json")
|
||||||
|
fac2.InitI18n("zh-CN")
|
||||||
|
fac2.LoadI18nFromFile("locales/zh-CN.json", "zh-CN")
|
||||||
|
fac2.LoadI18nFromFile("locales/en-US.json", "en-US")
|
||||||
|
|
||||||
|
msg3 := fac2.GetMessage("zh-CN", "user.login_success")
|
||||||
|
fmt.Printf("中文: %s\n", msg3)
|
||||||
|
|
||||||
|
// ====== 示例3:带参数的消息 ======
|
||||||
|
fmt.Println("\n=== 示例3:带参数的消息 ===")
|
||||||
|
// 如果消息内容是 "欢迎,%s",可以使用参数
|
||||||
|
msg4 := fac.GetMessage("zh-CN", "user.welcome", "Alice")
|
||||||
|
fmt.Printf("中文: %s\n", msg4)
|
||||||
|
|
||||||
|
msg5 := fac.GetMessage("en-US", "user.welcome", "Alice")
|
||||||
|
fmt.Printf("英文: %s\n", msg5)
|
||||||
|
|
||||||
|
// ====== 示例4:语言回退机制 ======
|
||||||
|
fmt.Println("\n=== 示例4:语言回退机制 ===")
|
||||||
|
// 如果请求的语言不存在,会使用默认语言
|
||||||
|
msg6 := fac.GetMessage("fr-FR", "user.not_found") // fr-FR 不存在,使用默认语言 zh-CN
|
||||||
|
fmt.Printf("法语(不存在,回退到默认语言): %s\n", msg6)
|
||||||
|
|
||||||
|
// ====== 示例5:高级功能 ======
|
||||||
|
fmt.Println("\n=== 示例5:高级功能 ===")
|
||||||
|
i18n, _ := fac.GetI18n()
|
||||||
|
langs := i18n.GetSupportedLangs()
|
||||||
|
fmt.Printf("支持的语言: %v\n", langs)
|
||||||
|
|
||||||
|
hasLang := i18n.HasLang("en-US")
|
||||||
|
fmt.Printf("是否支持英文: %v\n", hasLang)
|
||||||
|
|
||||||
|
// ====== 示例6:在HTTP处理中使用 ======
|
||||||
|
fmt.Println("\n=== 示例6:在HTTP处理中使用 ===")
|
||||||
|
// 在实际HTTP处理中,可以从请求头获取语言
|
||||||
|
// lang := r.Header.Get("Accept-Language") // 例如: "zh-CN,en-US;q=0.9"
|
||||||
|
// 简化示例,假设从请求中获取到语言代码
|
||||||
|
userLang := "zh-CN"
|
||||||
|
errorMsg := fac.GetMessage(userLang, "user.not_found")
|
||||||
|
fmt.Printf("错误消息: %s\n", errorMsg)
|
||||||
|
|
||||||
|
successMsg := fac.GetMessage(userLang, "user.login_success")
|
||||||
|
fmt.Printf("成功消息: %s\n", successMsg)
|
||||||
|
|
||||||
|
// ====== 示例7:通过错误码直接返回国际化消息(推荐) ======
|
||||||
|
fmt.Println("\n=== 示例7:通过错误码直接返回国际化消息 ===")
|
||||||
|
// 在实际HTTP处理中,Error 方法会自动识别消息代码并返回国际化消息
|
||||||
|
// 需要确保使用了 middleware.Language 中间件(factory.GetMiddlewareChain() 已包含)
|
||||||
|
//
|
||||||
|
// 示例代码(在HTTP handler中):
|
||||||
|
// func handleGetUser(w http.ResponseWriter, r *http.Request) {
|
||||||
|
// fac, _ := factory.NewFactoryFromFile("config.json")
|
||||||
|
//
|
||||||
|
// // 如果用户不存在,直接传入消息代码,会自动获取国际化消息
|
||||||
|
// fac.Error(w, r, 404, "user.not_found")
|
||||||
|
// // 自动从context获取语言(由middleware.Language设置),返回对应语言的错误消息
|
||||||
|
// // 返回: {"code": 404, "message": "用户不存在", "message_code": "user.not_found"}
|
||||||
|
// }
|
||||||
|
//
|
||||||
|
// 如果请求头是 Accept-Language: zh-CN,返回: {"code": 404, "message": "用户不存在", "message_code": "user.not_found"}
|
||||||
|
// 如果请求头是 Accept-Language: en-US,返回: {"code": 404, "message": "User not found", "message_code": "user.not_found"}
|
||||||
|
fmt.Println("Error 方法会自动识别消息代码并返回国际化消息和消息代码")
|
||||||
|
}
|
||||||
38
examples/locales/en-US.json
Normal file
38
examples/locales/en-US.json
Normal file
@@ -0,0 +1,38 @@
|
|||||||
|
{
|
||||||
|
"user.not_found": {
|
||||||
|
"code": 100002,
|
||||||
|
"message": "User not found"
|
||||||
|
},
|
||||||
|
"user.login_success": {
|
||||||
|
"code": 0,
|
||||||
|
"message": "Login successful"
|
||||||
|
},
|
||||||
|
"user.welcome": {
|
||||||
|
"code": 0,
|
||||||
|
"message": "Welcome, %s"
|
||||||
|
},
|
||||||
|
"user.logout": {
|
||||||
|
"code": 0,
|
||||||
|
"message": "Logout"
|
||||||
|
},
|
||||||
|
"error.invalid_params": {
|
||||||
|
"code": 100001,
|
||||||
|
"message": "Invalid parameters"
|
||||||
|
},
|
||||||
|
"error.server_error": {
|
||||||
|
"code": 100003,
|
||||||
|
"message": "Server error"
|
||||||
|
},
|
||||||
|
"order.created": {
|
||||||
|
"code": 0,
|
||||||
|
"message": "Order created successfully"
|
||||||
|
},
|
||||||
|
"order.paid": {
|
||||||
|
"code": 0,
|
||||||
|
"message": "Order paid successfully"
|
||||||
|
},
|
||||||
|
"message.count": {
|
||||||
|
"code": 0,
|
||||||
|
"message": "You have %d new messages"
|
||||||
|
}
|
||||||
|
}
|
||||||
38
examples/locales/zh-CN.json
Normal file
38
examples/locales/zh-CN.json
Normal file
@@ -0,0 +1,38 @@
|
|||||||
|
{
|
||||||
|
"user.not_found": {
|
||||||
|
"code": 100002,
|
||||||
|
"message": "用户不存在"
|
||||||
|
},
|
||||||
|
"user.login_success": {
|
||||||
|
"code": 0,
|
||||||
|
"message": "登录成功"
|
||||||
|
},
|
||||||
|
"user.welcome": {
|
||||||
|
"code": 0,
|
||||||
|
"message": "欢迎,%s"
|
||||||
|
},
|
||||||
|
"user.logout": {
|
||||||
|
"code": 0,
|
||||||
|
"message": "退出登录"
|
||||||
|
},
|
||||||
|
"error.invalid_params": {
|
||||||
|
"code": 100001,
|
||||||
|
"message": "参数无效"
|
||||||
|
},
|
||||||
|
"error.server_error": {
|
||||||
|
"code": 100003,
|
||||||
|
"message": "服务器错误"
|
||||||
|
},
|
||||||
|
"order.created": {
|
||||||
|
"code": 0,
|
||||||
|
"message": "订单创建成功"
|
||||||
|
},
|
||||||
|
"order.paid": {
|
||||||
|
"code": 0,
|
||||||
|
"message": "订单支付成功"
|
||||||
|
},
|
||||||
|
"message.count": {
|
||||||
|
"code": 0,
|
||||||
|
"message": "您有 %d 条新消息"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -21,13 +21,11 @@ func main() {
|
|||||||
|
|
||||||
// 定义API处理器
|
// 定义API处理器
|
||||||
http.Handle("/api/hello", chain.ThenFunc(func(w http.ResponseWriter, r *http.Request) {
|
http.Handle("/api/hello", chain.ThenFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
h := commonhttp.NewHandler(w, r)
|
// 获取时区(使用公共方法)
|
||||||
|
timezone := commonhttp.GetTimezone(r)
|
||||||
|
|
||||||
// 获取时区
|
// 返回响应(使用公共方法)
|
||||||
timezone := h.GetTimezone()
|
commonhttp.Success(w, map[string]interface{}{
|
||||||
|
|
||||||
// 返回响应
|
|
||||||
h.Success(map[string]interface{}{
|
|
||||||
"message": "Hello, World!",
|
"message": "Hello, World!",
|
||||||
"timezone": timezone,
|
"timezone": timezone,
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -110,10 +110,14 @@ func main() {
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
### 方式2:环境变量(Docker友好)
|
### 方式2:使用配置文件(推荐)
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
DATABASE_URL="mysql://root:password@localhost:3306/mydb" go run migrate.go up
|
# 使用默认配置文件 config.json
|
||||||
|
go run migrate.go up
|
||||||
|
|
||||||
|
# 或指定配置文件路径
|
||||||
|
go run migrate.go up -config /path/to/config.json
|
||||||
```
|
```
|
||||||
|
|
||||||
**Docker 中**:
|
**Docker 中**:
|
||||||
@@ -121,12 +125,13 @@ DATABASE_URL="mysql://root:password@localhost:3306/mydb" go run migrate.go up
|
|||||||
# docker-compose.yml
|
# docker-compose.yml
|
||||||
services:
|
services:
|
||||||
app:
|
app:
|
||||||
environment:
|
volumes:
|
||||||
DATABASE_URL: mysql://root:password@db:3306/mydb
|
# 挂载配置文件
|
||||||
|
- ./config.json:/app/config.json:ro
|
||||||
command: sh -c "go run migrate.go up && ./app"
|
command: sh -c "go run migrate.go up && ./app"
|
||||||
```
|
```
|
||||||
|
|
||||||
**注意**:Docker 中使用服务名(`db`),不是 `localhost`
|
**注意**:配置文件中的数据库主机应使用服务名(`db`),不是 `localhost`
|
||||||
|
|
||||||
## 更多信息
|
## 更多信息
|
||||||
|
|
||||||
|
|||||||
@@ -5,15 +5,19 @@ import (
|
|||||||
"fmt"
|
"fmt"
|
||||||
"io"
|
"io"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"git.toowon.com/jimmy/go-common/config"
|
"git.toowon.com/jimmy/go-common/config"
|
||||||
"git.toowon.com/jimmy/go-common/email"
|
"git.toowon.com/jimmy/go-common/email"
|
||||||
|
commonhttp "git.toowon.com/jimmy/go-common/http"
|
||||||
|
"git.toowon.com/jimmy/go-common/i18n"
|
||||||
"git.toowon.com/jimmy/go-common/logger"
|
"git.toowon.com/jimmy/go-common/logger"
|
||||||
"git.toowon.com/jimmy/go-common/middleware"
|
"git.toowon.com/jimmy/go-common/middleware"
|
||||||
"git.toowon.com/jimmy/go-common/migration"
|
"git.toowon.com/jimmy/go-common/migration"
|
||||||
"git.toowon.com/jimmy/go-common/sms"
|
"git.toowon.com/jimmy/go-common/sms"
|
||||||
"git.toowon.com/jimmy/go-common/storage"
|
"git.toowon.com/jimmy/go-common/storage"
|
||||||
|
"git.toowon.com/jimmy/go-common/tools"
|
||||||
"github.com/redis/go-redis/v9"
|
"github.com/redis/go-redis/v9"
|
||||||
"gorm.io/driver/mysql"
|
"gorm.io/driver/mysql"
|
||||||
"gorm.io/driver/postgres"
|
"gorm.io/driver/postgres"
|
||||||
@@ -21,6 +25,57 @@ import (
|
|||||||
"gorm.io/gorm"
|
"gorm.io/gorm"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// ========== HTTP响应结构体(暴露给外部项目使用) ==========
|
||||||
|
|
||||||
|
// Response 标准响应结构(暴露给外部项目使用)
|
||||||
|
// 外部项目可以直接使用 factory.Response 创建响应对象
|
||||||
|
//
|
||||||
|
// 示例:
|
||||||
|
//
|
||||||
|
// response := factory.Response{
|
||||||
|
// Code: 0,
|
||||||
|
// Message: "success",
|
||||||
|
// Data: data,
|
||||||
|
// }
|
||||||
|
type Response = commonhttp.Response
|
||||||
|
|
||||||
|
// PageResponse 分页响应结构(暴露给外部项目使用)
|
||||||
|
// 外部项目可以直接使用 factory.PageResponse 创建分页响应对象
|
||||||
|
type PageResponse = commonhttp.PageResponse
|
||||||
|
|
||||||
|
// PageData 分页数据(暴露给外部项目使用)
|
||||||
|
// 外部项目可以直接使用 factory.PageData 创建分页数据对象
|
||||||
|
//
|
||||||
|
// 示例:
|
||||||
|
//
|
||||||
|
// pageData := &factory.PageData{
|
||||||
|
// List: users,
|
||||||
|
// Total: 100,
|
||||||
|
// Page: 1,
|
||||||
|
// PageSize: 20,
|
||||||
|
// }
|
||||||
|
// fac.Success(w, pageData)
|
||||||
|
type PageData = commonhttp.PageData
|
||||||
|
|
||||||
|
// ========== HTTP请求结构体(暴露给外部项目使用) ==========
|
||||||
|
|
||||||
|
// PaginationRequest 分页请求结构(暴露给外部项目使用)
|
||||||
|
// 外部项目可以直接使用 factory.PaginationRequest 创建分页请求对象
|
||||||
|
//
|
||||||
|
// 示例:
|
||||||
|
//
|
||||||
|
// type ListUserRequest struct {
|
||||||
|
// Keyword string `json:"keyword"`
|
||||||
|
// factory.PaginationRequest // 嵌入分页请求结构
|
||||||
|
// }
|
||||||
|
type PaginationRequest = commonhttp.PaginationRequest
|
||||||
|
|
||||||
|
// ========== Time工具结构体(暴露给外部项目使用) ==========
|
||||||
|
|
||||||
|
// TimeInfo 详细时间信息结构(暴露给外部项目使用)
|
||||||
|
// 外部项目可以直接使用 factory.TimeInfo 创建时间信息对象
|
||||||
|
type TimeInfo = tools.TimeInfo
|
||||||
|
|
||||||
// Factory 工厂类 - 黑盒模式设计
|
// Factory 工厂类 - 黑盒模式设计
|
||||||
//
|
//
|
||||||
// 核心理念:
|
// 核心理念:
|
||||||
@@ -65,6 +120,7 @@ type Factory struct {
|
|||||||
sms *sms.SMS // 短信客户端(延迟初始化)
|
sms *sms.SMS // 短信客户端(延迟初始化)
|
||||||
db *gorm.DB // 数据库连接(延迟初始化)
|
db *gorm.DB // 数据库连接(延迟初始化)
|
||||||
redis *redis.Client // Redis客户端(延迟初始化)
|
redis *redis.Client // Redis客户端(延迟初始化)
|
||||||
|
i18n *i18n.I18n // 国际化工具(延迟初始化)
|
||||||
}
|
}
|
||||||
|
|
||||||
// NewFactory 创建工厂实例
|
// NewFactory 创建工厂实例
|
||||||
@@ -90,17 +146,8 @@ func (f *Factory) getEmailClient() (*email.Email, error) {
|
|||||||
return f.email, nil
|
return f.email, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
if f.cfg.Email == nil {
|
f.email = email.NewEmail(f.cfg)
|
||||||
return nil, fmt.Errorf("email config is nil")
|
return f.email, nil
|
||||||
}
|
|
||||||
|
|
||||||
e, err := email.NewEmail(f.cfg.Email)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("failed to create email client: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
f.email = e
|
|
||||||
return e, nil
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// SendEmail 发送邮件(黑盒模式,推荐使用)
|
// SendEmail 发送邮件(黑盒模式,推荐使用)
|
||||||
@@ -114,18 +161,7 @@ func (f *Factory) SendEmail(to []string, subject, body string, htmlBody ...strin
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
return e.SendEmail(to, subject, body, htmlBody...)
|
||||||
msg := &email.Message{
|
|
||||||
To: to,
|
|
||||||
Subject: subject,
|
|
||||||
Body: body,
|
|
||||||
}
|
|
||||||
|
|
||||||
if len(htmlBody) > 0 && htmlBody[0] != "" {
|
|
||||||
msg.HTMLBody = htmlBody[0]
|
|
||||||
}
|
|
||||||
|
|
||||||
return e.Send(msg)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// getSMSClient 获取短信客户端(内部方法,延迟初始化)
|
// getSMSClient 获取短信客户端(内部方法,延迟初始化)
|
||||||
@@ -134,17 +170,8 @@ func (f *Factory) getSMSClient() (*sms.SMS, error) {
|
|||||||
return f.sms, nil
|
return f.sms, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
if f.cfg.SMS == nil {
|
f.sms = sms.NewSMS(f.cfg)
|
||||||
return nil, fmt.Errorf("SMS config is nil")
|
return f.sms, nil
|
||||||
}
|
|
||||||
|
|
||||||
s, err := sms.NewSMS(f.cfg.SMS)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("failed to create SMS client: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
f.sms = s
|
|
||||||
return s, nil
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// SendSMS 发送短信(黑盒模式,推荐使用)
|
// SendSMS 发送短信(黑盒模式,推荐使用)
|
||||||
@@ -157,17 +184,7 @@ func (f *Factory) SendSMS(phoneNumbers []string, templateParam interface{}, temp
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
return s.SendSMS(phoneNumbers, templateParam, templateCode...)
|
||||||
req := &sms.SendRequest{
|
|
||||||
PhoneNumbers: phoneNumbers,
|
|
||||||
TemplateParam: templateParam,
|
|
||||||
}
|
|
||||||
|
|
||||||
if len(templateCode) > 0 && templateCode[0] != "" {
|
|
||||||
req.TemplateCode = templateCode[0]
|
|
||||||
}
|
|
||||||
|
|
||||||
return s.Send(req)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// getLogger 获取日志记录器(内部方法,延迟初始化)
|
// getLogger 获取日志记录器(内部方法,延迟初始化)
|
||||||
@@ -760,7 +777,10 @@ func (f *Factory) GetMiddlewareChain() *middleware.Chain {
|
|||||||
middlewares = append(middlewares, middleware.CORS(corsConfig))
|
middlewares = append(middlewares, middleware.CORS(corsConfig))
|
||||||
}
|
}
|
||||||
|
|
||||||
// 5. Timezone 中间件(必需,处理时区)
|
// 5. Language 中间件(必需,处理语言)
|
||||||
|
middlewares = append(middlewares, middleware.Language)
|
||||||
|
|
||||||
|
// 6. Timezone 中间件(必需,处理时区)
|
||||||
middlewares = append(middlewares, middleware.Timezone)
|
middlewares = append(middlewares, middleware.Timezone)
|
||||||
|
|
||||||
return middleware.NewChain(middlewares...)
|
return middleware.NewChain(middlewares...)
|
||||||
@@ -789,8 +809,12 @@ func (f *Factory) RunMigrations(migrationsDir string) error {
|
|||||||
return fmt.Errorf("failed to get database: %w", err)
|
return fmt.Errorf("failed to get database: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
// 创建迁移器
|
// 创建迁移器(传入数据库类型,性能更好)
|
||||||
migrator := migration.NewMigrator(db)
|
dbType := "mysql" // 默认值
|
||||||
|
if f.cfg.Database != nil && f.cfg.Database.Type != "" {
|
||||||
|
dbType = f.cfg.Database.Type
|
||||||
|
}
|
||||||
|
migrator := migration.NewMigratorWithType(db, dbType)
|
||||||
|
|
||||||
// 自动发现并加载迁移文件
|
// 自动发现并加载迁移文件
|
||||||
migrations, err := migration.LoadMigrationsFromFiles(migrationsDir, "*.sql")
|
migrations, err := migration.LoadMigrationsFromFiles(migrationsDir, "*.sql")
|
||||||
@@ -835,8 +859,12 @@ func (f *Factory) GetMigrationStatus(migrationsDir string) ([]migration.Migratio
|
|||||||
return nil, fmt.Errorf("failed to get database: %w", err)
|
return nil, fmt.Errorf("failed to get database: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
// 创建迁移器
|
// 创建迁移器(传入数据库类型,性能更好)
|
||||||
migrator := migration.NewMigrator(db)
|
dbType := "mysql" // 默认值
|
||||||
|
if f.cfg.Database != nil && f.cfg.Database.Type != "" {
|
||||||
|
dbType = f.cfg.Database.Type
|
||||||
|
}
|
||||||
|
migrator := migration.NewMigratorWithType(db, dbType)
|
||||||
|
|
||||||
// 加载迁移文件
|
// 加载迁移文件
|
||||||
migrations, err := migration.LoadMigrationsFromFiles(migrationsDir, "*.sql")
|
migrations, err := migration.LoadMigrationsFromFiles(migrationsDir, "*.sql")
|
||||||
@@ -854,3 +882,674 @@ func (f *Factory) GetMigrationStatus(migrationsDir string) ([]migration.Migratio
|
|||||||
|
|
||||||
return status, nil
|
return status, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ========== HTTP响应方法(黑盒模式,推荐使用) ==========
|
||||||
|
//
|
||||||
|
// 这些方法直接调用 http 包的公共方法,保持低耦合。
|
||||||
|
// 推荐直接使用 factory.Success() 等方法,而不是通过 handler。
|
||||||
|
|
||||||
|
// Success 成功响应(黑盒模式,推荐使用)
|
||||||
|
// w: ResponseWriter
|
||||||
|
// data: 响应数据,可以为nil
|
||||||
|
// message: 响应消息(可选),如果为空则使用默认消息 "success"
|
||||||
|
//
|
||||||
|
// 示例:
|
||||||
|
//
|
||||||
|
// fac, _ := factory.NewFactoryFromFile("config.json")
|
||||||
|
// http.HandleFunc("/user", func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
// fac.Success(w, user) // 只有数据
|
||||||
|
// fac.Success(w, user, "查询成功") // 数据+消息
|
||||||
|
// })
|
||||||
|
func (f *Factory) Success(w http.ResponseWriter, data interface{}, message ...string) {
|
||||||
|
commonhttp.Success(w, data, message...)
|
||||||
|
}
|
||||||
|
|
||||||
|
// SuccessPage 分页成功响应(黑盒模式,推荐使用)
|
||||||
|
// w: ResponseWriter
|
||||||
|
// list: 数据列表
|
||||||
|
// total: 总记录数
|
||||||
|
// page: 当前页码
|
||||||
|
// pageSize: 每页大小
|
||||||
|
// message: 响应消息(可选),如果为空则使用默认消息 "success"
|
||||||
|
func (f *Factory) SuccessPage(w http.ResponseWriter, list interface{}, total int64, page, pageSize int, message ...string) {
|
||||||
|
commonhttp.SuccessPage(w, list, total, page, pageSize, message...)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Error 错误响应(黑盒模式,推荐使用)
|
||||||
|
// w: ResponseWriter
|
||||||
|
// r: HTTP请求(用于获取语言信息和i18n处理)
|
||||||
|
// code: 业务错误码(如果message是消息代码,此参数会被语言文件中的code覆盖)
|
||||||
|
// message: 错误消息或消息代码(如果i18n已初始化且message是消息代码格式,会自动获取国际化消息和业务code)
|
||||||
|
// args: 可选参数,用于格式化消息(类似 fmt.Sprintf,仅在message是消息代码时使用)
|
||||||
|
//
|
||||||
|
// 使用逻辑:
|
||||||
|
// 1. 如果i18n已初始化,且message看起来是消息代码(包含点号,如 "user.not_found"),
|
||||||
|
// 则从请求context中获取语言,并尝试从语言文件中获取国际化消息和业务code
|
||||||
|
// 2. 如果获取到国际化消息,使用语言文件中的code作为响应code,使用国际化消息作为响应message
|
||||||
|
// 3. 如果未获取到或i18n未初始化,使用传入的code和message
|
||||||
|
//
|
||||||
|
// 示例:
|
||||||
|
//
|
||||||
|
// // 方式1:直接传入消息代码(推荐,自动国际化)
|
||||||
|
// fac.Error(w, r, 0, "user.not_found")
|
||||||
|
// // 如果请求语言是 zh-CN,且语言文件中 "user.not_found" 的 code 是 1001,
|
||||||
|
// // 返回: {"code": 1001, "message": "用户不存在"}
|
||||||
|
// // 如果请求语言是 en-US,返回: {"code": 1001, "message": "User not found"}
|
||||||
|
//
|
||||||
|
// // 方式2:带参数的消息代码
|
||||||
|
// fac.Error(w, r, 0, "user.welcome", "Alice")
|
||||||
|
// // 如果消息内容是 "欢迎,%s",返回: {"code": 0, "message": "欢迎,Alice"}
|
||||||
|
//
|
||||||
|
// // 方式3:直接传入消息文本(不使用国际化)
|
||||||
|
// fac.Error(w, r, 500, "系统错误")
|
||||||
|
// // 返回: {"code": 500, "message": "系统错误"}
|
||||||
|
func (f *Factory) Error(w http.ResponseWriter, r *http.Request, code int, message string, args ...interface{}) {
|
||||||
|
// 判断message是否是消息代码(简单判断:包含点号)
|
||||||
|
isMessageCode := strings.Contains(message, ".")
|
||||||
|
|
||||||
|
var finalCode int
|
||||||
|
var finalMessage string
|
||||||
|
|
||||||
|
if isMessageCode {
|
||||||
|
// 尝试从i18n获取国际化消息和业务code
|
||||||
|
if i, err := f.getI18n(); err == nil {
|
||||||
|
// i18n已初始化,获取语言并查找消息
|
||||||
|
lang := f.GetLanguage(r)
|
||||||
|
if lang == "" {
|
||||||
|
lang = i.GetDefaultLang()
|
||||||
|
}
|
||||||
|
msgInfo := i.GetMessageInfo(lang, message, args...)
|
||||||
|
// 如果获取到了国际化消息(不是返回code本身),使用国际化消息和业务code
|
||||||
|
if msgInfo.Message != message {
|
||||||
|
finalCode = msgInfo.Code
|
||||||
|
finalMessage = msgInfo.Message
|
||||||
|
} else {
|
||||||
|
// 消息代码不存在,使用传入的code和消息代码作为消息
|
||||||
|
finalCode = code
|
||||||
|
finalMessage = message
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// i18n未初始化,使用传入的code和消息代码作为消息
|
||||||
|
finalCode = code
|
||||||
|
finalMessage = message
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// 不是消息代码格式,使用传入的code和消息
|
||||||
|
finalCode = code
|
||||||
|
finalMessage = message
|
||||||
|
}
|
||||||
|
|
||||||
|
commonhttp.Error(w, finalCode, finalMessage)
|
||||||
|
}
|
||||||
|
|
||||||
|
// SystemError 系统错误响应(返回HTTP 500)(黑盒模式,推荐使用)
|
||||||
|
// w: ResponseWriter
|
||||||
|
// message: 错误消息
|
||||||
|
func (f *Factory) SystemError(w http.ResponseWriter, message string) {
|
||||||
|
commonhttp.SystemError(w, message)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ========== HTTP请求解析方法(黑盒模式,推荐使用) ==========
|
||||||
|
//
|
||||||
|
// 这些方法直接调用 http 包的公共方法,保持低耦合。
|
||||||
|
// 推荐直接使用 factory.ParseJSON()、factory.ConvertInt() 等方法。
|
||||||
|
|
||||||
|
// ParseJSON 解析JSON请求体(黑盒模式,推荐使用)
|
||||||
|
// r: HTTP请求
|
||||||
|
// v: 目标结构体指针
|
||||||
|
//
|
||||||
|
// 示例:
|
||||||
|
//
|
||||||
|
// var req struct {
|
||||||
|
// Name string `json:"name"`
|
||||||
|
// }
|
||||||
|
// if err := fac.ParseJSON(r, &req); err != nil {
|
||||||
|
// fac.Error(w, 400, "请求参数解析失败")
|
||||||
|
// return
|
||||||
|
// }
|
||||||
|
func (f *Factory) ParseJSON(r *http.Request, v interface{}) error {
|
||||||
|
return commonhttp.ParseJSON(r, v)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ParsePaginationRequest 从请求中解析分页参数(黑盒模式,推荐使用)
|
||||||
|
// r: HTTP请求
|
||||||
|
// 支持从查询参数和form表单中解析
|
||||||
|
// 优先级:查询参数 > form表单
|
||||||
|
//
|
||||||
|
// 示例:
|
||||||
|
//
|
||||||
|
// pagination := fac.ParsePaginationRequest(r)
|
||||||
|
// page := pagination.GetPage()
|
||||||
|
// pageSize := pagination.GetSize()
|
||||||
|
func (f *Factory) ParsePaginationRequest(r *http.Request) *PaginationRequest {
|
||||||
|
return commonhttp.ParsePaginationRequest(r)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ConvertInt 将字符串转换为int类型(黑盒模式,推荐使用)
|
||||||
|
// value: 待转换的字符串
|
||||||
|
// defaultValue: 转换失败或字符串为空时返回的默认值
|
||||||
|
func (f *Factory) ConvertInt(value string, defaultValue int) int {
|
||||||
|
return tools.ConvertInt(value, defaultValue)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ConvertInt64 将字符串转换为int64类型(黑盒模式,推荐使用)
|
||||||
|
// value: 待转换的字符串
|
||||||
|
// defaultValue: 转换失败或字符串为空时返回的默认值
|
||||||
|
func (f *Factory) ConvertInt64(value string, defaultValue int64) int64 {
|
||||||
|
return tools.ConvertInt64(value, defaultValue)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ConvertUint64 将字符串转换为uint64类型(黑盒模式,推荐使用)
|
||||||
|
// value: 待转换的字符串
|
||||||
|
// defaultValue: 转换失败或字符串为空时返回的默认值
|
||||||
|
func (f *Factory) ConvertUint64(value string, defaultValue uint64) uint64 {
|
||||||
|
return tools.ConvertUint64(value, defaultValue)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ConvertUint32 将字符串转换为uint32类型(黑盒模式,推荐使用)
|
||||||
|
// value: 待转换的字符串
|
||||||
|
// defaultValue: 转换失败或字符串为空时返回的默认值
|
||||||
|
func (f *Factory) ConvertUint32(value string, defaultValue uint32) uint32 {
|
||||||
|
return tools.ConvertUint32(value, defaultValue)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ConvertBool 将字符串转换为bool类型(黑盒模式,推荐使用)
|
||||||
|
// value: 待转换的字符串
|
||||||
|
// defaultValue: 转换失败或字符串为空时返回的默认值
|
||||||
|
func (f *Factory) ConvertBool(value string, defaultValue bool) bool {
|
||||||
|
return tools.ConvertBool(value, defaultValue)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ConvertFloat64 将字符串转换为float64类型(黑盒模式,推荐使用)
|
||||||
|
// value: 待转换的字符串
|
||||||
|
// defaultValue: 转换失败或字符串为空时返回的默认值
|
||||||
|
func (f *Factory) ConvertFloat64(value string, defaultValue float64) float64 {
|
||||||
|
return tools.ConvertFloat64(value, defaultValue)
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetTimezone 从请求的context中获取时区(黑盒模式,推荐使用)
|
||||||
|
// r: HTTP请求
|
||||||
|
// 如果使用了middleware.Timezone中间件,可以从context中获取时区信息
|
||||||
|
// 如果未设置,返回默认时区 AsiaShanghai
|
||||||
|
func (f *Factory) GetTimezone(r *http.Request) string {
|
||||||
|
return commonhttp.GetTimezone(r)
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetLanguage 从请求的context中获取语言(黑盒模式,推荐使用)
|
||||||
|
// r: HTTP请求
|
||||||
|
// 如果使用了middleware.Language中间件,可以从context中获取语言信息
|
||||||
|
// 如果未设置,返回默认语言 zh-CN
|
||||||
|
func (f *Factory) GetLanguage(r *http.Request) string {
|
||||||
|
return commonhttp.GetLanguage(r)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ========== Tools工具方法(黑盒模式,推荐使用) ==========
|
||||||
|
//
|
||||||
|
// 这些方法直接调用 tools 包的公共方法,保持低耦合。
|
||||||
|
// factory 只负责方法暴露,具体业务在 tools 包中实现。
|
||||||
|
|
||||||
|
// ========== Version 版本工具 ==========
|
||||||
|
|
||||||
|
// GetVersion 获取版本号(黑盒模式,推荐使用)
|
||||||
|
// 优先从环境变量 DOCKER_TAG 或 VERSION 中读取
|
||||||
|
// 如果没有设置环境变量,则使用默认版本号
|
||||||
|
func (f *Factory) GetVersion() string {
|
||||||
|
return tools.GetVersion()
|
||||||
|
}
|
||||||
|
|
||||||
|
// ========== Money 金额工具 ==========
|
||||||
|
|
||||||
|
// GetMoneyCalculator 获取金额计算器(黑盒模式,推荐使用)
|
||||||
|
// 返回金额计算器实例,可用于金额计算操作
|
||||||
|
func (f *Factory) GetMoneyCalculator() *tools.MoneyCalculator {
|
||||||
|
return tools.NewMoneyCalculator()
|
||||||
|
}
|
||||||
|
|
||||||
|
// YuanToCents 元转分(黑盒模式,推荐使用)
|
||||||
|
func (f *Factory) YuanToCents(yuan float64) int64 {
|
||||||
|
return tools.YuanToCents(yuan)
|
||||||
|
}
|
||||||
|
|
||||||
|
// CentsToYuan 分转元(黑盒模式,推荐使用)
|
||||||
|
func (f *Factory) CentsToYuan(cents int64) float64 {
|
||||||
|
return tools.CentsToYuan(cents)
|
||||||
|
}
|
||||||
|
|
||||||
|
// FormatYuan 格式化显示金额(分转元,保留2位小数)(黑盒模式,推荐使用)
|
||||||
|
func (f *Factory) FormatYuan(cents int64) string {
|
||||||
|
return tools.FormatYuan(cents)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ========== DateTime 日期时间工具 ==========
|
||||||
|
|
||||||
|
// Now 获取当前时间(使用指定时区)(黑盒模式,推荐使用)
|
||||||
|
func (f *Factory) Now(timezone ...string) time.Time {
|
||||||
|
return tools.Now(timezone...)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ParseDateTime 解析日期时间字符串(2006-01-02 15:04:05)(黑盒模式,推荐使用)
|
||||||
|
func (f *Factory) ParseDateTime(value string, timezone ...string) (time.Time, error) {
|
||||||
|
return tools.ParseDateTime(value, timezone...)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ParseDate 解析日期字符串(2006-01-02)(黑盒模式,推荐使用)
|
||||||
|
func (f *Factory) ParseDate(value string, timezone ...string) (time.Time, error) {
|
||||||
|
return tools.ParseDate(value, timezone...)
|
||||||
|
}
|
||||||
|
|
||||||
|
// FormatDateTime 格式化日期时间(2006-01-02 15:04:05)(黑盒模式,推荐使用)
|
||||||
|
func (f *Factory) FormatDateTime(t time.Time, timezone ...string) string {
|
||||||
|
return tools.FormatDateTime(t, timezone...)
|
||||||
|
}
|
||||||
|
|
||||||
|
// FormatDate 格式化日期(2006-01-02)(黑盒模式,推荐使用)
|
||||||
|
func (f *Factory) FormatDate(t time.Time, timezone ...string) string {
|
||||||
|
return tools.FormatDate(t, timezone...)
|
||||||
|
}
|
||||||
|
|
||||||
|
// FormatTime 格式化时间(15:04:05)(黑盒模式,推荐使用)
|
||||||
|
func (f *Factory) FormatTime(t time.Time, timezone ...string) string {
|
||||||
|
return tools.FormatTime(t, timezone...)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ToUnix 转换为Unix时间戳(黑盒模式,推荐使用)
|
||||||
|
func (f *Factory) ToUnix(t time.Time) int64 {
|
||||||
|
return tools.ToUnix(t)
|
||||||
|
}
|
||||||
|
|
||||||
|
// FromUnix 从Unix时间戳创建时间(黑盒模式,推荐使用)
|
||||||
|
func (f *Factory) FromUnix(sec int64, timezone ...string) time.Time {
|
||||||
|
return tools.FromUnix(sec, timezone...)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ToUnixMilli 转换为Unix毫秒时间戳(黑盒模式,推荐使用)
|
||||||
|
func (f *Factory) ToUnixMilli(t time.Time) int64 {
|
||||||
|
return tools.ToUnixMilli(t)
|
||||||
|
}
|
||||||
|
|
||||||
|
// FromUnixMilli 从Unix毫秒时间戳创建时间(黑盒模式,推荐使用)
|
||||||
|
func (f *Factory) FromUnixMilli(msec int64, timezone ...string) time.Time {
|
||||||
|
return tools.FromUnixMilli(msec, timezone...)
|
||||||
|
}
|
||||||
|
|
||||||
|
// AddDays 添加天数(黑盒模式,推荐使用)
|
||||||
|
func (f *Factory) AddDays(t time.Time, days int) time.Time {
|
||||||
|
return tools.AddDays(t, days)
|
||||||
|
}
|
||||||
|
|
||||||
|
// AddMonths 添加月数(黑盒模式,推荐使用)
|
||||||
|
func (f *Factory) AddMonths(t time.Time, months int) time.Time {
|
||||||
|
return tools.AddMonths(t, months)
|
||||||
|
}
|
||||||
|
|
||||||
|
// AddYears 添加年数(黑盒模式,推荐使用)
|
||||||
|
func (f *Factory) AddYears(t time.Time, years int) time.Time {
|
||||||
|
return tools.AddYears(t, years)
|
||||||
|
}
|
||||||
|
|
||||||
|
// StartOfDay 获取一天的开始时间(00:00:00)(黑盒模式,推荐使用)
|
||||||
|
func (f *Factory) StartOfDay(t time.Time, timezone ...string) time.Time {
|
||||||
|
return tools.StartOfDay(t, timezone...)
|
||||||
|
}
|
||||||
|
|
||||||
|
// EndOfDay 获取一天的结束时间(23:59:59.999999999)(黑盒模式,推荐使用)
|
||||||
|
func (f *Factory) EndOfDay(t time.Time, timezone ...string) time.Time {
|
||||||
|
return tools.EndOfDay(t, timezone...)
|
||||||
|
}
|
||||||
|
|
||||||
|
// StartOfMonth 获取月份的开始时间(黑盒模式,推荐使用)
|
||||||
|
func (f *Factory) StartOfMonth(t time.Time, timezone ...string) time.Time {
|
||||||
|
return tools.StartOfMonth(t, timezone...)
|
||||||
|
}
|
||||||
|
|
||||||
|
// EndOfMonth 获取月份的结束时间(黑盒模式,推荐使用)
|
||||||
|
func (f *Factory) EndOfMonth(t time.Time, timezone ...string) time.Time {
|
||||||
|
return tools.EndOfMonth(t, timezone...)
|
||||||
|
}
|
||||||
|
|
||||||
|
// StartOfYear 获取年份的开始时间(黑盒模式,推荐使用)
|
||||||
|
func (f *Factory) StartOfYear(t time.Time, timezone ...string) time.Time {
|
||||||
|
return tools.StartOfYear(t, timezone...)
|
||||||
|
}
|
||||||
|
|
||||||
|
// EndOfYear 获取年份的结束时间(黑盒模式,推荐使用)
|
||||||
|
func (f *Factory) EndOfYear(t time.Time, timezone ...string) time.Time {
|
||||||
|
return tools.EndOfYear(t, timezone...)
|
||||||
|
}
|
||||||
|
|
||||||
|
// DiffDays 计算两个时间之间的天数差(黑盒模式,推荐使用)
|
||||||
|
func (f *Factory) DiffDays(t1, t2 time.Time) int {
|
||||||
|
return tools.DiffDays(t1, t2)
|
||||||
|
}
|
||||||
|
|
||||||
|
// DiffHours 计算两个时间之间的小时差(黑盒模式,推荐使用)
|
||||||
|
func (f *Factory) DiffHours(t1, t2 time.Time) int64 {
|
||||||
|
return tools.DiffHours(t1, t2)
|
||||||
|
}
|
||||||
|
|
||||||
|
// DiffMinutes 计算两个时间之间的分钟差(黑盒模式,推荐使用)
|
||||||
|
func (f *Factory) DiffMinutes(t1, t2 time.Time) int64 {
|
||||||
|
return tools.DiffMinutes(t1, t2)
|
||||||
|
}
|
||||||
|
|
||||||
|
// DiffSeconds 计算两个时间之间的秒数差(黑盒模式,推荐使用)
|
||||||
|
func (f *Factory) DiffSeconds(t1, t2 time.Time) int64 {
|
||||||
|
return tools.DiffSeconds(t1, t2)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ========== Time 时间工具(黑盒模式,推荐使用) ==========
|
||||||
|
//
|
||||||
|
// 这些方法提供基础时间操作、时间戳、时间判断等功能。
|
||||||
|
// 与 DateTime 工具的区别:
|
||||||
|
// - DateTime: 专注于时区相关、格式化、解析、UTC转换
|
||||||
|
// - Time: 专注于基础时间操作、时间戳、时间判断、时间信息生成
|
||||||
|
|
||||||
|
// ========== 时间戳方法 ==========
|
||||||
|
|
||||||
|
// GetTimestamp 获取当前时间戳(秒)(黑盒模式,推荐使用)
|
||||||
|
func (f *Factory) GetTimestamp() int64 {
|
||||||
|
return tools.GetTimestamp()
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetMillisTimestamp 获取当前时间戳(毫秒)(黑盒模式,推荐使用)
|
||||||
|
func (f *Factory) GetMillisTimestamp() int64 {
|
||||||
|
return tools.GetMillisTimestamp()
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetUTCTimestamp 获取UTC时间戳(秒)(黑盒模式,推荐使用)
|
||||||
|
func (f *Factory) GetUTCTimestamp() int64 {
|
||||||
|
return tools.GetUTCTimestamp()
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetUTCTimestampFromTime 从指定时间获取UTC时间戳(秒)(黑盒模式,推荐使用)
|
||||||
|
func (f *Factory) GetUTCTimestampFromTime(t time.Time) int64 {
|
||||||
|
return tools.GetUTCTimestampFromTime(t)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ========== 格式化方法(自定义格式) ==========
|
||||||
|
|
||||||
|
// FormatTimeWithLayout 格式化时间(自定义格式)(黑盒模式,推荐使用)
|
||||||
|
// layout: 时间格式,如 "2006-01-02 15:04:05",如果为空则使用默认格式
|
||||||
|
func (f *Factory) FormatTimeWithLayout(t time.Time, layout string) string {
|
||||||
|
return tools.FormatTimeWithLayout(t, layout)
|
||||||
|
}
|
||||||
|
|
||||||
|
// FormatTimeUTC 格式化时间为UTC字符串(ISO 8601格式)(黑盒模式,推荐使用)
|
||||||
|
func (f *Factory) FormatTimeUTC(t time.Time) string {
|
||||||
|
return tools.FormatTimeUTC(t)
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetCurrentTime 获取当前时间字符串(黑盒模式,推荐使用)
|
||||||
|
// 使用默认格式 "2006-01-02 15:04:05"
|
||||||
|
func (f *Factory) GetCurrentTime() string {
|
||||||
|
return tools.GetCurrentTime()
|
||||||
|
}
|
||||||
|
|
||||||
|
// ========== 解析方法(自定义格式) ==========
|
||||||
|
|
||||||
|
// ParseTime 解析时间字符串(自定义格式)(黑盒模式,推荐使用)
|
||||||
|
// timeStr: 时间字符串
|
||||||
|
// layout: 时间格式,如 "2006-01-02 15:04:05",如果为空则使用默认格式
|
||||||
|
func (f *Factory) ParseTime(timeStr, layout string) (time.Time, error) {
|
||||||
|
return tools.ParseTime(timeStr, layout)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ========== 时间计算(补充 DateTime 的 Add 系列) ==========
|
||||||
|
|
||||||
|
// AddHours 增加小时数(黑盒模式,推荐使用)
|
||||||
|
func (f *Factory) AddHours(t time.Time, hours int) time.Time {
|
||||||
|
return tools.AddHours(t, hours)
|
||||||
|
}
|
||||||
|
|
||||||
|
// AddMinutes 增加分钟数(黑盒模式,推荐使用)
|
||||||
|
func (f *Factory) AddMinutes(t time.Time, minutes int) time.Time {
|
||||||
|
return tools.AddMinutes(t, minutes)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ========== 时间范围(周相关) ==========
|
||||||
|
|
||||||
|
// GetBeginOfWeek 获取某周的开始时间(周一)(黑盒模式,推荐使用)
|
||||||
|
func (f *Factory) GetBeginOfWeek(t time.Time) time.Time {
|
||||||
|
return tools.GetBeginOfWeek(t)
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetEndOfWeek 获取某周的结束时间(周日)(黑盒模式,推荐使用)
|
||||||
|
func (f *Factory) GetEndOfWeek(t time.Time) time.Time {
|
||||||
|
return tools.GetEndOfWeek(t)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ========== 时间判断 ==========
|
||||||
|
|
||||||
|
// IsToday 判断是否为今天(黑盒模式,推荐使用)
|
||||||
|
func (f *Factory) IsToday(t time.Time) bool {
|
||||||
|
return tools.IsToday(t)
|
||||||
|
}
|
||||||
|
|
||||||
|
// IsYesterday 判断是否为昨天(黑盒模式,推荐使用)
|
||||||
|
func (f *Factory) IsYesterday(t time.Time) bool {
|
||||||
|
return tools.IsYesterday(t)
|
||||||
|
}
|
||||||
|
|
||||||
|
// IsTomorrow 判断是否为明天(黑盒模式,推荐使用)
|
||||||
|
func (f *Factory) IsTomorrow(t time.Time) bool {
|
||||||
|
return tools.IsTomorrow(t)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ========== 时间信息生成 ==========
|
||||||
|
|
||||||
|
// GenerateTimeInfoWithTimezone 生成详细时间信息(指定时区)(黑盒模式,推荐使用)
|
||||||
|
// 返回包含UTC时间、本地时间、时间戳、时区信息等的完整时间信息结构
|
||||||
|
func (f *Factory) GenerateTimeInfoWithTimezone(t time.Time, timezone string) TimeInfo {
|
||||||
|
return tools.GenerateTimeInfoWithTimezone(t, timezone)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ========== Crypto 加密工具(黑盒模式,推荐使用) ==========
|
||||||
|
//
|
||||||
|
// 这些方法提供密码加密、哈希计算、随机字符串生成等功能。
|
||||||
|
|
||||||
|
// ========== 密码加密 ==========
|
||||||
|
|
||||||
|
// HashPassword 使用bcrypt加密密码(黑盒模式,推荐使用)
|
||||||
|
// password: 原始密码
|
||||||
|
// 返回: 加密后的密码哈希值
|
||||||
|
func (f *Factory) HashPassword(password string) (string, error) {
|
||||||
|
return tools.HashPassword(password)
|
||||||
|
}
|
||||||
|
|
||||||
|
// CheckPassword 验证密码(黑盒模式,推荐使用)
|
||||||
|
// password: 原始密码
|
||||||
|
// hash: 加密后的密码哈希值
|
||||||
|
// 返回: 密码是否正确
|
||||||
|
func (f *Factory) CheckPassword(password, hash string) bool {
|
||||||
|
return tools.CheckPassword(password, hash)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ========== 哈希计算 ==========
|
||||||
|
|
||||||
|
// MD5 计算MD5哈希值(黑盒模式,推荐使用)
|
||||||
|
// text: 要计算哈希的文本
|
||||||
|
// 返回: MD5哈希值(十六进制字符串)
|
||||||
|
func (f *Factory) MD5(text string) string {
|
||||||
|
return tools.MD5(text)
|
||||||
|
}
|
||||||
|
|
||||||
|
// SHA256 计算SHA256哈希值(黑盒模式,推荐使用)
|
||||||
|
// text: 要计算哈希的文本
|
||||||
|
// 返回: SHA256哈希值(十六进制字符串)
|
||||||
|
func (f *Factory) SHA256(text string) string {
|
||||||
|
return tools.SHA256(text)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ========== 随机字符串生成 ==========
|
||||||
|
|
||||||
|
// GenerateRandomString 生成指定长度的随机字符串(黑盒模式,推荐使用)
|
||||||
|
// length: 字符串长度
|
||||||
|
// 返回: 随机字符串(包含大小写字母和数字)
|
||||||
|
func (f *Factory) GenerateRandomString(length int) string {
|
||||||
|
return tools.GenerateRandomString(length)
|
||||||
|
}
|
||||||
|
|
||||||
|
// GenerateRandomNumber 生成指定长度的随机数字字符串(黑盒模式,推荐使用)
|
||||||
|
// length: 字符串长度
|
||||||
|
// 返回: 随机数字字符串
|
||||||
|
func (f *Factory) GenerateRandomNumber(length int) string {
|
||||||
|
return tools.GenerateRandomNumber(length)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ========== 业务相关随机码生成 ==========
|
||||||
|
|
||||||
|
// GenerateSMSCode 生成短信验证码(黑盒模式,推荐使用)
|
||||||
|
// 返回: 6位数字验证码
|
||||||
|
func (f *Factory) GenerateSMSCode() string {
|
||||||
|
return tools.GenerateSMSCode()
|
||||||
|
}
|
||||||
|
|
||||||
|
// GenerateOrderNo 生成订单号(黑盒模式,推荐使用)
|
||||||
|
// prefix: 订单号前缀
|
||||||
|
// 返回: 订单号(格式:前缀+时间戳+6位随机数)
|
||||||
|
func (f *Factory) GenerateOrderNo(prefix string) string {
|
||||||
|
return tools.GenerateOrderNo(prefix)
|
||||||
|
}
|
||||||
|
|
||||||
|
// GeneratePaymentNo 生成支付单号(黑盒模式,推荐使用)
|
||||||
|
// 返回: 支付单号(格式:PAY+时间戳+6位随机数)
|
||||||
|
func (f *Factory) GeneratePaymentNo() string {
|
||||||
|
return tools.GeneratePaymentNo()
|
||||||
|
}
|
||||||
|
|
||||||
|
// GenerateRefundNo 生成退款单号(黑盒模式,推荐使用)
|
||||||
|
// 返回: 退款单号(格式:RF+时间戳+6位随机数)
|
||||||
|
func (f *Factory) GenerateRefundNo() string {
|
||||||
|
return tools.GenerateRefundNo()
|
||||||
|
}
|
||||||
|
|
||||||
|
// GenerateTransferNo 生成调拨单号(黑盒模式,推荐使用)
|
||||||
|
// 返回: 调拨单号(格式:TF+时间戳+6位随机数)
|
||||||
|
func (f *Factory) GenerateTransferNo() string {
|
||||||
|
return tools.GenerateTransferNo()
|
||||||
|
}
|
||||||
|
|
||||||
|
// ========== I18n 国际化工具(黑盒模式,推荐使用) ==========
|
||||||
|
//
|
||||||
|
// 这些方法提供多语言内容管理功能,支持从文件加载语言内容,通过语言代码和消息代码获取对应语言的内容。
|
||||||
|
|
||||||
|
// getI18n 获取国际化工具实例(内部方法,延迟初始化)
|
||||||
|
func (f *Factory) getI18n() (*i18n.I18n, error) {
|
||||||
|
if f.i18n != nil {
|
||||||
|
return f.i18n, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// 如果没有配置,返回错误
|
||||||
|
return nil, fmt.Errorf("i18n not initialized, please call InitI18n first")
|
||||||
|
}
|
||||||
|
|
||||||
|
// InitI18n 初始化国际化工具(黑盒模式,推荐使用)
|
||||||
|
// defaultLang: 默认语言代码(如 "zh-CN", "en-US")
|
||||||
|
// 初始化后可以调用 LoadI18nFromDir 或 LoadI18nFromFile 加载语言文件
|
||||||
|
//
|
||||||
|
// 示例:
|
||||||
|
//
|
||||||
|
// fac, _ := factory.NewFactoryFromFile("config.json")
|
||||||
|
// fac.InitI18n("zh-CN")
|
||||||
|
// fac.LoadI18nFromDir("locales")
|
||||||
|
func (f *Factory) InitI18n(defaultLang string) {
|
||||||
|
f.i18n = i18n.NewI18n(defaultLang)
|
||||||
|
}
|
||||||
|
|
||||||
|
// LoadI18nFromDir 从目录加载多个语言文件(黑盒模式,推荐使用)
|
||||||
|
// dirPath: 语言文件目录路径
|
||||||
|
// 文件命名规则:{语言代码}.json(如 zh-CN.json, en-US.json)
|
||||||
|
//
|
||||||
|
// 文件格式示例(zh-CN.json):
|
||||||
|
//
|
||||||
|
// {
|
||||||
|
// "user.not_found": "用户不存在",
|
||||||
|
// "user.login_success": "登录成功",
|
||||||
|
// "user.welcome": "欢迎,%s"
|
||||||
|
// }
|
||||||
|
//
|
||||||
|
// 示例:
|
||||||
|
//
|
||||||
|
// fac.InitI18n("zh-CN")
|
||||||
|
// fac.LoadI18nFromDir("locales")
|
||||||
|
func (f *Factory) LoadI18nFromDir(dirPath string) error {
|
||||||
|
i, err := f.getI18n()
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return i.LoadFromDir(dirPath)
|
||||||
|
}
|
||||||
|
|
||||||
|
// LoadI18nFromFile 从单个语言文件加载内容(黑盒模式,推荐使用)
|
||||||
|
// filePath: 语言文件路径(JSON格式)
|
||||||
|
// lang: 语言代码(如 "zh-CN", "en-US")
|
||||||
|
//
|
||||||
|
// 示例:
|
||||||
|
//
|
||||||
|
// fac.InitI18n("zh-CN")
|
||||||
|
// fac.LoadI18nFromFile("locales/zh-CN.json", "zh-CN")
|
||||||
|
// fac.LoadI18nFromFile("locales/en-US.json", "en-US")
|
||||||
|
func (f *Factory) LoadI18nFromFile(filePath, lang string) error {
|
||||||
|
i, err := f.getI18n()
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return i.LoadFromFile(filePath, lang)
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetMessage 获取指定语言和代码的消息内容(黑盒模式,推荐使用)
|
||||||
|
// lang: 语言代码(如 "zh-CN", "en-US")
|
||||||
|
// code: 消息代码(如 "user.not_found")
|
||||||
|
// args: 可选参数,用于格式化消息(类似 fmt.Sprintf)
|
||||||
|
//
|
||||||
|
// 返回逻辑:
|
||||||
|
// 1. 如果指定语言存在该code,返回对应内容
|
||||||
|
// 2. 如果指定语言不存在,尝试使用默认语言
|
||||||
|
// 3. 如果默认语言也不存在,返回code本身(作为fallback)
|
||||||
|
//
|
||||||
|
// 示例:
|
||||||
|
//
|
||||||
|
// // 简单消息
|
||||||
|
// msg := fac.GetMessage("zh-CN", "user.not_found")
|
||||||
|
// // 返回: "用户不存在"
|
||||||
|
//
|
||||||
|
// // 带参数的消息
|
||||||
|
// msg := fac.GetMessage("zh-CN", "user.welcome", "Alice")
|
||||||
|
// // 如果消息内容是 "欢迎,%s",返回: "欢迎,Alice"
|
||||||
|
func (f *Factory) GetMessage(lang, code string, args ...interface{}) string {
|
||||||
|
i, err := f.getI18n()
|
||||||
|
if err != nil {
|
||||||
|
// 如果未初始化,返回code本身
|
||||||
|
return code
|
||||||
|
}
|
||||||
|
return i.GetMessage(lang, code, args...)
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetI18n 获取国际化工具对象(高级功能时使用)
|
||||||
|
// 返回已初始化的国际化工具对象
|
||||||
|
//
|
||||||
|
// ℹ️ 推荐使用黑盒方法:
|
||||||
|
// - GetMessage():获取消息内容
|
||||||
|
// - LoadI18nFromDir():加载语言文件目录
|
||||||
|
// - LoadI18nFromFile():加载单个语言文件
|
||||||
|
//
|
||||||
|
// 仅在需要使用高级功能时获取对象:
|
||||||
|
// - HasLang():检查语言是否存在
|
||||||
|
// - GetSupportedLangs():获取所有支持的语言
|
||||||
|
// - ReloadFromFile():重新加载语言文件
|
||||||
|
// - SetDefaultLang():动态设置默认语言
|
||||||
|
//
|
||||||
|
// 示例(常用操作,推荐):
|
||||||
|
//
|
||||||
|
// fac.InitI18n("zh-CN")
|
||||||
|
// fac.LoadI18nFromDir("locales")
|
||||||
|
// msg := fac.GetMessage("zh-CN", "user.not_found")
|
||||||
|
//
|
||||||
|
// 示例(高级功能):
|
||||||
|
//
|
||||||
|
// i18n, _ := fac.GetI18n()
|
||||||
|
// langs := i18n.GetSupportedLangs()
|
||||||
|
// hasLang := i18n.HasLang("en-US")
|
||||||
|
func (f *Factory) GetI18n() (*i18n.I18n, error) {
|
||||||
|
return f.getI18n()
|
||||||
|
}
|
||||||
|
|||||||
279
http/handler.go
279
http/handler.go
@@ -1,279 +0,0 @@
|
|||||||
package http
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"encoding/json"
|
|
||||||
"io"
|
|
||||||
"net/http"
|
|
||||||
"strconv"
|
|
||||||
|
|
||||||
"git.toowon.com/jimmy/go-common/middleware"
|
|
||||||
)
|
|
||||||
|
|
||||||
// Handler HTTP处理器包装器,封装ResponseWriter和Request,提供简洁的API
|
|
||||||
type Handler struct {
|
|
||||||
w http.ResponseWriter
|
|
||||||
r *http.Request
|
|
||||||
}
|
|
||||||
|
|
||||||
// NewHandler 创建Handler实例
|
|
||||||
func NewHandler(w http.ResponseWriter, r *http.Request) *Handler {
|
|
||||||
return &Handler{
|
|
||||||
w: w,
|
|
||||||
r: r,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// ResponseWriter 获取原始的ResponseWriter(需要时使用)
|
|
||||||
func (h *Handler) ResponseWriter() http.ResponseWriter {
|
|
||||||
return h.w
|
|
||||||
}
|
|
||||||
|
|
||||||
// Request 获取原始的Request(需要时使用)
|
|
||||||
func (h *Handler) Request() *http.Request {
|
|
||||||
return h.r
|
|
||||||
}
|
|
||||||
|
|
||||||
// Context 获取请求的Context
|
|
||||||
func (h *Handler) Context() context.Context {
|
|
||||||
return h.r.Context()
|
|
||||||
}
|
|
||||||
|
|
||||||
// ========== 响应方法(黑盒模式) ==========
|
|
||||||
|
|
||||||
// Success 成功响应
|
|
||||||
// data: 响应数据,可以为nil
|
|
||||||
func (h *Handler) Success(data interface{}) {
|
|
||||||
writeJSON(h.w, http.StatusOK, 0, "success", data)
|
|
||||||
}
|
|
||||||
|
|
||||||
// SuccessWithMessage 带消息的成功响应
|
|
||||||
func (h *Handler) SuccessWithMessage(message string, data interface{}) {
|
|
||||||
writeJSON(h.w, http.StatusOK, 0, message, data)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Error 错误响应
|
|
||||||
// code: 业务错误码,非0表示业务错误
|
|
||||||
// message: 错误消息
|
|
||||||
func (h *Handler) Error(code int, message string) {
|
|
||||||
writeJSON(h.w, http.StatusOK, code, message, nil)
|
|
||||||
}
|
|
||||||
|
|
||||||
// SystemError 系统错误响应(返回HTTP 500)
|
|
||||||
// message: 错误消息
|
|
||||||
func (h *Handler) SystemError(message string) {
|
|
||||||
writeJSON(h.w, http.StatusInternalServerError, 500, message, nil)
|
|
||||||
}
|
|
||||||
|
|
||||||
// WriteJSON 写入JSON响应(自定义HTTP状态码和业务状态码)
|
|
||||||
// httpCode: HTTP状态码(200表示正常,500表示系统错误等)
|
|
||||||
// code: 业务状态码(0表示成功,非0表示业务错误)
|
|
||||||
// message: 响应消息
|
|
||||||
// data: 响应数据
|
|
||||||
func (h *Handler) WriteJSON(httpCode, code int, message string, data interface{}) {
|
|
||||||
writeJSON(h.w, httpCode, code, message, data)
|
|
||||||
}
|
|
||||||
|
|
||||||
// SuccessPage 分页成功响应
|
|
||||||
// list: 数据列表
|
|
||||||
// total: 总记录数
|
|
||||||
// page: 当前页码
|
|
||||||
// pageSize: 每页大小
|
|
||||||
// message: 响应消息(可选,如果为空则使用默认消息 "success")
|
|
||||||
func (h *Handler) SuccessPage(list interface{}, total int64, page, pageSize int, message ...string) {
|
|
||||||
msg := "success"
|
|
||||||
if len(message) > 0 && message[0] != "" {
|
|
||||||
msg = message[0]
|
|
||||||
}
|
|
||||||
|
|
||||||
pageData := &PageData{
|
|
||||||
List: list,
|
|
||||||
Total: total,
|
|
||||||
Page: page,
|
|
||||||
PageSize: pageSize,
|
|
||||||
}
|
|
||||||
|
|
||||||
writeJSON(h.w, http.StatusOK, 0, msg, pageData)
|
|
||||||
}
|
|
||||||
|
|
||||||
// ========== 请求解析方法(黑盒模式) ==========
|
|
||||||
|
|
||||||
// ParseJSON 解析JSON请求体
|
|
||||||
// v: 目标结构体指针
|
|
||||||
func (h *Handler) ParseJSON(v interface{}) error {
|
|
||||||
body, err := io.ReadAll(h.r.Body)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
defer h.r.Body.Close()
|
|
||||||
|
|
||||||
if len(body) == 0 {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
return json.Unmarshal(body, v)
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetQuery 获取查询参数
|
|
||||||
// key: 参数名
|
|
||||||
// defaultValue: 默认值
|
|
||||||
func (h *Handler) GetQuery(key, defaultValue string) string {
|
|
||||||
value := h.r.URL.Query().Get(key)
|
|
||||||
if value == "" {
|
|
||||||
return defaultValue
|
|
||||||
}
|
|
||||||
return value
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetQueryInt 获取整数查询参数
|
|
||||||
// key: 参数名
|
|
||||||
// defaultValue: 默认值
|
|
||||||
func (h *Handler) GetQueryInt(key string, defaultValue int) int {
|
|
||||||
value := h.r.URL.Query().Get(key)
|
|
||||||
if value == "" {
|
|
||||||
return defaultValue
|
|
||||||
}
|
|
||||||
|
|
||||||
intValue, err := strconv.Atoi(value)
|
|
||||||
if err != nil {
|
|
||||||
return defaultValue
|
|
||||||
}
|
|
||||||
|
|
||||||
return intValue
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetQueryInt64 获取int64查询参数
|
|
||||||
func (h *Handler) GetQueryInt64(key string, defaultValue int64) int64 {
|
|
||||||
value := h.r.URL.Query().Get(key)
|
|
||||||
if value == "" {
|
|
||||||
return defaultValue
|
|
||||||
}
|
|
||||||
|
|
||||||
intValue, err := strconv.ParseInt(value, 10, 64)
|
|
||||||
if err != nil {
|
|
||||||
return defaultValue
|
|
||||||
}
|
|
||||||
|
|
||||||
return intValue
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetQueryBool 获取布尔查询参数
|
|
||||||
func (h *Handler) GetQueryBool(key string, defaultValue bool) bool {
|
|
||||||
value := h.r.URL.Query().Get(key)
|
|
||||||
if value == "" {
|
|
||||||
return defaultValue
|
|
||||||
}
|
|
||||||
|
|
||||||
boolValue, err := strconv.ParseBool(value)
|
|
||||||
if err != nil {
|
|
||||||
return defaultValue
|
|
||||||
}
|
|
||||||
|
|
||||||
return boolValue
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetQueryFloat64 获取float64查询参数
|
|
||||||
func (h *Handler) GetQueryFloat64(key string, defaultValue float64) float64 {
|
|
||||||
value := h.r.URL.Query().Get(key)
|
|
||||||
if value == "" {
|
|
||||||
return defaultValue
|
|
||||||
}
|
|
||||||
|
|
||||||
floatValue, err := strconv.ParseFloat(value, 64)
|
|
||||||
if err != nil {
|
|
||||||
return defaultValue
|
|
||||||
}
|
|
||||||
|
|
||||||
return floatValue
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetFormValue 获取表单值
|
|
||||||
func (h *Handler) GetFormValue(key, defaultValue string) string {
|
|
||||||
value := h.r.FormValue(key)
|
|
||||||
if value == "" {
|
|
||||||
return defaultValue
|
|
||||||
}
|
|
||||||
return value
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetFormInt 获取表单整数
|
|
||||||
func (h *Handler) GetFormInt(key string, defaultValue int) int {
|
|
||||||
value := h.r.FormValue(key)
|
|
||||||
if value == "" {
|
|
||||||
return defaultValue
|
|
||||||
}
|
|
||||||
|
|
||||||
intValue, err := strconv.Atoi(value)
|
|
||||||
if err != nil {
|
|
||||||
return defaultValue
|
|
||||||
}
|
|
||||||
|
|
||||||
return intValue
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetFormInt64 获取表单int64
|
|
||||||
func (h *Handler) GetFormInt64(key string, defaultValue int64) int64 {
|
|
||||||
value := h.r.FormValue(key)
|
|
||||||
if value == "" {
|
|
||||||
return defaultValue
|
|
||||||
}
|
|
||||||
|
|
||||||
intValue, err := strconv.ParseInt(value, 10, 64)
|
|
||||||
if err != nil {
|
|
||||||
return defaultValue
|
|
||||||
}
|
|
||||||
|
|
||||||
return intValue
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetFormBool 获取表单布尔值
|
|
||||||
func (h *Handler) GetFormBool(key string, defaultValue bool) bool {
|
|
||||||
value := h.r.FormValue(key)
|
|
||||||
if value == "" {
|
|
||||||
return defaultValue
|
|
||||||
}
|
|
||||||
|
|
||||||
boolValue, err := strconv.ParseBool(value)
|
|
||||||
if err != nil {
|
|
||||||
return defaultValue
|
|
||||||
}
|
|
||||||
|
|
||||||
return boolValue
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetHeader 获取请求头
|
|
||||||
func (h *Handler) GetHeader(key, defaultValue string) string {
|
|
||||||
value := h.r.Header.Get(key)
|
|
||||||
if value == "" {
|
|
||||||
return defaultValue
|
|
||||||
}
|
|
||||||
return value
|
|
||||||
}
|
|
||||||
|
|
||||||
// ParsePaginationRequest 从请求中解析分页参数
|
|
||||||
// 支持从查询参数和form表单中解析
|
|
||||||
// 优先级:查询参数 > form表单
|
|
||||||
func (h *Handler) ParsePaginationRequest() *PaginationRequest {
|
|
||||||
return ParsePaginationRequest(h.r)
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetTimezone 从请求的context中获取时区
|
|
||||||
// 如果使用了middleware.Timezone中间件,可以从context中获取时区信息
|
|
||||||
// 如果未设置,返回默认时区 AsiaShanghai
|
|
||||||
func (h *Handler) GetTimezone() string {
|
|
||||||
return middleware.GetTimezoneFromContext(h.r.Context())
|
|
||||||
}
|
|
||||||
|
|
||||||
// HandleFunc 将Handler函数转换为标准的http.HandlerFunc
|
|
||||||
// 这样可以将Handler函数直接用于http.HandleFunc
|
|
||||||
// 示例:
|
|
||||||
//
|
|
||||||
// http.HandleFunc("/users", http.HandleFunc(func(h *http.Handler) {
|
|
||||||
// h.Success(data)
|
|
||||||
// }))
|
|
||||||
func HandleFunc(fn func(*Handler)) http.HandlerFunc {
|
|
||||||
return func(w http.ResponseWriter, r *http.Request) {
|
|
||||||
h := NewHandler(w, r)
|
|
||||||
fn(h)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
108
http/request.go
108
http/request.go
@@ -1,46 +1,20 @@
|
|||||||
package http
|
package http
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"io"
|
||||||
"net/http"
|
"net/http"
|
||||||
"strconv"
|
|
||||||
|
"git.toowon.com/jimmy/go-common/middleware"
|
||||||
|
"git.toowon.com/jimmy/go-common/tools"
|
||||||
)
|
)
|
||||||
|
|
||||||
// getQueryInt 获取整数查询参数(内部方法,供ParsePaginationRequest使用)
|
|
||||||
func getQueryInt(r *http.Request, key string, defaultValue int) int {
|
|
||||||
value := r.URL.Query().Get(key)
|
|
||||||
if value == "" {
|
|
||||||
return defaultValue
|
|
||||||
}
|
|
||||||
|
|
||||||
intValue, err := strconv.Atoi(value)
|
|
||||||
if err != nil {
|
|
||||||
return defaultValue
|
|
||||||
}
|
|
||||||
|
|
||||||
return intValue
|
|
||||||
}
|
|
||||||
|
|
||||||
// getFormInt 获取表单整数(内部方法,供ParsePaginationRequest使用)
|
|
||||||
func getFormInt(r *http.Request, key string, defaultValue int) int {
|
|
||||||
value := r.FormValue(key)
|
|
||||||
if value == "" {
|
|
||||||
return defaultValue
|
|
||||||
}
|
|
||||||
|
|
||||||
intValue, err := strconv.Atoi(value)
|
|
||||||
if err != nil {
|
|
||||||
return defaultValue
|
|
||||||
}
|
|
||||||
|
|
||||||
return intValue
|
|
||||||
}
|
|
||||||
|
|
||||||
// PaginationRequest 分页请求结构
|
// PaginationRequest 分页请求结构
|
||||||
// 支持从JSON和form中解析分页参数
|
// 支持从JSON和form中解析分页参数
|
||||||
type PaginationRequest struct {
|
type PaginationRequest struct {
|
||||||
Page int `json:"page" form:"page"` // 页码,默认1
|
Page int `json:"page" form:"page"` // 页码,默认1
|
||||||
Size int `json:"size" form:"size"` // 每页数量(兼容旧版本)
|
PageSize int `json:"page_size" form:"page_size"` // 每页数量
|
||||||
PageSize int `json:"page_size" form:"page_size"` // 每页数量(推荐使用)
|
Keyword string `json:"keyword" form:"keyword"` // 关键字
|
||||||
}
|
}
|
||||||
|
|
||||||
// GetPage 获取页码,如果未设置则返回默认值1
|
// GetPage 获取页码,如果未设置则返回默认值1
|
||||||
@@ -51,13 +25,9 @@ func (p *PaginationRequest) GetPage() int {
|
|||||||
return p.Page
|
return p.Page
|
||||||
}
|
}
|
||||||
|
|
||||||
// GetSize 获取每页数量,如果未设置则返回默认值20,最大限制100
|
// GetPageSize 获取每页数量,如果未设置则返回默认值20,最大限制100
|
||||||
// 优先使用 PageSize 字段,如果未设置则使用 Size 字段(兼容旧版本)
|
func (p *PaginationRequest) GetPageSize() int {
|
||||||
func (p *PaginationRequest) GetSize() int {
|
|
||||||
size := p.PageSize
|
size := p.PageSize
|
||||||
if size <= 0 {
|
|
||||||
size = p.Size // 兼容旧版本的 Size 字段
|
|
||||||
}
|
|
||||||
if size <= 0 {
|
if size <= 0 {
|
||||||
return 20 // 默认20条
|
return 20 // 默认20条
|
||||||
}
|
}
|
||||||
@@ -69,22 +39,20 @@ func (p *PaginationRequest) GetSize() int {
|
|||||||
|
|
||||||
// GetOffset 计算数据库查询的偏移量
|
// GetOffset 计算数据库查询的偏移量
|
||||||
func (p *PaginationRequest) GetOffset() int {
|
func (p *PaginationRequest) GetOffset() int {
|
||||||
return (p.GetPage() - 1) * p.GetSize()
|
return (p.GetPage() - 1) * p.GetPageSize()
|
||||||
}
|
}
|
||||||
|
|
||||||
// getPaginationFromQuery 从查询参数获取分页参数(内部辅助方法)
|
// getPaginationFromQuery 从查询参数获取分页参数(内部辅助方法)
|
||||||
func getPaginationFromQuery(r *http.Request) (page, size, pageSize int) {
|
func getPaginationFromQuery(r *http.Request) (page, pageSize int) {
|
||||||
page = getQueryInt(r, "page", 0)
|
page = tools.ConvertInt(r.URL.Query().Get("page"), 0)
|
||||||
size = getQueryInt(r, "size", 0)
|
pageSize = tools.ConvertInt(r.URL.Query().Get("page_size"), 0)
|
||||||
pageSize = getQueryInt(r, "page_size", 0)
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// getPaginationFromForm 从form表单获取分页参数(内部辅助方法)
|
// getPaginationFromForm 从form表单获取分页参数(内部辅助方法)
|
||||||
func getPaginationFromForm(r *http.Request) (page, size, pageSize int) {
|
func getPaginationFromForm(r *http.Request) (page, pageSize int) {
|
||||||
page = getFormInt(r, "page", 0)
|
page = tools.ConvertInt(r.FormValue("page"), 0)
|
||||||
size = getFormInt(r, "size", 0)
|
pageSize = tools.ConvertInt(r.FormValue("page_size"), 0)
|
||||||
pageSize = getFormInt(r, "page_size", 0)
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -96,17 +64,14 @@ func ParsePaginationRequest(r *http.Request) *PaginationRequest {
|
|||||||
req := &PaginationRequest{}
|
req := &PaginationRequest{}
|
||||||
|
|
||||||
// 1. 从查询参数解析(优先级最高)
|
// 1. 从查询参数解析(优先级最高)
|
||||||
req.Page, req.Size, req.PageSize = getPaginationFromQuery(r)
|
req.Page, req.PageSize = getPaginationFromQuery(r)
|
||||||
|
|
||||||
// 2. 如果查询参数中没有,尝试从form表单解析
|
// 2. 如果查询参数中没有,尝试从form表单解析
|
||||||
if req.Page == 0 || (req.Size == 0 && req.PageSize == 0) {
|
if req.Page == 0 || req.PageSize == 0 {
|
||||||
page, size, pageSize := getPaginationFromForm(r)
|
page, pageSize := getPaginationFromForm(r)
|
||||||
if req.Page == 0 && page != 0 {
|
if req.Page == 0 && page != 0 {
|
||||||
req.Page = page
|
req.Page = page
|
||||||
}
|
}
|
||||||
if req.Size == 0 && size != 0 {
|
|
||||||
req.Size = size
|
|
||||||
}
|
|
||||||
if req.PageSize == 0 && pageSize != 0 {
|
if req.PageSize == 0 && pageSize != 0 {
|
||||||
req.PageSize = pageSize
|
req.PageSize = pageSize
|
||||||
}
|
}
|
||||||
@@ -114,3 +79,36 @@ func ParsePaginationRequest(r *http.Request) *PaginationRequest {
|
|||||||
|
|
||||||
return req
|
return req
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ParseJSON 解析JSON请求体(公共方法)
|
||||||
|
// r: HTTP请求
|
||||||
|
// v: 目标结构体指针
|
||||||
|
func ParseJSON(r *http.Request, v interface{}) error {
|
||||||
|
body, err := io.ReadAll(r.Body)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
defer r.Body.Close()
|
||||||
|
|
||||||
|
if len(body) == 0 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
return json.Unmarshal(body, v)
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetTimezone 从请求的context中获取时区(公共方法)
|
||||||
|
// r: HTTP请求
|
||||||
|
// 如果使用了middleware.Timezone中间件,可以从context中获取时区信息
|
||||||
|
// 如果未设置,返回默认时区 AsiaShanghai
|
||||||
|
func GetTimezone(r *http.Request) string {
|
||||||
|
return middleware.GetTimezoneFromContext(r.Context())
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetLanguage 从请求的context中获取语言(公共方法)
|
||||||
|
// r: HTTP请求
|
||||||
|
// 如果使用了middleware.Language中间件,可以从context中获取语言信息
|
||||||
|
// 如果未设置,返回默认语言 zh-CN
|
||||||
|
func GetLanguage(r *http.Request) string {
|
||||||
|
return middleware.GetLanguageFromContext(r.Context())
|
||||||
|
}
|
||||||
|
|||||||
@@ -30,7 +30,7 @@ type PageData struct {
|
|||||||
PageSize int `json:"pageSize"` // 每页大小
|
PageSize int `json:"pageSize"` // 每页大小
|
||||||
}
|
}
|
||||||
|
|
||||||
// writeJSON 写入JSON响应(内部方法)
|
// writeJSON 写入JSON响应(公共方法)
|
||||||
// httpCode: HTTP状态码(200表示正常,500表示系统错误等)
|
// httpCode: HTTP状态码(200表示正常,500表示系统错误等)
|
||||||
// code: 业务状态码(0表示成功,非0表示业务错误)
|
// code: 业务状态码(0表示成功,非0表示业务错误)
|
||||||
// message: 响应消息
|
// message: 响应消息
|
||||||
@@ -48,3 +48,58 @@ func writeJSON(w http.ResponseWriter, httpCode, code int, message string, data i
|
|||||||
|
|
||||||
json.NewEncoder(w).Encode(response)
|
json.NewEncoder(w).Encode(response)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Success 成功响应(公共方法)
|
||||||
|
// w: ResponseWriter
|
||||||
|
// data: 响应数据,可以为nil
|
||||||
|
// message: 响应消息(可选),如果为空则使用默认消息 "success"
|
||||||
|
//
|
||||||
|
// 使用方式:
|
||||||
|
//
|
||||||
|
// Success(w, data) // 只有数据,使用默认消息 "success"
|
||||||
|
// Success(w, data, "查询成功") // 数据+消息
|
||||||
|
func Success(w http.ResponseWriter, data interface{}, message ...string) {
|
||||||
|
msg := "success"
|
||||||
|
if len(message) > 0 && message[0] != "" {
|
||||||
|
msg = message[0]
|
||||||
|
}
|
||||||
|
writeJSON(w, http.StatusOK, 0, msg, data)
|
||||||
|
}
|
||||||
|
|
||||||
|
// SuccessPage 分页成功响应(公共方法)
|
||||||
|
// w: ResponseWriter
|
||||||
|
// list: 数据列表
|
||||||
|
// total: 总记录数
|
||||||
|
// page: 当前页码
|
||||||
|
// pageSize: 每页大小
|
||||||
|
// message: 响应消息(可选),如果为空则使用默认消息 "success"
|
||||||
|
func SuccessPage(w http.ResponseWriter, list interface{}, total int64, page, pageSize int, message ...string) {
|
||||||
|
msg := "success"
|
||||||
|
if len(message) > 0 && message[0] != "" {
|
||||||
|
msg = message[0]
|
||||||
|
}
|
||||||
|
|
||||||
|
pageData := &PageData{
|
||||||
|
List: list,
|
||||||
|
Total: total,
|
||||||
|
Page: page,
|
||||||
|
PageSize: pageSize,
|
||||||
|
}
|
||||||
|
|
||||||
|
writeJSON(w, http.StatusOK, 0, msg, pageData)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Error 错误响应(公共方法)
|
||||||
|
// w: ResponseWriter
|
||||||
|
// code: 业务错误码,非0表示业务错误
|
||||||
|
// message: 错误消息
|
||||||
|
func Error(w http.ResponseWriter, code int, message string) {
|
||||||
|
writeJSON(w, http.StatusOK, code, message, nil)
|
||||||
|
}
|
||||||
|
|
||||||
|
// SystemError 系统错误响应(返回HTTP 500)(公共方法)
|
||||||
|
// w: ResponseWriter
|
||||||
|
// message: 错误消息
|
||||||
|
func SystemError(w http.ResponseWriter, message string) {
|
||||||
|
writeJSON(w, http.StatusInternalServerError, 500, message, nil)
|
||||||
|
}
|
||||||
|
|||||||
286
i18n/i18n.go
Normal file
286
i18n/i18n.go
Normal file
@@ -0,0 +1,286 @@
|
|||||||
|
package i18n
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
|
)
|
||||||
|
|
||||||
|
// MessageInfo 消息信息结构
|
||||||
|
// 包含业务错误码和消息内容
|
||||||
|
type MessageInfo struct {
|
||||||
|
Code int `json:"code"` // 业务错误码
|
||||||
|
Message string `json:"message"` // 消息内容
|
||||||
|
}
|
||||||
|
|
||||||
|
// I18n 国际化工具
|
||||||
|
// 支持多语言内容管理,通过语言代码和消息代码获取对应语言的内容
|
||||||
|
type I18n struct {
|
||||||
|
messages map[string]map[string]MessageInfo // 存储格式:messages[语言][code] = MessageInfo
|
||||||
|
defaultLang string // 默认语言代码
|
||||||
|
mu sync.RWMutex // 读写锁,保证并发安全
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewI18n 创建国际化工具实例
|
||||||
|
// defaultLang: 默认语言代码(如 "zh-CN", "en-US"),当指定语言不存在时使用
|
||||||
|
func NewI18n(defaultLang string) *I18n {
|
||||||
|
return &I18n{
|
||||||
|
messages: make(map[string]map[string]MessageInfo),
|
||||||
|
defaultLang: defaultLang,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// LoadFromFile 从单个语言文件加载内容
|
||||||
|
// filePath: 语言文件路径(JSON格式)
|
||||||
|
// lang: 语言代码(如 "zh-CN", "en-US")
|
||||||
|
//
|
||||||
|
// 文件格式示例(zh-CN.json):
|
||||||
|
//
|
||||||
|
// {
|
||||||
|
// "user.not_found": {
|
||||||
|
// "code": 1001,
|
||||||
|
// "message": "用户不存在"
|
||||||
|
// },
|
||||||
|
// "user.login_success": {
|
||||||
|
// "code": 0,
|
||||||
|
// "message": "登录成功"
|
||||||
|
// },
|
||||||
|
// "user.welcome": {
|
||||||
|
// "code": 0,
|
||||||
|
// "message": "欢迎,%s"
|
||||||
|
// }
|
||||||
|
// }
|
||||||
|
func (i *I18n) LoadFromFile(filePath, lang string) error {
|
||||||
|
data, err := os.ReadFile(filePath)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("failed to read file %s: %w", filePath, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
var messages map[string]MessageInfo
|
||||||
|
if err := json.Unmarshal(data, &messages); err != nil {
|
||||||
|
return fmt.Errorf("failed to parse JSON file %s: %w", filePath, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
i.mu.Lock()
|
||||||
|
defer i.mu.Unlock()
|
||||||
|
|
||||||
|
if i.messages[lang] == nil {
|
||||||
|
i.messages[lang] = make(map[string]MessageInfo)
|
||||||
|
}
|
||||||
|
|
||||||
|
// 合并到现有消息中(如果key已存在会被覆盖)
|
||||||
|
for k, v := range messages {
|
||||||
|
i.messages[lang][k] = v
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// LoadFromDir 从目录加载多个语言文件
|
||||||
|
// dirPath: 语言文件目录路径
|
||||||
|
// 文件命名规则:{语言代码}.json(如 zh-CN.json, en-US.json)
|
||||||
|
//
|
||||||
|
// 示例目录结构:
|
||||||
|
//
|
||||||
|
// locales/
|
||||||
|
// zh-CN.json
|
||||||
|
// en-US.json
|
||||||
|
// ja-JP.json
|
||||||
|
func (i *I18n) LoadFromDir(dirPath string) error {
|
||||||
|
entries, err := os.ReadDir(dirPath)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("failed to read directory %s: %w", dirPath, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, entry := range entries {
|
||||||
|
if entry.IsDir() {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
// 只处理 .json 文件
|
||||||
|
if !strings.HasSuffix(entry.Name(), ".json") {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
// 从文件名提取语言代码(去掉 .json 后缀)
|
||||||
|
lang := strings.TrimSuffix(entry.Name(), ".json")
|
||||||
|
filePath := filepath.Join(dirPath, entry.Name())
|
||||||
|
|
||||||
|
if err := i.LoadFromFile(filePath, lang); err != nil {
|
||||||
|
return fmt.Errorf("failed to load language file %s: %w", filePath, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// LoadFromMap 从map加载语言内容(用于测试或动态加载)
|
||||||
|
// lang: 语言代码
|
||||||
|
// messages: 消息map,key为消息代码,value为消息信息
|
||||||
|
//
|
||||||
|
// 示例:
|
||||||
|
//
|
||||||
|
// i18n.LoadFromMap("zh-CN", map[string]MessageInfo{
|
||||||
|
// "user.not_found": {Code: 1001, Message: "用户不存在"},
|
||||||
|
// "user.login_success": {Code: 0, Message: "登录成功"},
|
||||||
|
// })
|
||||||
|
func (i *I18n) LoadFromMap(lang string, messages map[string]MessageInfo) {
|
||||||
|
i.mu.Lock()
|
||||||
|
defer i.mu.Unlock()
|
||||||
|
|
||||||
|
if i.messages[lang] == nil {
|
||||||
|
i.messages[lang] = make(map[string]MessageInfo)
|
||||||
|
}
|
||||||
|
|
||||||
|
// 合并到现有消息中
|
||||||
|
for k, v := range messages {
|
||||||
|
i.messages[lang][k] = v
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetMessage 获取指定语言和代码的消息内容
|
||||||
|
// lang: 语言代码(如 "zh-CN", "en-US")
|
||||||
|
// code: 消息代码(如 "user.not_found")
|
||||||
|
// args: 可选参数,用于格式化消息(类似 fmt.Sprintf)
|
||||||
|
//
|
||||||
|
// 返回逻辑:
|
||||||
|
// 1. 如果指定语言存在该code,返回对应内容
|
||||||
|
// 2. 如果指定语言不存在,尝试使用默认语言
|
||||||
|
// 3. 如果默认语言也不存在,返回code本身(作为fallback)
|
||||||
|
//
|
||||||
|
// 示例:
|
||||||
|
//
|
||||||
|
// msg := i18n.GetMessage("zh-CN", "user.not_found")
|
||||||
|
// // 返回: "用户不存在"
|
||||||
|
//
|
||||||
|
// msg := i18n.GetMessage("zh-CN", "user.welcome", "Alice")
|
||||||
|
// // 如果消息内容是 "欢迎,%s",返回: "欢迎,Alice"
|
||||||
|
func (i *I18n) GetMessage(lang, code string, args ...interface{}) string {
|
||||||
|
info := i.GetMessageInfo(lang, code, args...)
|
||||||
|
return info.Message
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetMessageInfo 获取指定语言和代码的完整消息信息(包含业务code)
|
||||||
|
// lang: 语言代码(如 "zh-CN", "en-US")
|
||||||
|
// code: 消息代码(如 "user.not_found")
|
||||||
|
// args: 可选参数,用于格式化消息(类似 fmt.Sprintf)
|
||||||
|
//
|
||||||
|
// 返回逻辑:
|
||||||
|
// 1. 如果指定语言存在该code,返回对应的MessageInfo
|
||||||
|
// 2. 如果指定语言不存在,尝试使用默认语言
|
||||||
|
// 3. 如果默认语言也不存在,返回code本身作为message,code为0
|
||||||
|
//
|
||||||
|
// 示例:
|
||||||
|
//
|
||||||
|
// info := i18n.GetMessageInfo("zh-CN", "user.not_found")
|
||||||
|
// // 返回: MessageInfo{Code: 1001, Message: "用户不存在"}
|
||||||
|
func (i *I18n) GetMessageInfo(lang, code string, args ...interface{}) MessageInfo {
|
||||||
|
i.mu.RLock()
|
||||||
|
defer i.mu.RUnlock()
|
||||||
|
|
||||||
|
// 尝试从指定语言获取
|
||||||
|
if messages, ok := i.messages[lang]; ok {
|
||||||
|
if msgInfo, ok := messages[code]; ok {
|
||||||
|
// 格式化消息内容
|
||||||
|
msgInfo.Message = i.formatMessage(msgInfo.Message, args...)
|
||||||
|
return msgInfo
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 如果指定语言不存在该code,尝试使用默认语言
|
||||||
|
if i.defaultLang != "" && i.defaultLang != lang {
|
||||||
|
if messages, ok := i.messages[i.defaultLang]; ok {
|
||||||
|
if msgInfo, ok := messages[code]; ok {
|
||||||
|
// 格式化消息内容
|
||||||
|
msgInfo.Message = i.formatMessage(msgInfo.Message, args...)
|
||||||
|
return msgInfo
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 如果都不存在,返回code本身作为message,code为0(作为fallback)
|
||||||
|
return MessageInfo{
|
||||||
|
Code: 0,
|
||||||
|
Message: code,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// formatMessage 格式化消息(支持参数替换)
|
||||||
|
// 如果消息中包含 %s, %d 等格式化占位符,使用 args 进行替换
|
||||||
|
func (i *I18n) formatMessage(msg string, args ...interface{}) string {
|
||||||
|
if len(args) == 0 {
|
||||||
|
return msg
|
||||||
|
}
|
||||||
|
|
||||||
|
// 检查消息中是否包含格式化占位符
|
||||||
|
if strings.Contains(msg, "%") {
|
||||||
|
return fmt.Sprintf(msg, args...)
|
||||||
|
}
|
||||||
|
|
||||||
|
return msg
|
||||||
|
}
|
||||||
|
|
||||||
|
// SetDefaultLang 设置默认语言
|
||||||
|
// lang: 默认语言代码
|
||||||
|
func (i *I18n) SetDefaultLang(lang string) {
|
||||||
|
i.mu.Lock()
|
||||||
|
defer i.mu.Unlock()
|
||||||
|
i.defaultLang = lang
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetDefaultLang 获取默认语言代码
|
||||||
|
func (i *I18n) GetDefaultLang() string {
|
||||||
|
i.mu.RLock()
|
||||||
|
defer i.mu.RUnlock()
|
||||||
|
return i.defaultLang
|
||||||
|
}
|
||||||
|
|
||||||
|
// HasLang 检查是否已加载指定语言
|
||||||
|
// lang: 语言代码
|
||||||
|
func (i *I18n) HasLang(lang string) bool {
|
||||||
|
i.mu.RLock()
|
||||||
|
defer i.mu.RUnlock()
|
||||||
|
_, ok := i.messages[lang]
|
||||||
|
return ok
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetSupportedLangs 获取所有已加载的语言代码列表
|
||||||
|
func (i *I18n) GetSupportedLangs() []string {
|
||||||
|
i.mu.RLock()
|
||||||
|
defer i.mu.RUnlock()
|
||||||
|
|
||||||
|
langs := make([]string, 0, len(i.messages))
|
||||||
|
for lang := range i.messages {
|
||||||
|
langs = append(langs, lang)
|
||||||
|
}
|
||||||
|
|
||||||
|
return langs
|
||||||
|
}
|
||||||
|
|
||||||
|
// ReloadFromFile 重新加载指定语言文件
|
||||||
|
// filePath: 语言文件路径
|
||||||
|
// lang: 语言代码
|
||||||
|
func (i *I18n) ReloadFromFile(filePath, lang string) error {
|
||||||
|
// 先清除该语言的所有消息
|
||||||
|
i.mu.Lock()
|
||||||
|
delete(i.messages, lang)
|
||||||
|
i.mu.Unlock()
|
||||||
|
|
||||||
|
// 重新加载
|
||||||
|
return i.LoadFromFile(filePath, lang)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ReloadFromDir 重新加载目录中的所有语言文件
|
||||||
|
// dirPath: 语言文件目录路径
|
||||||
|
func (i *I18n) ReloadFromDir(dirPath string) error {
|
||||||
|
// 先清除所有消息
|
||||||
|
i.mu.Lock()
|
||||||
|
i.messages = make(map[string]map[string]MessageInfo)
|
||||||
|
i.mu.Unlock()
|
||||||
|
|
||||||
|
// 重新加载
|
||||||
|
return i.LoadFromDir(dirPath)
|
||||||
|
}
|
||||||
102
middleware/language.go
Normal file
102
middleware/language.go
Normal file
@@ -0,0 +1,102 @@
|
|||||||
|
package middleware
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"net/http"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
// LanguageKey context中存储语言的key
|
||||||
|
type languageKey struct{}
|
||||||
|
|
||||||
|
// LanguageHeaderName 语言请求头名称
|
||||||
|
const LanguageHeaderName = "X-Language"
|
||||||
|
|
||||||
|
// AcceptLanguageHeaderName Accept-Language 请求头名称
|
||||||
|
const AcceptLanguageHeaderName = "Accept-Language"
|
||||||
|
|
||||||
|
// DefaultLanguage 默认语言
|
||||||
|
const DefaultLanguage = "zh-CN"
|
||||||
|
|
||||||
|
// GetLanguageFromContext 从context中获取语言
|
||||||
|
func GetLanguageFromContext(ctx context.Context) string {
|
||||||
|
if lang, ok := ctx.Value(languageKey{}).(string); ok && lang != "" {
|
||||||
|
return lang
|
||||||
|
}
|
||||||
|
return DefaultLanguage
|
||||||
|
}
|
||||||
|
|
||||||
|
// Language 语言处理中间件
|
||||||
|
// 从请求头 X-Language 或 Accept-Language 读取语言信息,如果未传递则使用默认语言 zh-CN
|
||||||
|
// 语言信息会存储到context中,可以通过 GetLanguageFromContext 获取
|
||||||
|
func Language(next http.Handler) http.Handler {
|
||||||
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
// 1. 优先从 X-Language 请求头获取(显式指定)
|
||||||
|
lang := r.Header.Get(LanguageHeaderName)
|
||||||
|
|
||||||
|
// 2. 如果未设置,从 Accept-Language 请求头解析
|
||||||
|
if lang == "" {
|
||||||
|
acceptLang := r.Header.Get(AcceptLanguageHeaderName)
|
||||||
|
if acceptLang != "" {
|
||||||
|
lang = parseAcceptLanguage(acceptLang)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 3. 如果都未设置,使用默认语言
|
||||||
|
if lang == "" {
|
||||||
|
lang = DefaultLanguage
|
||||||
|
}
|
||||||
|
|
||||||
|
// 将语言存储到context中
|
||||||
|
ctx := context.WithValue(r.Context(), languageKey{}, lang)
|
||||||
|
next.ServeHTTP(w, r.WithContext(ctx))
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// LanguageWithDefault 语言处理中间件(可自定义默认语言)
|
||||||
|
// defaultLanguage: 默认语言,如果未指定则使用 zh-CN
|
||||||
|
func LanguageWithDefault(defaultLanguage string) func(http.Handler) http.Handler {
|
||||||
|
return func(next http.Handler) http.Handler {
|
||||||
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
// 1. 优先从 X-Language 请求头获取(显式指定)
|
||||||
|
lang := r.Header.Get(LanguageHeaderName)
|
||||||
|
|
||||||
|
// 2. 如果未设置,从 Accept-Language 请求头解析
|
||||||
|
if lang == "" {
|
||||||
|
acceptLang := r.Header.Get(AcceptLanguageHeaderName)
|
||||||
|
if acceptLang != "" {
|
||||||
|
lang = parseAcceptLanguage(acceptLang)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 3. 如果都未设置,使用指定的默认语言
|
||||||
|
if lang == "" {
|
||||||
|
lang = defaultLanguage
|
||||||
|
}
|
||||||
|
|
||||||
|
// 将语言存储到context中
|
||||||
|
ctx := context.WithValue(r.Context(), languageKey{}, lang)
|
||||||
|
next.ServeHTTP(w, r.WithContext(ctx))
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// parseAcceptLanguage 解析 Accept-Language 请求头
|
||||||
|
// 返回第一个语言代码(去掉权重信息)
|
||||||
|
func parseAcceptLanguage(acceptLang string) string {
|
||||||
|
if acceptLang == "" {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
|
||||||
|
// 分割语言列表
|
||||||
|
parts := strings.Split(acceptLang, ",")
|
||||||
|
if len(parts) == 0 {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
|
||||||
|
// 取第一个语言代码,去掉权重信息(如 ";q=0.9")
|
||||||
|
firstLang := strings.Split(parts[0], ";")[0]
|
||||||
|
firstLang = strings.TrimSpace(firstLang)
|
||||||
|
|
||||||
|
return firstLang
|
||||||
|
}
|
||||||
@@ -4,7 +4,7 @@ import (
|
|||||||
"context"
|
"context"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
|
||||||
"git.toowon.com/jimmy/go-common/datetime"
|
"git.toowon.com/jimmy/go-common/tools"
|
||||||
)
|
)
|
||||||
|
|
||||||
// TimezoneKey context中存储时区的key
|
// TimezoneKey context中存储时区的key
|
||||||
@@ -14,7 +14,7 @@ type timezoneKey struct{}
|
|||||||
const TimezoneHeaderName = "X-Timezone"
|
const TimezoneHeaderName = "X-Timezone"
|
||||||
|
|
||||||
// DefaultTimezone 默认时区
|
// DefaultTimezone 默认时区
|
||||||
const DefaultTimezone = datetime.AsiaShanghai
|
const DefaultTimezone = tools.AsiaShanghai
|
||||||
|
|
||||||
// GetTimezoneFromContext 从context中获取时区
|
// GetTimezoneFromContext 从context中获取时区
|
||||||
func GetTimezoneFromContext(ctx context.Context) string {
|
func GetTimezoneFromContext(ctx context.Context) string {
|
||||||
@@ -38,7 +38,7 @@ func Timezone(next http.Handler) http.Handler {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// 验证时区是否有效
|
// 验证时区是否有效
|
||||||
if _, err := datetime.GetLocation(timezone); err != nil {
|
if _, err := tools.GetLocation(timezone); err != nil {
|
||||||
// 如果时区无效,使用默认时区
|
// 如果时区无效,使用默认时区
|
||||||
timezone = DefaultTimezone
|
timezone = DefaultTimezone
|
||||||
}
|
}
|
||||||
@@ -53,7 +53,7 @@ func Timezone(next http.Handler) http.Handler {
|
|||||||
// defaultTimezone: 默认时区,如果未指定则使用 AsiaShanghai
|
// defaultTimezone: 默认时区,如果未指定则使用 AsiaShanghai
|
||||||
func TimezoneWithDefault(defaultTimezone string) func(http.Handler) http.Handler {
|
func TimezoneWithDefault(defaultTimezone string) func(http.Handler) http.Handler {
|
||||||
// 验证默认时区是否有效
|
// 验证默认时区是否有效
|
||||||
if _, err := datetime.GetLocation(defaultTimezone); err != nil {
|
if _, err := tools.GetLocation(defaultTimezone); err != nil {
|
||||||
defaultTimezone = DefaultTimezone
|
defaultTimezone = DefaultTimezone
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -68,7 +68,7 @@ func TimezoneWithDefault(defaultTimezone string) func(http.Handler) http.Handler
|
|||||||
}
|
}
|
||||||
|
|
||||||
// 验证时区是否有效
|
// 验证时区是否有效
|
||||||
if _, err := datetime.GetLocation(timezone); err != nil {
|
if _, err := tools.GetLocation(timezone); err != nil {
|
||||||
// 如果时区无效,使用默认时区
|
// 如果时区无效,使用默认时区
|
||||||
timezone = defaultTimezone
|
timezone = defaultTimezone
|
||||||
}
|
}
|
||||||
@@ -79,4 +79,3 @@ func TimezoneWithDefault(defaultTimezone string) func(http.Handler) http.Handler
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -34,14 +34,14 @@ func RunMigrationsFromConfig(configFile, migrationsDir string) error {
|
|||||||
// RunMigrationsFromConfigWithCommand 从配置文件运行迁移(支持命令,黑盒模式)
|
// RunMigrationsFromConfigWithCommand 从配置文件运行迁移(支持命令,黑盒模式)
|
||||||
//
|
//
|
||||||
// 这是最简单的迁移方式,内部自动处理:
|
// 这是最简单的迁移方式,内部自动处理:
|
||||||
// - 配置加载(支持文件、环境变量、默认路径)
|
// - 配置加载(支持配置文件、默认路径)
|
||||||
// - 数据库连接(自动识别数据库类型)
|
// - 数据库连接(自动识别数据库类型)
|
||||||
// - 迁移文件加载和执行
|
// - 迁移文件加载和执行
|
||||||
//
|
//
|
||||||
// 参数:
|
// 参数:
|
||||||
// - configFile: 配置文件路径,支持:
|
// - configFile: 配置文件路径,支持:
|
||||||
// - 空字符串:自动查找(config.json, ../config.json)
|
// - 空字符串:自动查找(config.json, ../config.json)
|
||||||
// - 环境变量 DATABASE_URL:直接使用数据库URL
|
// - 相对路径或绝对路径:指定配置文件路径
|
||||||
// - migrationsDir: 迁移文件目录,支持:
|
// - migrationsDir: 迁移文件目录,支持:
|
||||||
// - 空字符串:使用默认目录 "migrations"
|
// - 空字符串:使用默认目录 "migrations"
|
||||||
// - 相对路径或绝对路径
|
// - 相对路径或绝对路径
|
||||||
@@ -57,9 +57,6 @@ func RunMigrationsFromConfig(configFile, migrationsDir string) error {
|
|||||||
//
|
//
|
||||||
// // 指定配置和迁移目录
|
// // 指定配置和迁移目录
|
||||||
// migration.RunMigrationsFromConfigWithCommand("config.json", "scripts/sql", "up")
|
// migration.RunMigrationsFromConfigWithCommand("config.json", "scripts/sql", "up")
|
||||||
//
|
|
||||||
// // 使用环境变量
|
|
||||||
// // DATABASE_URL="mysql://..." migration.RunMigrationsFromConfigWithCommand("", "migrations", "up")
|
|
||||||
func RunMigrationsFromConfigWithCommand(configFile, migrationsDir, command string) error {
|
func RunMigrationsFromConfigWithCommand(configFile, migrationsDir, command string) error {
|
||||||
// 加载配置
|
// 加载配置
|
||||||
cfg, err := loadConfigFromFileOrEnv(configFile)
|
cfg, err := loadConfigFromFileOrEnv(configFile)
|
||||||
@@ -78,8 +75,8 @@ func RunMigrationsFromConfigWithCommand(configFile, migrationsDir, command strin
|
|||||||
migrationsDir = "migrations"
|
migrationsDir = "migrations"
|
||||||
}
|
}
|
||||||
|
|
||||||
// 创建迁移器
|
// 创建迁移器(传入数据库类型,性能更好)
|
||||||
migrator := NewMigrator(db)
|
migrator := NewMigratorWithType(db, cfg.Database.Type)
|
||||||
|
|
||||||
// 加载迁移文件
|
// 加载迁移文件
|
||||||
migrations, err := LoadMigrationsFromFiles(migrationsDir, "*.sql")
|
migrations, err := LoadMigrationsFromFiles(migrationsDir, "*.sql")
|
||||||
@@ -122,22 +119,16 @@ func RunMigrationsFromConfigWithCommand(configFile, migrationsDir, command strin
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// loadConfigFromFileOrEnv 从文件或环境变量加载配置
|
// loadConfigFromFileOrEnv 从配置文件加载配置
|
||||||
|
// 支持指定配置文件路径,或自动查找默认路径
|
||||||
func loadConfigFromFileOrEnv(configFile string) (*config.Config, error) {
|
func loadConfigFromFileOrEnv(configFile string) (*config.Config, error) {
|
||||||
// 优先从环境变量加载
|
// 如果指定了配置文件路径,优先使用
|
||||||
if dbURL := os.Getenv("DATABASE_URL"); dbURL != "" {
|
|
||||||
return &config.Config{
|
|
||||||
Database: &config.DatabaseConfig{
|
|
||||||
DSN: dbURL,
|
|
||||||
},
|
|
||||||
}, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// 尝试从配置文件加载
|
|
||||||
if configFile != "" {
|
if configFile != "" {
|
||||||
if _, err := os.Stat(configFile); err == nil {
|
if _, err := os.Stat(configFile); err == nil {
|
||||||
return config.LoadFromFile(configFile)
|
return config.LoadFromFile(configFile)
|
||||||
}
|
}
|
||||||
|
// 如果指定的文件不存在,返回错误
|
||||||
|
return nil, fmt.Errorf("配置文件不存在: %s", configFile)
|
||||||
}
|
}
|
||||||
|
|
||||||
// 尝试默认路径
|
// 尝试默认路径
|
||||||
@@ -148,7 +139,7 @@ func loadConfigFromFileOrEnv(configFile string) (*config.Config, error) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return nil, fmt.Errorf("未找到配置文件,也未设置环境变量 DATABASE_URL")
|
return nil, fmt.Errorf("未找到配置文件,请指定配置文件路径或确保存在以下文件之一: %v", defaultPaths)
|
||||||
}
|
}
|
||||||
|
|
||||||
// connectDB 连接数据库
|
// connectDB 连接数据库
|
||||||
|
|||||||
@@ -26,6 +26,7 @@ type Migrator struct {
|
|||||||
db *gorm.DB
|
db *gorm.DB
|
||||||
migrations []Migration
|
migrations []Migration
|
||||||
tableName string
|
tableName string
|
||||||
|
dbType string // 数据库类型: mysql, postgres, sqlite
|
||||||
}
|
}
|
||||||
|
|
||||||
// NewMigrator 创建新的迁移器
|
// NewMigrator 创建新的迁移器
|
||||||
@@ -41,6 +42,25 @@ func NewMigrator(db *gorm.DB, tableName ...string) *Migrator {
|
|||||||
db: db,
|
db: db,
|
||||||
migrations: make([]Migration, 0),
|
migrations: make([]Migration, 0),
|
||||||
tableName: table,
|
tableName: table,
|
||||||
|
dbType: "", // 未指定时为空,会使用兼容模式
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewMigratorWithType 创建新的迁移器(指定数据库类型,性能更好)
|
||||||
|
// db: GORM数据库连接
|
||||||
|
// dbType: 数据库类型 ("mysql", "postgres", "sqlite")
|
||||||
|
// tableName: 存储迁移记录的表名,默认为 "schema_migrations"
|
||||||
|
func NewMigratorWithType(db *gorm.DB, dbType string, tableName ...string) *Migrator {
|
||||||
|
table := "schema_migrations"
|
||||||
|
if len(tableName) > 0 && tableName[0] != "" {
|
||||||
|
table = tableName[0]
|
||||||
|
}
|
||||||
|
|
||||||
|
return &Migrator{
|
||||||
|
db: db,
|
||||||
|
migrations: make([]Migration, 0),
|
||||||
|
tableName: table,
|
||||||
|
dbType: dbType,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -56,18 +76,78 @@ func (m *Migrator) AddMigrations(migrations ...Migration) {
|
|||||||
|
|
||||||
// initTable 初始化迁移记录表
|
// initTable 初始化迁移记录表
|
||||||
func (m *Migrator) initTable() error {
|
func (m *Migrator) initTable() error {
|
||||||
// 检查表是否存在
|
// 检查表是否存在(根据数据库类型使用对应的SQL,性能更好)
|
||||||
var exists bool
|
var exists bool
|
||||||
err := m.db.Raw(fmt.Sprintf(`
|
var err error
|
||||||
SELECT EXISTS (
|
|
||||||
SELECT FROM information_schema.tables
|
|
||||||
WHERE table_schema = CURRENT_SCHEMA()
|
|
||||||
AND table_name = '%s'
|
|
||||||
)
|
|
||||||
`, m.tableName)).Scan(&exists).Error
|
|
||||||
|
|
||||||
|
switch m.dbType {
|
||||||
|
case "mysql":
|
||||||
|
// MySQL/MariaDB语法
|
||||||
|
var count int64
|
||||||
|
err = m.db.Raw(fmt.Sprintf(`
|
||||||
|
SELECT COUNT(*) FROM information_schema.tables
|
||||||
|
WHERE table_schema = DATABASE()
|
||||||
|
AND table_name = '%s'
|
||||||
|
`, m.tableName)).Scan(&count).Error
|
||||||
|
if err == nil {
|
||||||
|
exists = count > 0
|
||||||
|
}
|
||||||
|
case "postgres":
|
||||||
|
// PostgreSQL语法
|
||||||
|
err = m.db.Raw(fmt.Sprintf(`
|
||||||
|
SELECT EXISTS (
|
||||||
|
SELECT 1 FROM information_schema.tables
|
||||||
|
WHERE table_schema = CURRENT_SCHEMA()
|
||||||
|
AND table_name = '%s'
|
||||||
|
)
|
||||||
|
`, m.tableName)).Scan(&exists).Error
|
||||||
|
case "sqlite":
|
||||||
|
// SQLite语法
|
||||||
|
var count int64
|
||||||
|
err = m.db.Raw(fmt.Sprintf(`
|
||||||
|
SELECT COUNT(*) FROM sqlite_master
|
||||||
|
WHERE type='table' AND name='%s'
|
||||||
|
`, m.tableName)).Scan(&count).Error
|
||||||
|
if err == nil {
|
||||||
|
exists = count > 0
|
||||||
|
}
|
||||||
|
default:
|
||||||
|
// 未指定数据库类型时,使用兼容模式(向后兼容)
|
||||||
|
// 按顺序尝试不同数据库的语法
|
||||||
|
var count int64
|
||||||
|
err = m.db.Raw(fmt.Sprintf(`
|
||||||
|
SELECT COUNT(*) FROM information_schema.tables
|
||||||
|
WHERE table_schema = DATABASE()
|
||||||
|
AND table_name = '%s'
|
||||||
|
`, m.tableName)).Scan(&count).Error
|
||||||
|
if err == nil && count > 0 {
|
||||||
|
exists = true
|
||||||
|
} else {
|
||||||
|
var pgExists bool
|
||||||
|
err = m.db.Raw(fmt.Sprintf(`
|
||||||
|
SELECT EXISTS (
|
||||||
|
SELECT 1 FROM information_schema.tables
|
||||||
|
WHERE table_schema = CURRENT_SCHEMA()
|
||||||
|
AND table_name = '%s'
|
||||||
|
)
|
||||||
|
`, m.tableName)).Scan(&pgExists).Error
|
||||||
|
if err == nil {
|
||||||
|
exists = pgExists
|
||||||
|
} else {
|
||||||
|
var sqliteCount int64
|
||||||
|
err = m.db.Raw(fmt.Sprintf(`
|
||||||
|
SELECT COUNT(*) FROM sqlite_master
|
||||||
|
WHERE type='table' AND name='%s'
|
||||||
|
`, m.tableName)).Scan(&sqliteCount).Error
|
||||||
|
if err == nil && sqliteCount > 0 {
|
||||||
|
exists = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 如果查询失败,假设表不存在,尝试创建
|
||||||
if err != nil {
|
if err != nil {
|
||||||
// 如果查询失败,可能是SQLite或其他数据库,尝试直接创建
|
|
||||||
exists = false
|
exists = false
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -89,19 +169,57 @@ func (m *Migrator) initTable() error {
|
|||||||
// 注意:这个检查可能在某些数据库中失败,但不影响功能
|
// 注意:这个检查可能在某些数据库中失败,但不影响功能
|
||||||
// 如果字段不存在,记录执行时间时会失败,但不影响迁移执行
|
// 如果字段不存在,记录执行时间时会失败,但不影响迁移执行
|
||||||
var hasExecutionTime bool
|
var hasExecutionTime bool
|
||||||
checkSQL := fmt.Sprintf(`
|
var columnCount int64
|
||||||
SELECT COUNT(*) > 0
|
var checkErr error
|
||||||
FROM information_schema.columns
|
|
||||||
WHERE table_schema = CURRENT_SCHEMA()
|
switch m.dbType {
|
||||||
AND table_name = '%s'
|
case "mysql":
|
||||||
AND column_name = 'execution_time'
|
// MySQL/MariaDB语法
|
||||||
`, m.tableName)
|
checkErr = m.db.Raw(fmt.Sprintf(`
|
||||||
err = m.db.Raw(checkSQL).Scan(&hasExecutionTime).Error
|
SELECT COUNT(*)
|
||||||
if err == nil && !hasExecutionTime {
|
FROM information_schema.columns
|
||||||
|
WHERE table_schema = DATABASE()
|
||||||
|
AND table_name = '%s'
|
||||||
|
AND column_name = 'execution_time'
|
||||||
|
`, m.tableName)).Scan(&columnCount).Error
|
||||||
|
if checkErr == nil {
|
||||||
|
hasExecutionTime = columnCount > 0
|
||||||
|
}
|
||||||
|
case "postgres":
|
||||||
|
// PostgreSQL语法
|
||||||
|
checkErr = m.db.Raw(fmt.Sprintf(`
|
||||||
|
SELECT COUNT(*)
|
||||||
|
FROM information_schema.columns
|
||||||
|
WHERE table_schema = CURRENT_SCHEMA()
|
||||||
|
AND table_name = '%s'
|
||||||
|
AND column_name = 'execution_time'
|
||||||
|
`, m.tableName)).Scan(&columnCount).Error
|
||||||
|
if checkErr == nil {
|
||||||
|
hasExecutionTime = columnCount > 0
|
||||||
|
}
|
||||||
|
case "sqlite":
|
||||||
|
// SQLite不支持information_schema,跳过检查
|
||||||
|
hasExecutionTime = false
|
||||||
|
default:
|
||||||
|
// 兼容模式:尝试MySQL语法
|
||||||
|
checkErr = m.db.Raw(fmt.Sprintf(`
|
||||||
|
SELECT COUNT(*)
|
||||||
|
FROM information_schema.columns
|
||||||
|
WHERE table_schema = DATABASE()
|
||||||
|
AND table_name = '%s'
|
||||||
|
AND column_name = 'execution_time'
|
||||||
|
`, m.tableName)).Scan(&columnCount).Error
|
||||||
|
if checkErr == nil {
|
||||||
|
hasExecutionTime = columnCount > 0
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if !hasExecutionTime {
|
||||||
// 尝试添加字段(如果失败不影响功能)
|
// 尝试添加字段(如果失败不影响功能)
|
||||||
|
// 注意:SQLite的ALTER TABLE ADD COLUMN语法略有不同,但GORM会处理
|
||||||
_ = m.db.Exec(fmt.Sprintf(`
|
_ = m.db.Exec(fmt.Sprintf(`
|
||||||
ALTER TABLE %s
|
ALTER TABLE %s
|
||||||
ADD COLUMN execution_time INT COMMENT '执行耗时(ms)'
|
ADD COLUMN execution_time INT
|
||||||
`, m.tableName))
|
`, m.tableName))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
269
sms/sms.go
269
sms/sms.go
@@ -16,59 +16,6 @@ import (
|
|||||||
"git.toowon.com/jimmy/go-common/config"
|
"git.toowon.com/jimmy/go-common/config"
|
||||||
)
|
)
|
||||||
|
|
||||||
// SMS 短信发送器
|
|
||||||
type SMS struct {
|
|
||||||
config *config.SMSConfig
|
|
||||||
}
|
|
||||||
|
|
||||||
// NewSMS 创建短信发送器
|
|
||||||
func NewSMS(cfg *config.SMSConfig) (*SMS, error) {
|
|
||||||
if cfg == nil {
|
|
||||||
return nil, fmt.Errorf("SMS config is nil")
|
|
||||||
}
|
|
||||||
|
|
||||||
if cfg.AccessKeyID == "" {
|
|
||||||
return nil, fmt.Errorf("AccessKeyID is required")
|
|
||||||
}
|
|
||||||
|
|
||||||
if cfg.AccessKeySecret == "" {
|
|
||||||
return nil, fmt.Errorf("AccessKeySecret is required")
|
|
||||||
}
|
|
||||||
|
|
||||||
if cfg.SignName == "" {
|
|
||||||
return nil, fmt.Errorf("SignName is required")
|
|
||||||
}
|
|
||||||
|
|
||||||
// 设置默认值
|
|
||||||
if cfg.Region == "" {
|
|
||||||
cfg.Region = "cn-hangzhou"
|
|
||||||
}
|
|
||||||
if cfg.Timeout == 0 {
|
|
||||||
cfg.Timeout = 10
|
|
||||||
}
|
|
||||||
|
|
||||||
return &SMS{
|
|
||||||
config: cfg,
|
|
||||||
}, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// SendRequest 发送短信请求
|
|
||||||
type SendRequest struct {
|
|
||||||
// PhoneNumbers 手机号列表
|
|
||||||
PhoneNumbers []string
|
|
||||||
|
|
||||||
// TemplateCode 模板代码(如果为空,使用配置中的模板代码)
|
|
||||||
TemplateCode string
|
|
||||||
|
|
||||||
// TemplateParam 模板参数(可以是map或JSON字符串)
|
|
||||||
// 如果是map,会自动转换为JSON字符串
|
|
||||||
// 如果是string,直接使用(必须是有效的JSON字符串)
|
|
||||||
TemplateParam interface{}
|
|
||||||
|
|
||||||
// SignName 签名(如果为空,使用配置中的签名)
|
|
||||||
SignName string
|
|
||||||
}
|
|
||||||
|
|
||||||
// SendResponse 发送短信响应
|
// SendResponse 发送短信响应
|
||||||
type SendResponse struct {
|
type SendResponse struct {
|
||||||
// RequestID 请求ID
|
// RequestID 请求ID
|
||||||
@@ -84,48 +31,123 @@ type SendResponse struct {
|
|||||||
BizID string `json:"BizId"`
|
BizID string `json:"BizId"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// SendRaw 发送原始请求(允许外部完全控制请求参数)
|
// SMS 短信发送器
|
||||||
// params: 请求参数map,工具只负责添加必要的系统参数(如签名、时间戳等)并发送
|
type SMS struct {
|
||||||
func (s *SMS) SendRaw(params map[string]string) (*SendResponse, error) {
|
config *config.SMSConfig
|
||||||
if params == nil {
|
}
|
||||||
params = make(map[string]string)
|
|
||||||
|
// NewSMS 创建短信发送器
|
||||||
|
func NewSMS(cfg *config.Config) *SMS {
|
||||||
|
if cfg == nil || cfg.SMS == nil {
|
||||||
|
return &SMS{config: nil}
|
||||||
|
}
|
||||||
|
return &SMS{config: cfg.SMS}
|
||||||
|
}
|
||||||
|
|
||||||
|
// getSMSConfig 获取短信配置(内部方法)
|
||||||
|
func (s *SMS) getSMSConfig() (*config.SMSConfig, error) {
|
||||||
|
if s.config == nil {
|
||||||
|
return nil, fmt.Errorf("SMS config is nil")
|
||||||
}
|
}
|
||||||
|
|
||||||
// 确保必要的系统参数存在
|
if s.config.AccessKeyID == "" {
|
||||||
if params["Action"] == "" {
|
return nil, fmt.Errorf("AccessKeyID is required")
|
||||||
params["Action"] = "SendSms"
|
|
||||||
}
|
}
|
||||||
if params["Version"] == "" {
|
|
||||||
params["Version"] = "2017-05-25"
|
if s.config.AccessKeySecret == "" {
|
||||||
|
return nil, fmt.Errorf("AccessKeySecret is required")
|
||||||
}
|
}
|
||||||
if params["RegionId"] == "" {
|
|
||||||
params["RegionId"] = s.config.Region
|
if s.config.SignName == "" {
|
||||||
|
return nil, fmt.Errorf("SignName is required")
|
||||||
}
|
}
|
||||||
if params["AccessKeyId"] == "" {
|
|
||||||
params["AccessKeyId"] = s.config.AccessKeyID
|
// 设置默认值
|
||||||
|
if s.config.Region == "" {
|
||||||
|
s.config.Region = "cn-hangzhou"
|
||||||
}
|
}
|
||||||
if params["Format"] == "" {
|
if s.config.Timeout == 0 {
|
||||||
params["Format"] = "JSON"
|
s.config.Timeout = 10
|
||||||
}
|
}
|
||||||
if params["SignatureMethod"] == "" {
|
|
||||||
params["SignatureMethod"] = "HMAC-SHA1"
|
return s.config, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// SendSMS 发送短信
|
||||||
|
// phoneNumbers: 手机号列表
|
||||||
|
// templateParam: 模板参数(map或JSON字符串)
|
||||||
|
// templateCode: 模板代码(可选,如果为空使用配置中的模板代码)
|
||||||
|
func (s *SMS) SendSMS(phoneNumbers []string, templateParam interface{}, templateCode ...string) (*SendResponse, error) {
|
||||||
|
cfg, err := s.getSMSConfig()
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
}
|
}
|
||||||
if params["SignatureVersion"] == "" {
|
|
||||||
params["SignatureVersion"] = "1.0"
|
if len(phoneNumbers) == 0 {
|
||||||
|
return nil, fmt.Errorf("phone numbers are required")
|
||||||
}
|
}
|
||||||
if params["SignatureNonce"] == "" {
|
|
||||||
params["SignatureNonce"] = fmt.Sprint(time.Now().UnixNano())
|
// 使用配置中的模板代码(如果请求中未指定)
|
||||||
|
templateCodeValue := ""
|
||||||
|
if len(templateCode) > 0 && templateCode[0] != "" {
|
||||||
|
templateCodeValue = templateCode[0]
|
||||||
|
} else {
|
||||||
|
templateCodeValue = cfg.TemplateCode
|
||||||
}
|
}
|
||||||
if params["Timestamp"] == "" {
|
if templateCodeValue == "" {
|
||||||
params["Timestamp"] = time.Now().UTC().Format("2006-01-02T15:04:05Z")
|
return nil, fmt.Errorf("template code is required")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
signName := cfg.SignName
|
||||||
|
|
||||||
|
// 处理模板参数
|
||||||
|
var templateParamJSON string
|
||||||
|
if templateParam != nil {
|
||||||
|
switch v := templateParam.(type) {
|
||||||
|
case string:
|
||||||
|
// 直接使用字符串(必须是有效的JSON)
|
||||||
|
templateParamJSON = v
|
||||||
|
case map[string]string:
|
||||||
|
// 转换为JSON字符串
|
||||||
|
paramBytes, err := json.Marshal(v)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("failed to marshal template param: %w", err)
|
||||||
|
}
|
||||||
|
templateParamJSON = string(paramBytes)
|
||||||
|
default:
|
||||||
|
// 尝试JSON序列化
|
||||||
|
paramBytes, err := json.Marshal(v)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("failed to marshal template param: %w", err)
|
||||||
|
}
|
||||||
|
templateParamJSON = string(paramBytes)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
templateParamJSON = "{}"
|
||||||
|
}
|
||||||
|
|
||||||
|
// 构建请求参数
|
||||||
|
params := make(map[string]string)
|
||||||
|
params["Action"] = "SendSms"
|
||||||
|
params["Version"] = "2017-05-25"
|
||||||
|
params["RegionId"] = cfg.Region
|
||||||
|
params["AccessKeyId"] = cfg.AccessKeyID
|
||||||
|
params["Format"] = "JSON"
|
||||||
|
params["SignatureMethod"] = "HMAC-SHA1"
|
||||||
|
params["SignatureVersion"] = "1.0"
|
||||||
|
params["SignatureNonce"] = fmt.Sprint(time.Now().UnixNano())
|
||||||
|
params["Timestamp"] = time.Now().UTC().Format("2006-01-02T15:04:05Z")
|
||||||
|
params["PhoneNumbers"] = strings.Join(phoneNumbers, ",")
|
||||||
|
params["SignName"] = signName
|
||||||
|
params["TemplateCode"] = templateCodeValue
|
||||||
|
params["TemplateParam"] = templateParamJSON
|
||||||
|
|
||||||
// 计算签名
|
// 计算签名
|
||||||
signature := s.calculateSignature(params, "POST")
|
signature := s.calculateSignature(params, "POST", cfg.AccessKeySecret)
|
||||||
params["Signature"] = signature
|
params["Signature"] = signature
|
||||||
|
|
||||||
// 构建请求URL
|
// 构建请求URL
|
||||||
endpoint := s.config.Endpoint
|
endpoint := cfg.Endpoint
|
||||||
if endpoint == "" {
|
if endpoint == "" {
|
||||||
endpoint = "https://dysmsapi.aliyuncs.com"
|
endpoint = "https://dysmsapi.aliyuncs.com"
|
||||||
}
|
}
|
||||||
@@ -145,7 +167,7 @@ func (s *SMS) SendRaw(params map[string]string) (*SendResponse, error) {
|
|||||||
httpReq.Header.Set("Accept", "application/json")
|
httpReq.Header.Set("Accept", "application/json")
|
||||||
|
|
||||||
client := &http.Client{
|
client := &http.Client{
|
||||||
Timeout: time.Duration(s.config.Timeout) * time.Second,
|
Timeout: time.Duration(cfg.Timeout) * time.Second,
|
||||||
}
|
}
|
||||||
|
|
||||||
resp, err := client.Do(httpReq)
|
resp, err := client.Do(httpReq)
|
||||||
@@ -174,70 +196,8 @@ func (s *SMS) SendRaw(params map[string]string) (*SendResponse, error) {
|
|||||||
return &sendResp, nil
|
return &sendResp, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// Send 发送短信(使用SendRequest结构)
|
|
||||||
// 注意:如果需要完全控制请求参数,请使用SendRaw方法
|
|
||||||
func (s *SMS) Send(req *SendRequest) (*SendResponse, error) {
|
|
||||||
if req == nil {
|
|
||||||
return nil, fmt.Errorf("request is nil")
|
|
||||||
}
|
|
||||||
|
|
||||||
if len(req.PhoneNumbers) == 0 {
|
|
||||||
return nil, fmt.Errorf("phone numbers are required")
|
|
||||||
}
|
|
||||||
|
|
||||||
// 使用配置中的模板代码和签名(如果请求中未指定)
|
|
||||||
templateCode := req.TemplateCode
|
|
||||||
if templateCode == "" {
|
|
||||||
templateCode = s.config.TemplateCode
|
|
||||||
}
|
|
||||||
if templateCode == "" {
|
|
||||||
return nil, fmt.Errorf("template code is required")
|
|
||||||
}
|
|
||||||
|
|
||||||
signName := req.SignName
|
|
||||||
if signName == "" {
|
|
||||||
signName = s.config.SignName
|
|
||||||
}
|
|
||||||
|
|
||||||
// 处理模板参数
|
|
||||||
var templateParamJSON string
|
|
||||||
if req.TemplateParam != nil {
|
|
||||||
switch v := req.TemplateParam.(type) {
|
|
||||||
case string:
|
|
||||||
// 直接使用字符串(必须是有效的JSON)
|
|
||||||
templateParamJSON = v
|
|
||||||
case map[string]string:
|
|
||||||
// 转换为JSON字符串
|
|
||||||
paramBytes, err := json.Marshal(v)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("failed to marshal template param: %w", err)
|
|
||||||
}
|
|
||||||
templateParamJSON = string(paramBytes)
|
|
||||||
default:
|
|
||||||
// 尝试JSON序列化
|
|
||||||
paramBytes, err := json.Marshal(v)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("failed to marshal template param: %w", err)
|
|
||||||
}
|
|
||||||
templateParamJSON = string(paramBytes)
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
templateParamJSON = "{}"
|
|
||||||
}
|
|
||||||
|
|
||||||
// 构建请求参数
|
|
||||||
params := make(map[string]string)
|
|
||||||
params["PhoneNumbers"] = strings.Join(req.PhoneNumbers, ",")
|
|
||||||
params["SignName"] = signName
|
|
||||||
params["TemplateCode"] = templateCode
|
|
||||||
params["TemplateParam"] = templateParamJSON
|
|
||||||
|
|
||||||
// 使用SendRaw发送
|
|
||||||
return s.SendRaw(params)
|
|
||||||
}
|
|
||||||
|
|
||||||
// calculateSignature 计算签名
|
// calculateSignature 计算签名
|
||||||
func (s *SMS) calculateSignature(params map[string]string, method string) string {
|
func (s *SMS) calculateSignature(params map[string]string, method, accessKeySecret string) string {
|
||||||
// 对参数进行排序
|
// 对参数进行排序
|
||||||
keys := make([]string, 0, len(params))
|
keys := make([]string, 0, len(params))
|
||||||
for k := range params {
|
for k := range params {
|
||||||
@@ -260,31 +220,10 @@ func (s *SMS) calculateSignature(params map[string]string, method string) string
|
|||||||
stringToSign := method + "&" + url.QueryEscape("/") + "&" + url.QueryEscape(queryString)
|
stringToSign := method + "&" + url.QueryEscape("/") + "&" + url.QueryEscape(queryString)
|
||||||
|
|
||||||
// 计算HMAC-SHA1签名
|
// 计算HMAC-SHA1签名
|
||||||
mac := hmac.New(sha1.New, []byte(s.config.AccessKeySecret+"&"))
|
mac := hmac.New(sha1.New, []byte(accessKeySecret+"&"))
|
||||||
mac.Write([]byte(stringToSign))
|
mac.Write([]byte(stringToSign))
|
||||||
signature := base64.StdEncoding.EncodeToString(mac.Sum(nil))
|
signature := base64.StdEncoding.EncodeToString(mac.Sum(nil))
|
||||||
|
|
||||||
return signature
|
return signature
|
||||||
}
|
}
|
||||||
|
|
||||||
// SendSimple 发送简单短信(便捷方法)
|
|
||||||
// phoneNumbers: 手机号列表
|
|
||||||
// templateParam: 模板参数
|
|
||||||
func (s *SMS) SendSimple(phoneNumbers []string, templateParam map[string]string) (*SendResponse, error) {
|
|
||||||
return s.Send(&SendRequest{
|
|
||||||
PhoneNumbers: phoneNumbers,
|
|
||||||
TemplateParam: templateParam,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
// SendWithTemplate 使用指定模板发送短信(便捷方法)
|
|
||||||
// phoneNumbers: 手机号列表
|
|
||||||
// templateCode: 模板代码
|
|
||||||
// templateParam: 模板参数
|
|
||||||
func (s *SMS) SendWithTemplate(phoneNumbers []string, templateCode string, templateParam map[string]string) (*SendResponse, error) {
|
|
||||||
return s.Send(&SendRequest{
|
|
||||||
PhoneNumbers: phoneNumbers,
|
|
||||||
TemplateCode: templateCode,
|
|
||||||
TemplateParam: templateParam,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -43,31 +43,29 @@ func NewUploadHandler(cfg UploadHandlerConfig) *UploadHandler {
|
|||||||
// 表单字段: file (文件)
|
// 表单字段: file (文件)
|
||||||
// 可选字段: prefix (对象键前缀,会覆盖配置中的前缀)
|
// 可选字段: prefix (对象键前缀,会覆盖配置中的前缀)
|
||||||
func (h *UploadHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
func (h *UploadHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||||
handler := commonhttp.NewHandler(w, r)
|
|
||||||
|
|
||||||
if r.Method != http.MethodPost {
|
if r.Method != http.MethodPost {
|
||||||
handler.Error(4001, "Method not allowed")
|
commonhttp.Error(w, 4001, "Method not allowed")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// 解析multipart表单
|
// 解析multipart表单
|
||||||
err := r.ParseMultipartForm(h.maxFileSize)
|
err := r.ParseMultipartForm(h.maxFileSize)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
handler.Error(4002, fmt.Sprintf("Failed to parse form: %v", err))
|
commonhttp.Error(w, 4002, fmt.Sprintf("Failed to parse form: %v", err))
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// 获取文件
|
// 获取文件
|
||||||
file, header, err := r.FormFile("file")
|
file, header, err := r.FormFile("file")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
handler.Error(4003, fmt.Sprintf("Failed to get file: %v", err))
|
commonhttp.Error(w, 4003, fmt.Sprintf("Failed to get file: %v", err))
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
defer file.Close()
|
defer file.Close()
|
||||||
|
|
||||||
// 检查文件大小
|
// 检查文件大小
|
||||||
if h.maxFileSize > 0 && header.Size > h.maxFileSize {
|
if h.maxFileSize > 0 && header.Size > h.maxFileSize {
|
||||||
handler.Error(1001, fmt.Sprintf("File size exceeds limit: %d bytes", h.maxFileSize))
|
commonhttp.Error(w, 1001, fmt.Sprintf("File size exceeds limit: %d bytes", h.maxFileSize))
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -82,7 +80,7 @@ func (h *UploadHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
if !allowed {
|
if !allowed {
|
||||||
handler.Error(1002, fmt.Sprintf("File extension not allowed. Allowed: %v", h.allowedExts))
|
commonhttp.Error(w, 1002, fmt.Sprintf("File extension not allowed. Allowed: %v", h.allowedExts))
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -110,14 +108,14 @@ func (h *UploadHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
|||||||
ctx := r.Context()
|
ctx := r.Context()
|
||||||
err = h.storage.Upload(ctx, objectKey, file, contentType)
|
err = h.storage.Upload(ctx, objectKey, file, contentType)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
handler.SystemError(fmt.Sprintf("Failed to upload file: %v", err))
|
commonhttp.SystemError(w, fmt.Sprintf("Failed to upload file: %v", err))
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// 获取文件URL
|
// 获取文件URL
|
||||||
fileURL, err := h.storage.GetURL(objectKey, 0)
|
fileURL, err := h.storage.GetURL(objectKey, 0)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
handler.SystemError(fmt.Sprintf("Failed to get file URL: %v", err))
|
commonhttp.SystemError(w, fmt.Sprintf("Failed to get file URL: %v", err))
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -130,7 +128,7 @@ func (h *UploadHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
|||||||
UploadTime: time.Now(),
|
UploadTime: time.Now(),
|
||||||
}
|
}
|
||||||
|
|
||||||
handler.SuccessWithMessage("Upload successful", result)
|
commonhttp.Success(w, result, "Upload successful")
|
||||||
}
|
}
|
||||||
|
|
||||||
// generateUniqueFilename 生成唯一文件名
|
// generateUniqueFilename 生成唯一文件名
|
||||||
|
|||||||
@@ -24,11 +24,11 @@ import (
|
|||||||
// ./migrate down # 回滚最后一个迁移
|
// ./migrate down # 回滚最后一个迁移
|
||||||
//
|
//
|
||||||
// Docker 中使用:
|
// Docker 中使用:
|
||||||
// # 方式1:挂载配置文件
|
// # 方式1:挂载配置文件(推荐)
|
||||||
// docker run -v /host/config.json:/app/config.json myapp ./migrate up
|
// docker run -v /host/config.json:/app/config.json myapp ./migrate up
|
||||||
//
|
//
|
||||||
// # 方式2:使用环境变量
|
// # 方式2:使用环境变量指定配置文件路径
|
||||||
// docker run -e DATABASE_URL="mysql://..." myapp ./migrate up
|
// docker run -e CONFIG_FILE=/etc/app/config.json myapp ./migrate up
|
||||||
//
|
//
|
||||||
// # 方式3:指定容器内的配置文件路径
|
// # 方式3:指定容器内的配置文件路径
|
||||||
// docker run myapp ./migrate up -config /etc/app/config.json
|
// docker run myapp ./migrate up -config /etc/app/config.json
|
||||||
@@ -41,8 +41,7 @@ import (
|
|||||||
// 配置优先级(从高到低):
|
// 配置优先级(从高到低):
|
||||||
// 1. 命令行参数 -config 和 -dir
|
// 1. 命令行参数 -config 和 -dir
|
||||||
// 2. 环境变量 CONFIG_FILE 和 MIGRATIONS_DIR
|
// 2. 环境变量 CONFIG_FILE 和 MIGRATIONS_DIR
|
||||||
// 3. 环境变量 DATABASE_URL(直接连接,无需配置文件)
|
// 3. 默认值(config.json 和 migrations)
|
||||||
// 4. 默认值(config.json 和 migrations)
|
|
||||||
|
|
||||||
var (
|
var (
|
||||||
configFile string
|
configFile string
|
||||||
@@ -137,15 +136,14 @@ func printHelp() {
|
|||||||
fmt.Println(" # 指定配置和迁移目录")
|
fmt.Println(" # 指定配置和迁移目录")
|
||||||
fmt.Println(" migrate up -c config.json -d db/migrations")
|
fmt.Println(" migrate up -c config.json -d db/migrations")
|
||||||
fmt.Println()
|
fmt.Println()
|
||||||
fmt.Println(" # 使用环境变量")
|
fmt.Println(" # 使用环境变量指定配置文件路径")
|
||||||
fmt.Println(" DATABASE_URL='mysql://...' migrate up")
|
fmt.Println(" CONFIG_FILE=/etc/app/config.json migrate up")
|
||||||
fmt.Println()
|
fmt.Println()
|
||||||
fmt.Println(" # Docker 中使用")
|
fmt.Println(" # Docker 中使用(挂载配置文件)")
|
||||||
fmt.Println(" docker run -v /host/config.json:/app/config.json myapp migrate up")
|
fmt.Println(" docker run -v /host/config.json:/app/config.json myapp migrate up")
|
||||||
fmt.Println()
|
fmt.Println()
|
||||||
fmt.Println("配置优先级(从高到低):")
|
fmt.Println("配置优先级(从高到低):")
|
||||||
fmt.Println(" 1. 命令行参数 -config 和 -dir")
|
fmt.Println(" 1. 命令行参数 -config 和 -dir")
|
||||||
fmt.Println(" 2. 环境变量 CONFIG_FILE 和 MIGRATIONS_DIR")
|
fmt.Println(" 2. 环境变量 CONFIG_FILE 和 MIGRATIONS_DIR")
|
||||||
fmt.Println(" 3. 环境变量 DATABASE_URL")
|
fmt.Println(" 3. 默认值(config.json 和 migrations)")
|
||||||
fmt.Println(" 4. 默认值(config.json 和 migrations)")
|
|
||||||
}
|
}
|
||||||
|
|||||||
99
tools/convertor.go
Normal file
99
tools/convertor.go
Normal file
@@ -0,0 +1,99 @@
|
|||||||
|
package tools
|
||||||
|
|
||||||
|
import "strconv"
|
||||||
|
|
||||||
|
// ConvertInt 将字符串转换为int类型
|
||||||
|
// value: 待转换的字符串
|
||||||
|
// defaultValue: 转换失败或字符串为空时返回的默认值
|
||||||
|
func ConvertInt(value string, defaultValue int) int {
|
||||||
|
if value == "" {
|
||||||
|
return defaultValue
|
||||||
|
}
|
||||||
|
|
||||||
|
intValue, err := strconv.Atoi(value)
|
||||||
|
if err != nil {
|
||||||
|
return defaultValue
|
||||||
|
}
|
||||||
|
|
||||||
|
return intValue
|
||||||
|
}
|
||||||
|
|
||||||
|
// ConvertInt64 将字符串转换为int64类型
|
||||||
|
// value: 待转换的字符串
|
||||||
|
// defaultValue: 转换失败或字符串为空时返回的默认值
|
||||||
|
func ConvertInt64(value string, defaultValue int64) int64 {
|
||||||
|
if value == "" {
|
||||||
|
return defaultValue
|
||||||
|
}
|
||||||
|
|
||||||
|
intValue, err := strconv.ParseInt(value, 10, 64)
|
||||||
|
if err != nil {
|
||||||
|
return defaultValue
|
||||||
|
}
|
||||||
|
|
||||||
|
return intValue
|
||||||
|
}
|
||||||
|
|
||||||
|
// ConvertUint64 将字符串转换为uint64类型
|
||||||
|
// value: 待转换的字符串
|
||||||
|
// defaultValue: 转换失败或字符串为空时返回的默认值
|
||||||
|
func ConvertUint64(value string, defaultValue uint64) uint64 {
|
||||||
|
if value == "" {
|
||||||
|
return defaultValue
|
||||||
|
}
|
||||||
|
|
||||||
|
uintValue, err := strconv.ParseUint(value, 10, 64)
|
||||||
|
if err != nil {
|
||||||
|
return defaultValue
|
||||||
|
}
|
||||||
|
|
||||||
|
return uintValue
|
||||||
|
}
|
||||||
|
|
||||||
|
// ConvertUint32 将字符串转换为uint32类型
|
||||||
|
// value: 待转换的字符串
|
||||||
|
// defaultValue: 转换失败或字符串为空时返回的默认值
|
||||||
|
func ConvertUint32(value string, defaultValue uint32) uint32 {
|
||||||
|
if value == "" {
|
||||||
|
return defaultValue
|
||||||
|
}
|
||||||
|
|
||||||
|
uintValue, err := strconv.ParseUint(value, 10, 32)
|
||||||
|
if err != nil {
|
||||||
|
return defaultValue
|
||||||
|
}
|
||||||
|
|
||||||
|
return uint32(uintValue)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ConvertBool 将字符串转换为bool类型
|
||||||
|
// value: 待转换的字符串
|
||||||
|
// defaultValue: 转换失败或字符串为空时返回的默认值
|
||||||
|
func ConvertBool(value string, defaultValue bool) bool {
|
||||||
|
if value == "" {
|
||||||
|
return defaultValue
|
||||||
|
}
|
||||||
|
|
||||||
|
boolValue, err := strconv.ParseBool(value)
|
||||||
|
if err != nil {
|
||||||
|
return defaultValue
|
||||||
|
}
|
||||||
|
|
||||||
|
return boolValue
|
||||||
|
}
|
||||||
|
|
||||||
|
// ConvertFloat64 将字符串转换为float64类型
|
||||||
|
// value: 待转换的字符串
|
||||||
|
// defaultValue: 转换失败或字符串为空时返回的默认值
|
||||||
|
func ConvertFloat64(value string, defaultValue float64) float64 {
|
||||||
|
if value == "" {
|
||||||
|
return defaultValue
|
||||||
|
}
|
||||||
|
|
||||||
|
floatValue, err := strconv.ParseFloat(value, 64)
|
||||||
|
if err != nil {
|
||||||
|
return defaultValue
|
||||||
|
}
|
||||||
|
|
||||||
|
return floatValue
|
||||||
|
}
|
||||||
85
tools/crypto.go
Normal file
85
tools/crypto.go
Normal file
@@ -0,0 +1,85 @@
|
|||||||
|
package tools
|
||||||
|
|
||||||
|
import (
|
||||||
|
"crypto/md5"
|
||||||
|
"crypto/rand"
|
||||||
|
"crypto/sha256"
|
||||||
|
"encoding/hex"
|
||||||
|
"fmt"
|
||||||
|
"math/big"
|
||||||
|
|
||||||
|
"golang.org/x/crypto/bcrypt"
|
||||||
|
)
|
||||||
|
|
||||||
|
// HashPassword 使用bcrypt加密密码
|
||||||
|
func HashPassword(password string) (string, error) {
|
||||||
|
bytes, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
|
||||||
|
return string(bytes), err
|
||||||
|
}
|
||||||
|
|
||||||
|
// CheckPassword 验证密码
|
||||||
|
func CheckPassword(password, hash string) bool {
|
||||||
|
err := bcrypt.CompareHashAndPassword([]byte(hash), []byte(password))
|
||||||
|
return err == nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// MD5 计算MD5哈希值
|
||||||
|
func MD5(text string) string {
|
||||||
|
hash := md5.Sum([]byte(text))
|
||||||
|
return hex.EncodeToString(hash[:])
|
||||||
|
}
|
||||||
|
|
||||||
|
// SHA256 计算SHA256哈希值
|
||||||
|
func SHA256(text string) string {
|
||||||
|
hash := sha256.Sum256([]byte(text))
|
||||||
|
return hex.EncodeToString(hash[:])
|
||||||
|
}
|
||||||
|
|
||||||
|
// GenerateRandomString 生成指定长度的随机字符串
|
||||||
|
func GenerateRandomString(length int) string {
|
||||||
|
const charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
|
||||||
|
b := make([]byte, length)
|
||||||
|
for i := range b {
|
||||||
|
num, _ := rand.Int(rand.Reader, big.NewInt(int64(len(charset))))
|
||||||
|
b[i] = charset[num.Int64()]
|
||||||
|
}
|
||||||
|
return string(b)
|
||||||
|
}
|
||||||
|
|
||||||
|
// GenerateRandomNumber 生成指定长度的随机数字字符串
|
||||||
|
func GenerateRandomNumber(length int) string {
|
||||||
|
const charset = "0123456789"
|
||||||
|
b := make([]byte, length)
|
||||||
|
for i := range b {
|
||||||
|
num, _ := rand.Int(rand.Reader, big.NewInt(int64(len(charset))))
|
||||||
|
b[i] = charset[num.Int64()]
|
||||||
|
}
|
||||||
|
return string(b)
|
||||||
|
}
|
||||||
|
|
||||||
|
// GenerateSMSCode 生成短信验证码
|
||||||
|
func GenerateSMSCode() string {
|
||||||
|
return GenerateRandomNumber(6)
|
||||||
|
}
|
||||||
|
|
||||||
|
// GenerateOrderNo 生成订单号
|
||||||
|
func GenerateOrderNo(prefix string) string {
|
||||||
|
timestamp := GetTimestamp()
|
||||||
|
random := GenerateRandomNumber(6)
|
||||||
|
return fmt.Sprintf("%s%d%s", prefix, timestamp, random)
|
||||||
|
}
|
||||||
|
|
||||||
|
// GeneratePaymentNo 生成支付单号
|
||||||
|
func GeneratePaymentNo() string {
|
||||||
|
return GenerateOrderNo("PAY")
|
||||||
|
}
|
||||||
|
|
||||||
|
// GenerateRefundNo 生成退款单号
|
||||||
|
func GenerateRefundNo() string {
|
||||||
|
return GenerateOrderNo("RF")
|
||||||
|
}
|
||||||
|
|
||||||
|
// GenerateTransferNo 生成调拨单号
|
||||||
|
func GenerateTransferNo() string {
|
||||||
|
return GenerateOrderNo("TF")
|
||||||
|
}
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
package datetime
|
package tools
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt"
|
"fmt"
|
||||||
173
tools/money.go
Normal file
173
tools/money.go
Normal file
@@ -0,0 +1,173 @@
|
|||||||
|
package tools
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"math"
|
||||||
|
)
|
||||||
|
|
||||||
|
// MoneyCalculator 金额计算工具(以分为单位)
|
||||||
|
type MoneyCalculator struct{}
|
||||||
|
|
||||||
|
// NewMoneyCalculator 创建金额计算器
|
||||||
|
func NewMoneyCalculator() *MoneyCalculator {
|
||||||
|
return &MoneyCalculator{}
|
||||||
|
}
|
||||||
|
|
||||||
|
// YuanToCents 元转分
|
||||||
|
func (m *MoneyCalculator) YuanToCents(yuan float64) int64 {
|
||||||
|
return int64(math.Round(yuan * 100))
|
||||||
|
}
|
||||||
|
|
||||||
|
// CentsToYuan 分转元
|
||||||
|
func (m *MoneyCalculator) CentsToYuan(cents int64) float64 {
|
||||||
|
return float64(cents) / 100
|
||||||
|
}
|
||||||
|
|
||||||
|
// FormatYuan 格式化显示金额(分转元,保留2位小数)
|
||||||
|
func (m *MoneyCalculator) FormatYuan(cents int64) string {
|
||||||
|
return fmt.Sprintf("%.2f", m.CentsToYuan(cents))
|
||||||
|
}
|
||||||
|
|
||||||
|
// Add 金额相加
|
||||||
|
func (m *MoneyCalculator) Add(amount1, amount2 int64) int64 {
|
||||||
|
return amount1 + amount2
|
||||||
|
}
|
||||||
|
|
||||||
|
// Subtract 金额相减
|
||||||
|
func (m *MoneyCalculator) Subtract(amount1, amount2 int64) int64 {
|
||||||
|
return amount1 - amount2
|
||||||
|
}
|
||||||
|
|
||||||
|
// Multiply 金额乘法(金额 * 数量)
|
||||||
|
func (m *MoneyCalculator) Multiply(amount int64, quantity int) int64 {
|
||||||
|
return amount * int64(quantity)
|
||||||
|
}
|
||||||
|
|
||||||
|
// MultiplyFloat 金额乘法(金额 * 浮点数,如折扣)
|
||||||
|
func (m *MoneyCalculator) MultiplyFloat(amount int64, rate float64) int64 {
|
||||||
|
return int64(math.Round(float64(amount) * rate))
|
||||||
|
}
|
||||||
|
|
||||||
|
// Divide 金额除法(平均分配)
|
||||||
|
func (m *MoneyCalculator) Divide(amount int64, count int) int64 {
|
||||||
|
if count <= 0 {
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
return amount / int64(count)
|
||||||
|
}
|
||||||
|
|
||||||
|
// CalculateDiscount 计算折扣金额
|
||||||
|
func (m *MoneyCalculator) CalculateDiscount(originalAmount int64, discountRate float64) int64 {
|
||||||
|
if discountRate <= 0 || discountRate >= 1 {
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
return int64(math.Round(float64(originalAmount) * discountRate))
|
||||||
|
}
|
||||||
|
|
||||||
|
// CalculatePercentage 计算百分比金额
|
||||||
|
func (m *MoneyCalculator) CalculatePercentage(amount int64, percentage float64) int64 {
|
||||||
|
return int64(math.Round(float64(amount) * percentage / 100))
|
||||||
|
}
|
||||||
|
|
||||||
|
// Max 取最大金额
|
||||||
|
func (m *MoneyCalculator) Max(amounts ...int64) int64 {
|
||||||
|
if len(amounts) == 0 {
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
max := amounts[0]
|
||||||
|
for _, amount := range amounts[1:] {
|
||||||
|
if amount > max {
|
||||||
|
max = amount
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return max
|
||||||
|
}
|
||||||
|
|
||||||
|
// Min 取最小金额
|
||||||
|
func (m *MoneyCalculator) Min(amounts ...int64) int64 {
|
||||||
|
if len(amounts) == 0 {
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
min := amounts[0]
|
||||||
|
for _, amount := range amounts[1:] {
|
||||||
|
if amount < min {
|
||||||
|
min = amount
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return min
|
||||||
|
}
|
||||||
|
|
||||||
|
// IsPositive 判断是否为正数
|
||||||
|
func (m *MoneyCalculator) IsPositive(amount int64) bool {
|
||||||
|
return amount > 0
|
||||||
|
}
|
||||||
|
|
||||||
|
// IsZero 判断是否为零
|
||||||
|
func (m *MoneyCalculator) IsZero(amount int64) bool {
|
||||||
|
return amount == 0
|
||||||
|
}
|
||||||
|
|
||||||
|
// IsNegative 判断是否为负数
|
||||||
|
func (m *MoneyCalculator) IsNegative(amount int64) bool {
|
||||||
|
return amount < 0
|
||||||
|
}
|
||||||
|
|
||||||
|
// Equal 判断金额是否相等
|
||||||
|
func (m *MoneyCalculator) Equal(amount1, amount2 int64) bool {
|
||||||
|
return amount1 == amount2
|
||||||
|
}
|
||||||
|
|
||||||
|
// Greater 判断第一个金额是否大于第二个
|
||||||
|
func (m *MoneyCalculator) Greater(amount1, amount2 int64) bool {
|
||||||
|
return amount1 > amount2
|
||||||
|
}
|
||||||
|
|
||||||
|
// Less 判断第一个金额是否小于第二个
|
||||||
|
func (m *MoneyCalculator) Less(amount1, amount2 int64) bool {
|
||||||
|
return amount1 < amount2
|
||||||
|
}
|
||||||
|
|
||||||
|
// Sum 计算金额总和
|
||||||
|
func (m *MoneyCalculator) Sum(amounts ...int64) int64 {
|
||||||
|
var total int64
|
||||||
|
for _, amount := range amounts {
|
||||||
|
total += amount
|
||||||
|
}
|
||||||
|
return total
|
||||||
|
}
|
||||||
|
|
||||||
|
// SplitAmount 金额分摊(处理分摊不均的情况)
|
||||||
|
func (m *MoneyCalculator) SplitAmount(totalAmount int64, count int) []int64 {
|
||||||
|
if count <= 0 {
|
||||||
|
return []int64{}
|
||||||
|
}
|
||||||
|
|
||||||
|
baseAmount := totalAmount / int64(count)
|
||||||
|
remainder := totalAmount % int64(count)
|
||||||
|
|
||||||
|
amounts := make([]int64, count)
|
||||||
|
for i := 0; i < count; i++ {
|
||||||
|
amounts[i] = baseAmount
|
||||||
|
if int64(i) < remainder {
|
||||||
|
amounts[i]++
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return amounts
|
||||||
|
}
|
||||||
|
|
||||||
|
// 全局金额计算器实例
|
||||||
|
var Money = NewMoneyCalculator()
|
||||||
|
|
||||||
|
// 便捷函数
|
||||||
|
func YuanToCents(yuan float64) int64 {
|
||||||
|
return Money.YuanToCents(yuan)
|
||||||
|
}
|
||||||
|
|
||||||
|
func CentsToYuan(cents int64) float64 {
|
||||||
|
return Money.CentsToYuan(cents)
|
||||||
|
}
|
||||||
|
|
||||||
|
func FormatYuan(cents int64) string {
|
||||||
|
return Money.FormatYuan(cents)
|
||||||
|
}
|
||||||
186
tools/time.go
Normal file
186
tools/time.go
Normal file
@@ -0,0 +1,186 @@
|
|||||||
|
package tools
|
||||||
|
|
||||||
|
import (
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
// TimeInfo 详细时间信息结构
|
||||||
|
type TimeInfo struct {
|
||||||
|
UTC string `json:"utc"` // UTC时间
|
||||||
|
Local string `json:"local"` // 用户时区时间
|
||||||
|
Unix int64 `json:"unix"` // Unix时间戳
|
||||||
|
Timezone string `json:"timezone"` // 时区名称
|
||||||
|
Offset int `json:"offset"` // 时区偏移量(小时)
|
||||||
|
RFC3339 string `json:"rfc3339"` // RFC3339格式
|
||||||
|
DateTime string `json:"datetime"` // 日期时间格式
|
||||||
|
Date string `json:"date"` // 日期格式
|
||||||
|
Time string `json:"time"` // 时间格式
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetTimestamp 获取当前时间戳(秒)
|
||||||
|
func GetTimestamp() int64 {
|
||||||
|
return time.Now().Unix()
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetMillisTimestamp 获取当前时间戳(毫秒)
|
||||||
|
func GetMillisTimestamp() int64 {
|
||||||
|
return time.Now().UnixMilli()
|
||||||
|
}
|
||||||
|
|
||||||
|
// FormatTimeWithLayout 格式化时间(自定义格式)
|
||||||
|
func FormatTimeWithLayout(t time.Time, layout string) string {
|
||||||
|
if layout == "" {
|
||||||
|
layout = "2006-01-02 15:04:05"
|
||||||
|
}
|
||||||
|
return t.Format(layout)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ParseTime 解析时间字符串
|
||||||
|
func ParseTime(timeStr, layout string) (time.Time, error) {
|
||||||
|
if layout == "" {
|
||||||
|
layout = "2006-01-02 15:04:05"
|
||||||
|
}
|
||||||
|
return time.Parse(layout, timeStr)
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetCurrentTime 获取当前时间字符串
|
||||||
|
func GetCurrentTime() string {
|
||||||
|
return FormatTimeWithLayout(time.Now(), "")
|
||||||
|
}
|
||||||
|
|
||||||
|
// 注意:GetBeginOfDay、GetEndOfDay 已在 datetime.go 中实现为 StartOfDay、EndOfDay
|
||||||
|
// datetime.go 中的方法支持时区参数,功能更强大,建议使用 datetime.go 中的方法
|
||||||
|
|
||||||
|
// GetBeginOfWeek 获取某周的开始时间(周一)
|
||||||
|
func GetBeginOfWeek(t time.Time) time.Time {
|
||||||
|
weekday := t.Weekday()
|
||||||
|
if weekday == time.Sunday {
|
||||||
|
weekday = 7
|
||||||
|
}
|
||||||
|
// 使用 datetime.go 中的 StartOfDay 方法(需要时区,这里使用时间对象本身的时区)
|
||||||
|
beginDay := t.AddDate(0, 0, int(1-weekday))
|
||||||
|
return time.Date(beginDay.Year(), beginDay.Month(), beginDay.Day(), 0, 0, 0, 0, beginDay.Location())
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetEndOfWeek 获取某周的结束时间(周日)
|
||||||
|
func GetEndOfWeek(t time.Time) time.Time {
|
||||||
|
beginOfWeek := GetBeginOfWeek(t)
|
||||||
|
endDay := beginOfWeek.AddDate(0, 0, 6)
|
||||||
|
return time.Date(endDay.Year(), endDay.Month(), endDay.Day(), 23, 59, 59, 999999999, endDay.Location())
|
||||||
|
}
|
||||||
|
|
||||||
|
// 注意:GetBeginOfMonth、GetEndOfMonth、GetBeginOfYear、GetEndOfYear 已在 datetime.go 中实现
|
||||||
|
// datetime.go 中的方法(StartOfMonth、EndOfMonth、StartOfYear、EndOfYear)支持时区参数,功能更强大
|
||||||
|
// 建议使用 datetime.go 中的方法
|
||||||
|
|
||||||
|
// AddHours 增加小时数
|
||||||
|
func AddHours(t time.Time, hours int) time.Time {
|
||||||
|
return t.Add(time.Duration(hours) * time.Hour)
|
||||||
|
}
|
||||||
|
|
||||||
|
// AddMinutes 增加分钟数
|
||||||
|
func AddMinutes(t time.Time, minutes int) time.Time {
|
||||||
|
return t.Add(time.Duration(minutes) * time.Minute)
|
||||||
|
}
|
||||||
|
|
||||||
|
// 注意:DiffDays、DiffHours、DiffMinutes、DiffSeconds 方法已在 datetime.go 中实现
|
||||||
|
// 请使用 datetime.go 中的方法,它们支持更精确的计算和统一的返回类型
|
||||||
|
|
||||||
|
// IsToday 判断是否为今天
|
||||||
|
func IsToday(t time.Time) bool {
|
||||||
|
now := time.Now()
|
||||||
|
tBegin := time.Date(t.Year(), t.Month(), t.Day(), 0, 0, 0, 0, t.Location())
|
||||||
|
nowBegin := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, now.Location())
|
||||||
|
return tBegin.Equal(nowBegin)
|
||||||
|
}
|
||||||
|
|
||||||
|
// GenerateTimeInfoWithTimezone 生成详细时间信息(指定时区)
|
||||||
|
func GenerateTimeInfoWithTimezone(t time.Time, timezone string) TimeInfo {
|
||||||
|
// 加载时区
|
||||||
|
loc, err := time.LoadLocation(timezone)
|
||||||
|
if err != nil {
|
||||||
|
loc = time.UTC
|
||||||
|
timezone = "UTC"
|
||||||
|
}
|
||||||
|
|
||||||
|
// 转换为指定时区时间
|
||||||
|
localTime := t.In(loc)
|
||||||
|
|
||||||
|
// 计算时区偏移量
|
||||||
|
_, offset := localTime.Zone()
|
||||||
|
offsetHours := offset / 3600
|
||||||
|
|
||||||
|
// 预先计算格式化结果,避免重复调用
|
||||||
|
utcRFC3339 := t.UTC().Format(time.RFC3339)
|
||||||
|
localRFC3339 := localTime.Format(time.RFC3339)
|
||||||
|
localDateTime := localTime.Format("2006-01-02 15:04:05")
|
||||||
|
localDate := localTime.Format("2006-01-02")
|
||||||
|
localTimeOnly := localTime.Format("15:04:05")
|
||||||
|
|
||||||
|
return TimeInfo{
|
||||||
|
UTC: utcRFC3339,
|
||||||
|
Local: localRFC3339,
|
||||||
|
Unix: t.Unix(),
|
||||||
|
Timezone: timezone,
|
||||||
|
Offset: offsetHours,
|
||||||
|
RFC3339: localRFC3339,
|
||||||
|
DateTime: localDateTime,
|
||||||
|
Date: localDate,
|
||||||
|
Time: localTimeOnly,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetUTCTimestamp 获取UTC时间戳
|
||||||
|
func GetUTCTimestamp() int64 {
|
||||||
|
return time.Now().UTC().Unix()
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetUTCTimestampFromTime 从指定时间获取UTC时间戳
|
||||||
|
func GetUTCTimestampFromTime(t time.Time) int64 {
|
||||||
|
return t.UTC().Unix()
|
||||||
|
}
|
||||||
|
|
||||||
|
// FormatTimeUTC 格式化时间为UTC字符串(ISO 8601格式)
|
||||||
|
func FormatTimeUTC(t time.Time) string {
|
||||||
|
return t.UTC().Format(time.RFC3339)
|
||||||
|
}
|
||||||
|
|
||||||
|
// IsYesterday 判断是否为昨天
|
||||||
|
func IsYesterday(t time.Time) bool {
|
||||||
|
yesterday := time.Now().AddDate(0, 0, -1)
|
||||||
|
tBegin := time.Date(t.Year(), t.Month(), t.Day(), 0, 0, 0, 0, t.Location())
|
||||||
|
yesterdayBegin := time.Date(yesterday.Year(), yesterday.Month(), yesterday.Day(), 0, 0, 0, 0, yesterday.Location())
|
||||||
|
return tBegin.Equal(yesterdayBegin)
|
||||||
|
}
|
||||||
|
|
||||||
|
// IsTomorrow 判断是否为明天
|
||||||
|
func IsTomorrow(t time.Time) bool {
|
||||||
|
tomorrow := time.Now().AddDate(0, 0, 1)
|
||||||
|
tBegin := time.Date(t.Year(), t.Month(), t.Day(), 0, 0, 0, 0, t.Location())
|
||||||
|
tomorrowBegin := time.Date(tomorrow.Year(), tomorrow.Month(), tomorrow.Day(), 0, 0, 0, 0, tomorrow.Location())
|
||||||
|
return tBegin.Equal(tomorrowBegin)
|
||||||
|
}
|
||||||
|
|
||||||
|
// GenerateTimeInfoFromContext 从gin.Context中获取用户时区并生成时间信息
|
||||||
|
func GenerateTimeInfoFromContext(t time.Time, c interface{}) TimeInfo {
|
||||||
|
// 尝试从context中获取时区
|
||||||
|
timezone := ""
|
||||||
|
|
||||||
|
// 如果传入的是gin.Context,尝试获取时区
|
||||||
|
if ginCtx, ok := c.(interface {
|
||||||
|
Get(key string) (value interface{}, exists bool)
|
||||||
|
}); ok {
|
||||||
|
if tz, exists := ginCtx.Get("user_timezone"); exists {
|
||||||
|
if tzStr, ok := tz.(string); ok && tzStr != "" {
|
||||||
|
timezone = tzStr
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 如果没有获取到时区,使用默认时区(东8区)
|
||||||
|
if timezone == "" {
|
||||||
|
timezone = "Asia/Shanghai"
|
||||||
|
}
|
||||||
|
|
||||||
|
return GenerateTimeInfoWithTimezone(t, timezone)
|
||||||
|
}
|
||||||
26
tools/version.go
Normal file
26
tools/version.go
Normal file
@@ -0,0 +1,26 @@
|
|||||||
|
package tools
|
||||||
|
|
||||||
|
import (
|
||||||
|
"os"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Version 版本号 - 在这里修改版本号(默认值)
|
||||||
|
const DefaultVersion = "1.0.1"
|
||||||
|
|
||||||
|
// GetVersion 获取版本号
|
||||||
|
// 优先从环境变量 DOCKER_TAG 或 VERSION 中读取
|
||||||
|
// 如果没有设置环境变量,则使用默认版本号
|
||||||
|
func GetVersion() string {
|
||||||
|
// 优先从 Docker 标签环境变量读取
|
||||||
|
if dockerTag := os.Getenv("DOCKER_TAG"); dockerTag != "" {
|
||||||
|
return dockerTag
|
||||||
|
}
|
||||||
|
|
||||||
|
// 从通用版本环境变量读取
|
||||||
|
if version := os.Getenv("VERSION"); version != "" {
|
||||||
|
return version
|
||||||
|
}
|
||||||
|
|
||||||
|
// 使用默认版本号
|
||||||
|
return DefaultVersion
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user