Compare commits
13 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 38ebe73e45 | |||
| e3d9bbbcc5 | |||
| 47cbdbb2de | |||
| f8f4df4073 | |||
| 684923f9cb | |||
| 545c6ef6a4 | |||
| 5cfa0d7ce5 | |||
| f62e8ecebf | |||
| 339920a940 | |||
| b66f345281 | |||
| 6547e7bca8 | |||
| 6146178111 | |||
| 0650feb0d2 |
580
MIGRATION.md
Normal file
580
MIGRATION.md
Normal file
@@ -0,0 +1,580 @@
|
|||||||
|
# 数据库迁移工具 - 完整指南
|
||||||
|
|
||||||
|
## 📌 核心特点
|
||||||
|
|
||||||
|
- ✅ **独立工具,零耦合** - 与应用代码完全分离
|
||||||
|
- ✅ **生产就绪** - 编译成二进制,无需Go环境
|
||||||
|
- ✅ **灵活配置** - 支持命令行参数、环境变量、配置文件
|
||||||
|
- ✅ **Docker友好** - 挂载配置,修改无需重启容器
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 🚀 快速开始(3步)
|
||||||
|
|
||||||
|
> **黑盒模式**:迁移工具内部调用 `migration.RunMigrationsFromConfig()` 方法,自动处理配置加载、数据库连接、迁移执行等所有细节。你只需要提供配置文件和SQL文件即可。
|
||||||
|
|
||||||
|
### 1. 复制迁移工具模板
|
||||||
|
|
||||||
|
```bash
|
||||||
|
mkdir -p cmd/migrate
|
||||||
|
cp /path/to/go-common/templates/migrate/main.go cmd/migrate/
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2. 创建迁移文件
|
||||||
|
|
||||||
|
```bash
|
||||||
|
mkdir -p migrations
|
||||||
|
```
|
||||||
|
|
||||||
|
创建 `migrations/20240101000001_create_users.sql`:
|
||||||
|
|
||||||
|
```sql
|
||||||
|
CREATE TABLE users (
|
||||||
|
id BIGINT PRIMARY KEY AUTO_INCREMENT,
|
||||||
|
username VARCHAR(255) NOT NULL,
|
||||||
|
email VARCHAR(255) NOT NULL,
|
||||||
|
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
||||||
|
);
|
||||||
|
```
|
||||||
|
|
||||||
|
### 3. 编译和使用
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 编译(生产环境推荐)
|
||||||
|
go build -o bin/migrate cmd/migrate/main.go
|
||||||
|
|
||||||
|
# 使用
|
||||||
|
./bin/migrate up # 使用默认配置
|
||||||
|
./bin/migrate up -config /path/to/config.json # 指定配置
|
||||||
|
./bin/migrate status # 查看状态
|
||||||
|
./bin/migrate -help # 查看帮助
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 💻 本地使用
|
||||||
|
|
||||||
|
### 开发环境
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 直接运行(需要Go环境)
|
||||||
|
go run cmd/migrate/main.go up
|
||||||
|
go run cmd/migrate/main.go up -config dev.json
|
||||||
|
|
||||||
|
# 编译后运行(推荐)
|
||||||
|
go build -o bin/migrate cmd/migrate/main.go
|
||||||
|
./bin/migrate up
|
||||||
|
./bin/migrate up -config config.prod.json
|
||||||
|
./bin/migrate up -c prod.json -d db/migrations
|
||||||
|
```
|
||||||
|
|
||||||
|
### 命令说明
|
||||||
|
|
||||||
|
```bash
|
||||||
|
./bin/migrate -help
|
||||||
|
|
||||||
|
# 输出:
|
||||||
|
# 用法: migrate [命令] [选项]
|
||||||
|
#
|
||||||
|
# 命令:
|
||||||
|
# up 执行所有待执行的迁移(默认)
|
||||||
|
# down 回滚最后一个迁移
|
||||||
|
# status 查看迁移状态
|
||||||
|
#
|
||||||
|
# 选项:
|
||||||
|
# -config, -c 配置文件路径(默认: config.json)
|
||||||
|
# -dir, -d 迁移文件目录(默认: migrations)
|
||||||
|
# -help, -h 显示帮助信息
|
||||||
|
```
|
||||||
|
|
||||||
|
### 配置方式
|
||||||
|
|
||||||
|
#### 方式1:配置文件(推荐开发环境)
|
||||||
|
|
||||||
|
`config.json`:
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"database": {
|
||||||
|
"type": "mysql",
|
||||||
|
"host": "localhost",
|
||||||
|
"port": 3306,
|
||||||
|
"user": "root",
|
||||||
|
"password": "password",
|
||||||
|
"database": "mydb"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
#### 方式2:环境变量指定配置文件路径(推荐生产环境)
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 使用环境变量指定配置文件路径
|
||||||
|
export CONFIG_FILE="/etc/app/config.json"
|
||||||
|
export MIGRATIONS_DIR="/opt/app/migrations"
|
||||||
|
./bin/migrate up
|
||||||
|
```
|
||||||
|
|
||||||
|
#### 配置优先级(从高到低)
|
||||||
|
|
||||||
|
1. 命令行参数 `-config` 和 `-dir`(最高)
|
||||||
|
2. 环境变量 `CONFIG_FILE` 和 `MIGRATIONS_DIR`
|
||||||
|
3. 默认值 `config.json` 和 `migrations`
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 🐳 Docker 使用
|
||||||
|
|
||||||
|
### 方式1:挂载配置文件(推荐)⭐
|
||||||
|
|
||||||
|
**优势**:修改配置无需重启容器!
|
||||||
|
|
||||||
|
#### docker-compose.yml
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
version: '3.8'
|
||||||
|
|
||||||
|
services:
|
||||||
|
app:
|
||||||
|
build: .
|
||||||
|
ports:
|
||||||
|
- "8080:8080"
|
||||||
|
volumes:
|
||||||
|
# 挂载配置文件(推荐:修改配置无需重启容器)
|
||||||
|
- ./config.json:/app/config.json:ro
|
||||||
|
# 启动时先执行迁移,再启动应用
|
||||||
|
command: sh -c "./migrate up && ./server"
|
||||||
|
```
|
||||||
|
|
||||||
|
#### 使用方式
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 1. 启动服务
|
||||||
|
docker-compose up -d
|
||||||
|
|
||||||
|
# 2. 修改配置文件
|
||||||
|
vim config.json
|
||||||
|
|
||||||
|
# 3. 手动执行迁移(无需重启容器!)
|
||||||
|
docker-compose exec app ./migrate up
|
||||||
|
|
||||||
|
# 4. 查看状态
|
||||||
|
docker-compose exec app ./migrate status
|
||||||
|
```
|
||||||
|
|
||||||
|
### 方式2:指定配置文件路径
|
||||||
|
|
||||||
|
适用于多环境部署:
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
services:
|
||||||
|
app:
|
||||||
|
build: .
|
||||||
|
volumes:
|
||||||
|
# 挂载不同环境的配置文件
|
||||||
|
- ./config.prod.json:/app/config.json:ro
|
||||||
|
command: sh -c "./migrate up -config /app/config.json && ./server"
|
||||||
|
```
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 手动切换环境(修改挂载的配置文件后)
|
||||||
|
docker-compose exec app ./migrate up
|
||||||
|
```
|
||||||
|
|
||||||
|
### 方式3:使用环境变量指定配置文件路径
|
||||||
|
|
||||||
|
适用于多环境部署,通过环境变量指定不同环境的配置文件:
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
services:
|
||||||
|
app:
|
||||||
|
build: .
|
||||||
|
environment:
|
||||||
|
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"
|
||||||
|
```
|
||||||
|
|
||||||
|
### Dockerfile
|
||||||
|
|
||||||
|
```dockerfile
|
||||||
|
FROM golang:1.21 as builder
|
||||||
|
WORKDIR /app
|
||||||
|
COPY go.mod go.sum ./
|
||||||
|
RUN go mod download
|
||||||
|
COPY . .
|
||||||
|
|
||||||
|
# 编译应用和迁移工具
|
||||||
|
RUN go build -o bin/server cmd/server/main.go
|
||||||
|
RUN go build -o bin/migrate cmd/migrate/main.go
|
||||||
|
|
||||||
|
FROM debian:bookworm-slim
|
||||||
|
WORKDIR /app
|
||||||
|
RUN apt-get update && apt-get install -y ca-certificates && rm -rf /var/lib/apt/lists/*
|
||||||
|
|
||||||
|
# 复制二进制文件和迁移文件
|
||||||
|
COPY --from=builder /app/bin/migrate .
|
||||||
|
COPY --from=builder /app/bin/server .
|
||||||
|
COPY --from=builder /app/migrations ./migrations
|
||||||
|
|
||||||
|
EXPOSE 8080
|
||||||
|
|
||||||
|
# 启动:先迁移,再启动应用
|
||||||
|
CMD ["sh", "-c", "./migrate up && ./server"]
|
||||||
|
|
||||||
|
# 注意:配置文件通过 volumes 挂载,不打包进镜像
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## ☸️ Kubernetes 部署
|
||||||
|
|
||||||
|
### 使用 Job 执行迁移
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
# k8s-job-migrate.yaml
|
||||||
|
apiVersion: batch/v1
|
||||||
|
kind: Job
|
||||||
|
metadata:
|
||||||
|
name: db-migrate
|
||||||
|
spec:
|
||||||
|
template:
|
||||||
|
spec:
|
||||||
|
containers:
|
||||||
|
- name: migrate
|
||||||
|
image: myapp:latest
|
||||||
|
command: ["./migrate", "up", "-config", "/etc/config/database.json"]
|
||||||
|
volumeMounts:
|
||||||
|
- name: config
|
||||||
|
mountPath: /etc/config
|
||||||
|
readOnly: true
|
||||||
|
volumes:
|
||||||
|
- name: config
|
||||||
|
configMap:
|
||||||
|
name: app-config
|
||||||
|
restartPolicy: OnFailure
|
||||||
|
```
|
||||||
|
|
||||||
|
### 部署流程
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 1. 创建 ConfigMap
|
||||||
|
kubectl create configmap app-config --from-file=config.json
|
||||||
|
|
||||||
|
# 2. 执行迁移
|
||||||
|
kubectl apply -f k8s-job-migrate.yaml
|
||||||
|
kubectl wait --for=condition=complete job/db-migrate
|
||||||
|
|
||||||
|
# 3. 部署应用
|
||||||
|
kubectl apply -f k8s-deployment.yaml
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 🔧 CI/CD 集成
|
||||||
|
|
||||||
|
### GitLab CI
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
# .gitlab-ci.yml
|
||||||
|
stages:
|
||||||
|
- build
|
||||||
|
- migrate
|
||||||
|
- deploy
|
||||||
|
|
||||||
|
build:
|
||||||
|
stage: build
|
||||||
|
script:
|
||||||
|
- go build -o bin/migrate cmd/migrate/main.go
|
||||||
|
- go build -o bin/server cmd/server/main.go
|
||||||
|
artifacts:
|
||||||
|
paths:
|
||||||
|
- bin/
|
||||||
|
|
||||||
|
migrate:
|
||||||
|
stage: migrate
|
||||||
|
script:
|
||||||
|
- ./bin/migrate up -config config.prod.json
|
||||||
|
environment:
|
||||||
|
name: production
|
||||||
|
|
||||||
|
deploy:
|
||||||
|
stage: deploy
|
||||||
|
script:
|
||||||
|
- ./bin/server
|
||||||
|
```
|
||||||
|
|
||||||
|
### GitHub Actions
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
# .github/workflows/deploy.yml
|
||||||
|
name: Deploy
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
branches: [main]
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
deploy:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v3
|
||||||
|
|
||||||
|
- name: Set up Go
|
||||||
|
uses: actions/setup-go@v4
|
||||||
|
with:
|
||||||
|
go-version: '1.21'
|
||||||
|
|
||||||
|
- name: Build
|
||||||
|
run: |
|
||||||
|
go build -o bin/migrate cmd/migrate/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
|
||||||
|
run: ./bin/migrate up -config config.json
|
||||||
|
|
||||||
|
- name: Deploy
|
||||||
|
run: ./bin/server
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 📁 迁移文件管理
|
||||||
|
|
||||||
|
### 文件命名规则
|
||||||
|
|
||||||
|
```
|
||||||
|
migrations/
|
||||||
|
├── 20240101000001_create_users.sql # Up 迁移
|
||||||
|
├── 20240101000001_create_users.down.sql # Down 回滚(可选)
|
||||||
|
├── 20240102000001_add_posts.sql
|
||||||
|
└── 20240102000001_add_posts.down.sql
|
||||||
|
```
|
||||||
|
|
||||||
|
格式:`{时间戳}_{描述}.sql`
|
||||||
|
|
||||||
|
### 创建迁移文件
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 获取时间戳
|
||||||
|
date +%Y%m%d%H%M%S
|
||||||
|
# 输出:20240101120000
|
||||||
|
|
||||||
|
# 创建迁移文件
|
||||||
|
vim migrations/20240101120000_create_posts.sql
|
||||||
|
```
|
||||||
|
|
||||||
|
### 迁移文件示例
|
||||||
|
|
||||||
|
**Up 文件**:
|
||||||
|
```sql
|
||||||
|
-- migrations/20240101000001_create_users.sql
|
||||||
|
CREATE TABLE users (
|
||||||
|
id BIGINT PRIMARY KEY AUTO_INCREMENT,
|
||||||
|
username VARCHAR(255) NOT NULL UNIQUE,
|
||||||
|
email VARCHAR(255) NOT NULL UNIQUE,
|
||||||
|
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX idx_users_email ON users(email);
|
||||||
|
```
|
||||||
|
|
||||||
|
**Down 文件**(可选):
|
||||||
|
```sql
|
||||||
|
-- migrations/20240101000001_create_users.down.sql
|
||||||
|
DROP INDEX idx_users_email ON users;
|
||||||
|
DROP TABLE IF EXISTS users;
|
||||||
|
```
|
||||||
|
|
||||||
|
### 兼容性建议
|
||||||
|
|
||||||
|
使用条件语句确保迁移可重复执行:
|
||||||
|
|
||||||
|
```sql
|
||||||
|
-- 创建表
|
||||||
|
CREATE TABLE IF NOT EXISTS users (...);
|
||||||
|
|
||||||
|
-- 添加列
|
||||||
|
ALTER TABLE posts ADD COLUMN IF NOT EXISTS author_id BIGINT;
|
||||||
|
|
||||||
|
-- 创建索引
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_posts_author ON posts(author_id);
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 🔍 常见问题
|
||||||
|
|
||||||
|
### Q: 为什么不直接在应用代码中调用?
|
||||||
|
|
||||||
|
**A**: **耦合度太高!** 独立工具的优势:
|
||||||
|
- ✅ 应用和迁移完全解耦
|
||||||
|
- ✅ 可以独立部署和执行
|
||||||
|
- ✅ 更灵活的部署策略
|
||||||
|
- ✅ 符合单一职责原则
|
||||||
|
|
||||||
|
### Q: 生产环境没有Go怎么办?
|
||||||
|
|
||||||
|
**A**: **编译成二进制文件**!
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 本地或CI中编译
|
||||||
|
go build -o bin/migrate cmd/migrate/main.go
|
||||||
|
|
||||||
|
# 部署二进制文件(不需要Go环境)
|
||||||
|
scp bin/migrate server:/app/
|
||||||
|
ssh server "/app/migrate up"
|
||||||
|
```
|
||||||
|
|
||||||
|
### Q: Docker中修改配置需要重启吗?
|
||||||
|
|
||||||
|
**A**: **不需要!** 使用挂载方式:
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
volumes:
|
||||||
|
- ./config.json:/app/config.json:ro
|
||||||
|
```
|
||||||
|
|
||||||
|
修改后直接执行:
|
||||||
|
```bash
|
||||||
|
docker-compose exec app ./migrate up
|
||||||
|
```
|
||||||
|
|
||||||
|
### Q: 如何指定不同的配置文件?
|
||||||
|
|
||||||
|
**A**: 使用命令行参数:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 开发环境
|
||||||
|
./migrate up -config config.dev.json
|
||||||
|
|
||||||
|
# 测试环境
|
||||||
|
./migrate up -config config.test.json
|
||||||
|
|
||||||
|
# 生产环境
|
||||||
|
./migrate up -config /etc/app/config.prod.json
|
||||||
|
```
|
||||||
|
|
||||||
|
### Q: 多个实例同时启动会有问题吗?
|
||||||
|
|
||||||
|
**A**: 不会。数据库会保证只有一个实例能执行迁移(通过版本号主键)。
|
||||||
|
|
||||||
|
### Q: Docker连不上数据库?
|
||||||
|
|
||||||
|
**A**: 注意主机名:
|
||||||
|
- ❌ `localhost`(容器内无法访问宿主机)
|
||||||
|
- ✅ `db`(docker-compose 服务名)
|
||||||
|
- ✅ `host.docker.internal`(Mac/Windows 访问宿主机)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 💡 最佳实践
|
||||||
|
|
||||||
|
### 1. 开发环境
|
||||||
|
|
||||||
|
- 使用 `go run` 快速迭代
|
||||||
|
- 使用配置文件管理不同环境
|
||||||
|
|
||||||
|
```bash
|
||||||
|
go run cmd/migrate/main.go up -config config.dev.json
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2. 测试环境
|
||||||
|
|
||||||
|
- 编译后部署,模拟生产环境
|
||||||
|
- 使用独立的数据库
|
||||||
|
|
||||||
|
```bash
|
||||||
|
go build -o bin/migrate cmd/migrate/main.go
|
||||||
|
./bin/migrate up -config config.test.json
|
||||||
|
```
|
||||||
|
|
||||||
|
### 3. 生产环境
|
||||||
|
|
||||||
|
- 编译后部署,先执行迁移再启动应用
|
||||||
|
- 使用配置文件管理敏感信息
|
||||||
|
|
||||||
|
```bash
|
||||||
|
go build -o bin/migrate cmd/migrate/main.go
|
||||||
|
./bin/migrate up -config config.json
|
||||||
|
./bin/server
|
||||||
|
```
|
||||||
|
|
||||||
|
### 4. Docker 部署
|
||||||
|
|
||||||
|
- 多阶段构建,只包含二进制文件
|
||||||
|
- 挂载配置文件,灵活修改
|
||||||
|
|
||||||
|
```dockerfile
|
||||||
|
FROM golang:1.21 as builder
|
||||||
|
RUN go build -o bin/migrate cmd/migrate/main.go
|
||||||
|
|
||||||
|
FROM debian:bookworm-slim
|
||||||
|
COPY --from=builder /app/bin/migrate .
|
||||||
|
CMD ["sh", "-c", "./migrate up && ./server"]
|
||||||
|
```
|
||||||
|
|
||||||
|
### 5. CI/CD
|
||||||
|
|
||||||
|
- 在构建阶段编译
|
||||||
|
- 部署前执行迁移
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
- build: go build -o bin/migrate cmd/migrate/main.go
|
||||||
|
- migrate: ./bin/migrate up
|
||||||
|
- deploy: ./bin/server
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 📊 推荐的项目结构
|
||||||
|
|
||||||
|
```
|
||||||
|
your-project/
|
||||||
|
├── cmd/
|
||||||
|
│ ├── migrate/
|
||||||
|
│ │ └── main.go # 迁移工具(独立)
|
||||||
|
│ └── server/
|
||||||
|
│ └── main.go # 应用主程序
|
||||||
|
├── migrations/ # 迁移SQL文件
|
||||||
|
│ ├── 20240101000001_create_users.sql
|
||||||
|
│ └── 20240101000001_create_users.down.sql
|
||||||
|
├── config.json # 配置文件
|
||||||
|
├── Dockerfile
|
||||||
|
├── docker-compose.yml
|
||||||
|
├── Makefile # 常用命令
|
||||||
|
└── go.mod
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 📚 更多资源
|
||||||
|
|
||||||
|
- [模板文件](./templates/) - 可直接复制的模板
|
||||||
|
- [完整文档](./docs/migration.md) - 详细功能文档
|
||||||
|
- [配置文档](./docs/config.md) - 配置说明
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 🎯 总结
|
||||||
|
|
||||||
|
使用 GoCommon 的迁移工具,你可以:
|
||||||
|
|
||||||
|
1. ✅ 复制一个模板文件到 `cmd/migrate/main.go`
|
||||||
|
2. ✅ 创建 SQL 迁移文件到 `migrations/`
|
||||||
|
3. ✅ 编译:`go build -o bin/migrate cmd/migrate/main.go`
|
||||||
|
4. ✅ 使用:`./bin/migrate up`
|
||||||
|
|
||||||
|
**核心优势**:
|
||||||
|
- 独立工具,零耦合
|
||||||
|
- 生产就绪,无需Go环境
|
||||||
|
- 灵活配置,支持多环境
|
||||||
|
- Docker友好,修改配置无需重启
|
||||||
|
|
||||||
|
**开箱即用,灵活强大!** 🎉
|
||||||
|
|
||||||
346
QUICKSTART.md
Normal file
346
QUICKSTART.md
Normal file
@@ -0,0 +1,346 @@
|
|||||||
|
# 快速开始指南
|
||||||
|
|
||||||
|
5分钟快速上手 GoCommon 工具库。
|
||||||
|
|
||||||
|
## 1. 安装
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 配置私有仓库
|
||||||
|
go env -w GOPRIVATE=git.toowon.com
|
||||||
|
|
||||||
|
# 安装最新版本
|
||||||
|
go get git.toowon.com/jimmy/go-common@latest
|
||||||
|
```
|
||||||
|
|
||||||
|
## 2. 创建配置文件
|
||||||
|
|
||||||
|
创建 `config.json`:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"database": {
|
||||||
|
"type": "mysql",
|
||||||
|
"host": "localhost",
|
||||||
|
"port": 3306,
|
||||||
|
"user": "root",
|
||||||
|
"password": "password",
|
||||||
|
"database": "mydb"
|
||||||
|
},
|
||||||
|
"redis": {
|
||||||
|
"host": "localhost",
|
||||||
|
"port": 6379
|
||||||
|
},
|
||||||
|
"logger": {
|
||||||
|
"level": "info",
|
||||||
|
"output": "stdout",
|
||||||
|
"async": true
|
||||||
|
},
|
||||||
|
"rateLimit": {
|
||||||
|
"enable": true,
|
||||||
|
"rate": 100,
|
||||||
|
"period": 60,
|
||||||
|
"byIP": true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## 3. 创建主程序
|
||||||
|
|
||||||
|
创建 `main.go`:
|
||||||
|
|
||||||
|
```go
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"git.toowon.com/jimmy/go-common/factory"
|
||||||
|
"git.toowon.com/jimmy/go-common/middleware"
|
||||||
|
commonhttp "git.toowon.com/jimmy/go-common/http"
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
// 从配置文件创建工厂(黑盒模式)
|
||||||
|
fac, err := factory.NewFactoryFromFile("./config.json")
|
||||||
|
if err != nil {
|
||||||
|
panic(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// 使用factory的黑盒方法获取中间件链
|
||||||
|
// 自动从配置文件读取并配置所有中间件
|
||||||
|
chain := fac.GetMiddlewareChain()
|
||||||
|
|
||||||
|
// (可选)如果项目需要额外的中间件,可以继续添加
|
||||||
|
// chain.Append(yourAuthMiddleware, yourMetricsMiddleware)
|
||||||
|
|
||||||
|
// 注册路由
|
||||||
|
http.Handle("/api/hello", chain.ThenFunc(handleHello))
|
||||||
|
http.Handle("/api/users", chain.ThenFunc(handleUsers))
|
||||||
|
|
||||||
|
// 启动服务
|
||||||
|
logger.Info("Server started on :8080")
|
||||||
|
http.ListenAndServe(":8080", nil)
|
||||||
|
}
|
||||||
|
|
||||||
|
// API处理器 - 问候接口
|
||||||
|
func handleHello(w http.ResponseWriter, r *http.Request) {
|
||||||
|
h := commonhttp.NewHandler(w, r)
|
||||||
|
|
||||||
|
h.Success(map[string]interface{}{
|
||||||
|
"message": "Hello, World!",
|
||||||
|
"timezone": h.GetTimezone(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// API处理器 - 用户列表(带分页)
|
||||||
|
func handleUsers(w http.ResponseWriter, r *http.Request) {
|
||||||
|
h := commonhttp.NewHandler(w, r)
|
||||||
|
|
||||||
|
// 解析分页参数
|
||||||
|
pagination := h.ParsePaginationRequest()
|
||||||
|
page := pagination.GetPage()
|
||||||
|
size := pagination.GetSize()
|
||||||
|
|
||||||
|
// 模拟数据
|
||||||
|
users := []map[string]interface{}{
|
||||||
|
{"id": 1, "name": "Alice"},
|
||||||
|
{"id": 2, "name": "Bob"},
|
||||||
|
}
|
||||||
|
total := int64(100)
|
||||||
|
|
||||||
|
// 返回分页数据
|
||||||
|
h.SuccessPage(users, total, page, size)
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## 4. 运行
|
||||||
|
|
||||||
|
```bash
|
||||||
|
go run main.go
|
||||||
|
```
|
||||||
|
|
||||||
|
## 5. 测试
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 测试问候接口
|
||||||
|
curl http://localhost:8080/api/hello
|
||||||
|
|
||||||
|
# 测试分页接口
|
||||||
|
curl "http://localhost:8080/api/users?page=1&page_size=10"
|
||||||
|
|
||||||
|
# 测试时区
|
||||||
|
curl -H "X-Timezone: America/New_York" http://localhost:8080/api/hello
|
||||||
|
|
||||||
|
# 测试限流(快速请求多次)
|
||||||
|
for i in {1..150}; do curl http://localhost:8080/api/hello; done
|
||||||
|
```
|
||||||
|
|
||||||
|
## 6. 常见使用场景
|
||||||
|
|
||||||
|
### 场景1:使用数据库
|
||||||
|
|
||||||
|
```go
|
||||||
|
// 获取数据库连接
|
||||||
|
db, _ := fac.GetDatabase()
|
||||||
|
|
||||||
|
// 使用GORM查询
|
||||||
|
var users []User
|
||||||
|
db.Find(&users)
|
||||||
|
```
|
||||||
|
|
||||||
|
### 场景2:使用Redis
|
||||||
|
|
||||||
|
```go
|
||||||
|
ctx := context.Background()
|
||||||
|
|
||||||
|
// 设置值
|
||||||
|
fac.RedisSet(ctx, "key", "value", time.Hour)
|
||||||
|
|
||||||
|
// 获取值
|
||||||
|
value, _ := fac.RedisGet(ctx, "key")
|
||||||
|
|
||||||
|
// 删除值
|
||||||
|
fac.RedisDelete(ctx, "key")
|
||||||
|
```
|
||||||
|
|
||||||
|
### 场景3:发送邮件
|
||||||
|
|
||||||
|
```go
|
||||||
|
// 发送简单邮件
|
||||||
|
fac.SendEmail(
|
||||||
|
[]string{"user@example.com"},
|
||||||
|
"测试邮件",
|
||||||
|
"这是邮件正文",
|
||||||
|
)
|
||||||
|
|
||||||
|
// 发送HTML邮件
|
||||||
|
fac.SendEmail(
|
||||||
|
[]string{"user@example.com"},
|
||||||
|
"测试邮件",
|
||||||
|
"纯文本内容",
|
||||||
|
"<h1>HTML内容</h1>",
|
||||||
|
)
|
||||||
|
```
|
||||||
|
|
||||||
|
### 场景4:上传文件
|
||||||
|
|
||||||
|
```go
|
||||||
|
ctx := context.Background()
|
||||||
|
|
||||||
|
// 打开文件
|
||||||
|
file, _ := os.Open("test.jpg")
|
||||||
|
defer file.Close()
|
||||||
|
|
||||||
|
// 上传文件(自动选择OSS或MinIO)
|
||||||
|
url, _ := fac.UploadFile(ctx, "images/test.jpg", file, "image/jpeg")
|
||||||
|
|
||||||
|
// 获取文件URL
|
||||||
|
url, _ := fac.GetFileURL("images/test.jpg", 3600) // 1小时后过期
|
||||||
|
```
|
||||||
|
|
||||||
|
### 场景5:记录日志
|
||||||
|
|
||||||
|
```go
|
||||||
|
// 简单日志
|
||||||
|
fac.LogInfo("用户登录成功")
|
||||||
|
fac.LogError("登录失败: %v", err)
|
||||||
|
|
||||||
|
// 带字段的日志
|
||||||
|
fac.LogInfof(map[string]interface{}{
|
||||||
|
"user_id": 123,
|
||||||
|
"action": "login",
|
||||||
|
}, "用户操作")
|
||||||
|
```
|
||||||
|
|
||||||
|
### 场景6:时间处理
|
||||||
|
|
||||||
|
```go
|
||||||
|
import "git.toowon.com/jimmy/go-common/datetime"
|
||||||
|
|
||||||
|
// 获取当前时间(带时区)
|
||||||
|
timezone := h.GetTimezone()
|
||||||
|
now := datetime.Now(timezone)
|
||||||
|
|
||||||
|
// 格式化时间
|
||||||
|
str := datetime.FormatDateTime(now)
|
||||||
|
|
||||||
|
// 解析时间
|
||||||
|
t, _ := datetime.ParseDateTime("2024-01-01 00:00:00", timezone)
|
||||||
|
|
||||||
|
// 时间计算
|
||||||
|
tomorrow := datetime.AddDays(now, 1)
|
||||||
|
startOfDay := datetime.StartOfDay(now, timezone)
|
||||||
|
```
|
||||||
|
|
||||||
|
### 场景7:数据库迁移(独立工具)⭐
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 1. 复制模板到项目
|
||||||
|
cp templates/migrate/main.go cmd/migrate/
|
||||||
|
|
||||||
|
# 2. 创建迁移文件 migrations/20240101000001_create_users.sql
|
||||||
|
|
||||||
|
# 3. 编译并使用
|
||||||
|
go build -o bin/migrate cmd/migrate/main.go
|
||||||
|
./bin/migrate up # 执行迁移
|
||||||
|
./bin/migrate status # 查看状态
|
||||||
|
```
|
||||||
|
|
||||||
|
**特点**:独立工具,零耦合,生产就绪
|
||||||
|
|
||||||
|
完整指南:[MIGRATION.md](./MIGRATION.md)
|
||||||
|
|
||||||
|
## 7. 更多文档
|
||||||
|
|
||||||
|
- [完整文档](./docs/README.md)
|
||||||
|
- [中间件文档](./docs/middleware.md)
|
||||||
|
- [工厂模式文档](./docs/factory.md)
|
||||||
|
- [HTTP工具文档](./docs/http.md)
|
||||||
|
- [配置文档](./docs/config.md)
|
||||||
|
|
||||||
|
## 常见问题
|
||||||
|
|
||||||
|
### Q: 如何自定义中间件配置?
|
||||||
|
|
||||||
|
查看 [中间件文档](./docs/middleware.md) 了解详细配置选项。
|
||||||
|
|
||||||
|
### Q: 如何使用数据库迁移?
|
||||||
|
|
||||||
|
查看 [迁移工具文档](./docs/migration.md) 了解数据库版本管理。
|
||||||
|
|
||||||
|
### Q: 支持哪些数据库?
|
||||||
|
|
||||||
|
支持 MySQL、PostgreSQL、SQLite。
|
||||||
|
|
||||||
|
### Q: 日志如何配置异步模式?
|
||||||
|
|
||||||
|
在配置文件中设置 `"async": true`,或通过代码配置:
|
||||||
|
|
||||||
|
```go
|
||||||
|
loggerConfig := &config.LoggerConfig{
|
||||||
|
Async: true,
|
||||||
|
BufferSize: 1000,
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Q: 如何添加自定义中间件?
|
||||||
|
|
||||||
|
```go
|
||||||
|
// 获取基础中间件链
|
||||||
|
chain := fac.GetMiddlewareChain()
|
||||||
|
|
||||||
|
// 添加自定义中间件
|
||||||
|
chain.Append(
|
||||||
|
yourAuthMiddleware, // 认证中间件
|
||||||
|
yourMetricsMiddleware, // 指标中间件
|
||||||
|
// 更多自定义中间件...
|
||||||
|
)
|
||||||
|
|
||||||
|
// 使用扩展后的中间件链
|
||||||
|
http.Handle("/api/secure", chain.ThenFunc(yourHandler))
|
||||||
|
```
|
||||||
|
|
||||||
|
自定义中间件示例:
|
||||||
|
|
||||||
|
```go
|
||||||
|
func authMiddleware(next http.Handler) http.Handler {
|
||||||
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
token := r.Header.Get("Authorization")
|
||||||
|
if token == "" {
|
||||||
|
http.Error(w, "Unauthorized", 401)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
// 验证token...
|
||||||
|
next.ServeHTTP(w, r)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Q: 如何按用户ID限流?
|
||||||
|
|
||||||
|
在配置文件中设置:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"rateLimit": {
|
||||||
|
"enable": true,
|
||||||
|
"rate": 100,
|
||||||
|
"period": 60,
|
||||||
|
"byUserID": true,
|
||||||
|
"byIP": false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
中间件会自动从 `X-User-ID` header 中获取用户ID进行限流。
|
||||||
|
|
||||||
|
## 下一步
|
||||||
|
|
||||||
|
恭喜!你已经掌握了 GoCommon 的基本使用。
|
||||||
|
|
||||||
|
建议阅读:
|
||||||
|
1. [中间件文档](./docs/middleware.md) - 了解更多中间件配置
|
||||||
|
2. [工厂模式文档](./docs/factory.md) - 深入了解黑盒模式
|
||||||
|
3. [示例代码](./examples/) - 查看更多实际示例
|
||||||
|
|
||||||
463
README.md
463
README.md
@@ -2,11 +2,44 @@
|
|||||||
|
|
||||||
这是一个Go语言开发的通用工具类库,为其他Go项目提供常用的工具方法集合。
|
这是一个Go语言开发的通用工具类库,为其他Go项目提供常用的工具方法集合。
|
||||||
|
|
||||||
|
**📖 快速链接**:
|
||||||
|
- [5分钟快速开始](./QUICKSTART.md)
|
||||||
|
- [数据库迁移指南](./MIGRATION.md) ⭐ 独立工具,零耦合,Docker友好
|
||||||
|
- [完整文档](./docs/README.md)
|
||||||
|
|
||||||
|
## 🌟 核心特性
|
||||||
|
|
||||||
|
### 🎯 **极简调用,减少80%重复代码**
|
||||||
|
- **工厂黑盒模式**:一个配置文件,搞定所有服务初始化
|
||||||
|
- **Handler黑盒模式**:统一的HTTP请求处理,无需重复传递 `w` 和 `r`
|
||||||
|
- **中间件链式调用**:一行代码组合多个中间件
|
||||||
|
|
||||||
|
### 🚀 **生产级特性,开箱即用**
|
||||||
|
- **异步日志**:不阻塞请求,高并发性能
|
||||||
|
- **Panic恢复**:自动捕获panic,防止服务崩溃
|
||||||
|
- **令牌桶限流**:保护API,防止滥用
|
||||||
|
- **时区自动处理**:统一管理时区,避免时间错乱
|
||||||
|
|
||||||
|
### 🔧 **灵活可扩展**
|
||||||
|
- **默认配置即可用**:传 `nil` 使用默认配置
|
||||||
|
- **完全可定制**:每个功能都支持自定义配置
|
||||||
|
- **无侵入设计**:可以独立使用任何模块
|
||||||
|
|
||||||
|
### 📦 **零外部依赖(核心功能)**
|
||||||
|
- email、sms 使用 Go 标准库实现
|
||||||
|
- 可选依赖:gorm(数据库)、redis、minio
|
||||||
|
|
||||||
## 功能模块
|
## 功能模块
|
||||||
|
|
||||||
### 1. 数据库迁移工具 (migration)
|
### 1. 数据库迁移工具 (migration)
|
||||||
提供数据库迁移功能,支持MySQL、PostgreSQL、SQLite等数据库。
|
提供数据库迁移功能,支持MySQL、PostgreSQL、SQLite等数据库。
|
||||||
|
|
||||||
|
**🎯 独立工具,零耦合**:
|
||||||
|
- ✅ 编译成独立二进制:`go build -o bin/migrate cmd/migrate/main.go`
|
||||||
|
- ✅ 生产环境无需Go环境,只需二进制文件
|
||||||
|
- ✅ 与应用代码完全解耦,可独立部署和执行
|
||||||
|
- ✅ 支持宿主机和Docker,零额外配置
|
||||||
|
|
||||||
### 2. 日期转换工具 (datetime)
|
### 2. 日期转换工具 (datetime)
|
||||||
提供日期时间转换功能,支持时区设定和多种格式转换。
|
提供日期时间转换功能,支持时区设定和多种格式转换。
|
||||||
|
|
||||||
@@ -14,7 +47,13 @@
|
|||||||
提供HTTP请求/响应处理工具,包含标准化的响应结构、分页支持和HTTP状态码与业务状态码的分离。
|
提供HTTP请求/响应处理工具,包含标准化的响应结构、分页支持和HTTP状态码与业务状态码的分离。
|
||||||
|
|
||||||
### 4. 中间件工具 (middleware)
|
### 4. 中间件工具 (middleware)
|
||||||
提供常用的HTTP中间件,包括CORS处理和时区管理。
|
提供生产级HTTP中间件,包括:
|
||||||
|
- **CORS** - 跨域资源共享
|
||||||
|
- **Timezone** - 时区处理
|
||||||
|
- **Logging** - 请求日志记录(支持异步)
|
||||||
|
- **Recovery** - Panic恢复,防止服务崩溃
|
||||||
|
- **RateLimit** - 请求限流(令牌桶算法)
|
||||||
|
- **Chain** - 中间件链式组合
|
||||||
|
|
||||||
### 5. 配置工具 (config)
|
### 5. 配置工具 (config)
|
||||||
提供从外部文件加载配置的功能,支持数据库、OSS、Redis、CORS、MinIO等配置。
|
提供从外部文件加载配置的功能,支持数据库、OSS、Redis、CORS、MinIO等配置。
|
||||||
@@ -28,12 +67,67 @@
|
|||||||
### 8. 短信工具 (sms)
|
### 8. 短信工具 (sms)
|
||||||
提供阿里云短信发送功能,支持模板短信和批量发送,使用Go标准库实现。
|
提供阿里云短信发送功能,支持模板短信和批量发送,使用Go标准库实现。
|
||||||
|
|
||||||
### 9. 工厂工具 (factory)
|
### 9. Excel导出工具 (excel)
|
||||||
提供从配置文件直接创建已初始化客户端对象的功能,包括数据库、Redis、邮件、短信、日志等,避免调用方重复实现创建逻辑。
|
提供数据导出到Excel文件的功能,支持结构体切片、自定义格式化、多工作表等特性。
|
||||||
|
|
||||||
### 10. 日志工具 (logger)
|
**功能特性**:
|
||||||
|
- 支持结构体切片自动导出
|
||||||
|
- 支持嵌套字段访问(如 "User.Name")
|
||||||
|
- 支持自定义格式化函数
|
||||||
|
- 自动调整列宽和表头样式
|
||||||
|
- 支持导出到文件或HTTP响应
|
||||||
|
|
||||||
|
### 10. 工厂工具 (factory)
|
||||||
|
提供从配置文件直接创建已初始化客户端对象的功能,包括数据库、Redis、邮件、短信、日志、Excel等,避免调用方重复实现创建逻辑。
|
||||||
|
|
||||||
|
### 11. 日志工具 (logger)
|
||||||
提供统一的日志记录功能,支持多种日志级别和输出方式,使用Go标准库实现。
|
提供统一的日志记录功能,支持多种日志级别和输出方式,使用Go标准库实现。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 🎯 Factory 黑盒模式(核心设计)
|
||||||
|
|
||||||
|
**理念**:外部项目只需传递一个配置文件路径,直接使用黑盒方法,无需获取内部对象。
|
||||||
|
|
||||||
|
### 方法分类
|
||||||
|
|
||||||
|
| 类型 | 方法 | 使用方式 | 推荐度 |
|
||||||
|
|------|------|----------|--------|
|
||||||
|
| **黑盒方法(推荐)** | | | |
|
||||||
|
| 中间件 | `GetMiddlewareChain()` | 直接使用,可Append自定义中间件 | ⭐⭐⭐ |
|
||||||
|
| 日志 | `LogInfo()`, `LogError()` 等 | 直接调用,无需获取logger对象 | ⭐⭐⭐ |
|
||||||
|
| Redis | `RedisSet()`, `RedisGet()` 等 | 直接调用,覆盖常用操作 | ⭐⭐⭐ |
|
||||||
|
| 邮件 | `SendEmail()` | 直接调用 | ⭐⭐⭐ |
|
||||||
|
| 短信 | `SendSMS()` | 直接调用 | ⭐⭐⭐ |
|
||||||
|
| 存储 | `UploadFile()`, `GetFileURL()` | 直接调用 | ⭐⭐⭐ |
|
||||||
|
| Excel导出 | `ExportToExcel()`, `ExportToExcelFile()` | 直接调用 | ⭐⭐⭐ |
|
||||||
|
| **Get方法(高级功能)** | | | |
|
||||||
|
| 数据库 | `GetDatabase()` | 返回GORM对象,用于复杂查询 | ⭐⭐ |
|
||||||
|
| Redis高级 | `GetRedisClient()` | 返回Redis客户端,用于Hash/List/Set等 | ⭐ |
|
||||||
|
| Logger高级 | `GetLogger()` | 返回Logger对象,用于Close等 | ⭐ |
|
||||||
|
|
||||||
|
### 使用示例
|
||||||
|
|
||||||
|
```go
|
||||||
|
// 创建工厂(只需配置文件路径)
|
||||||
|
fac, _ := factory.NewFactoryFromFile("config.json")
|
||||||
|
|
||||||
|
// ====== 推荐使用黑盒方法 ======
|
||||||
|
fac.LogInfo("用户登录")
|
||||||
|
fac.RedisSet(ctx, "key", "value", time.Hour)
|
||||||
|
fac.SendEmail([]string{"user@example.com"}, "主题", "内容")
|
||||||
|
chain := fac.GetMiddlewareChain()
|
||||||
|
|
||||||
|
// ====== 仅在需要高级功能时获取对象 ======
|
||||||
|
db, _ := fac.GetDatabase() // 数据库操作复杂,使用GORM
|
||||||
|
db.Find(&users)
|
||||||
|
|
||||||
|
client, _ := fac.GetRedisClient() // Redis高级操作
|
||||||
|
client.HSet(ctx, "user:1", "name", "Alice")
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
## 安装
|
## 安装
|
||||||
|
|
||||||
### 1. 配置私有仓库(重要)
|
### 1. 配置私有仓库(重要)
|
||||||
@@ -64,191 +158,183 @@ go get git.toowon.com/jimmy/go-common@v1.0.0
|
|||||||
|
|
||||||
**版本管理说明请参考 [VERSION.md](./VERSION.md)**
|
**版本管理说明请参考 [VERSION.md](./VERSION.md)**
|
||||||
|
|
||||||
## 使用示例
|
---
|
||||||
|
|
||||||
详细的使用说明请参考各模块的文档:
|
## 📚 文档导航
|
||||||
- [数据库迁移工具文档](./docs/migration.md)
|
|
||||||
- [日期转换工具文档](./docs/datetime.md)
|
|
||||||
- [HTTP Restful工具文档](./docs/http.md)
|
|
||||||
- [中间件工具文档](./docs/middleware.md)
|
|
||||||
- [配置工具文档](./docs/config.md)
|
|
||||||
- [存储工具文档](./docs/storage.md)
|
|
||||||
- [邮件工具文档](./docs/email.md)
|
|
||||||
- [短信工具文档](./docs/sms.md)
|
|
||||||
- [工厂工具文档](./docs/factory.md)
|
|
||||||
- [日志工具文档](./docs/logger.md)
|
|
||||||
|
|
||||||
### 快速示例
|
- **[快速开始指南](./QUICKSTART.md)** ⭐ - 5分钟快速上手
|
||||||
|
- [完整文档](./docs/README.md) - 所有模块详细文档
|
||||||
|
- [故障排除](./TROUBLESHOOTING.md) - 常见问题解决
|
||||||
|
- [版本管理](./VERSION.md) - 版本发布说明
|
||||||
|
|
||||||
#### 数据库迁移
|
---
|
||||||
```go
|
|
||||||
import "git.toowon.com/jimmy/go-common/migration"
|
|
||||||
|
|
||||||
migrator := migration.NewMigrator(db)
|
## 快速开始
|
||||||
migrator.AddMigration(migration.Migration{
|
|
||||||
Version: "20240101000001",
|
### 1. 创建配置文件 `config.json`
|
||||||
Description: "create_users_table",
|
|
||||||
Up: func(db *gorm.DB) error {
|
```json
|
||||||
return db.Exec("CREATE TABLE users ...").Error
|
{
|
||||||
|
"database": {
|
||||||
|
"type": "mysql",
|
||||||
|
"host": "localhost",
|
||||||
|
"port": 3306,
|
||||||
|
"user": "root",
|
||||||
|
"password": "password",
|
||||||
|
"database": "mydb"
|
||||||
},
|
},
|
||||||
})
|
"redis": {
|
||||||
migrator.Up()
|
"host": "localhost",
|
||||||
|
"port": 6379
|
||||||
|
},
|
||||||
|
"logger": {
|
||||||
|
"level": "info",
|
||||||
|
"output": "both",
|
||||||
|
"filePath": "./logs/app.log",
|
||||||
|
"async": true
|
||||||
|
}
|
||||||
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
#### 日期转换
|
### 2. 使用工厂黑盒模式(最简单,推荐)⭐
|
||||||
```go
|
|
||||||
import "git.toowon.com/jimmy/go-common/datetime"
|
|
||||||
|
|
||||||
datetime.SetDefaultTimeZone(datetime.AsiaShanghai)
|
|
||||||
now := datetime.Now()
|
|
||||||
str := datetime.FormatDateTime(now)
|
|
||||||
```
|
|
||||||
|
|
||||||
#### HTTP响应(Handler黑盒模式)
|
|
||||||
```go
|
```go
|
||||||
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"context"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"git.toowon.com/jimmy/go-common/factory"
|
||||||
commonhttp "git.toowon.com/jimmy/go-common/http"
|
commonhttp "git.toowon.com/jimmy/go-common/http"
|
||||||
)
|
)
|
||||||
|
|
||||||
// 使用Handler(黑盒模式)
|
func main() {
|
||||||
|
// 只需传入配置文件路径
|
||||||
|
fac, _ := factory.NewFactoryFromFile("config.json")
|
||||||
|
|
||||||
|
// 获取配置好的中间件链(黑盒)
|
||||||
|
chain := fac.GetMiddlewareChain()
|
||||||
|
|
||||||
|
// (可选)添加自定义中间件
|
||||||
|
chain.Append(yourAuthMiddleware)
|
||||||
|
|
||||||
|
// 注册路由
|
||||||
|
http.Handle("/api/hello", chain.ThenFunc(handleHello))
|
||||||
|
http.ListenAndServe(":8080", nil)
|
||||||
|
}
|
||||||
|
|
||||||
|
func handleHello(w http.ResponseWriter, r *http.Request) {
|
||||||
|
h := commonhttp.NewHandler(w, r)
|
||||||
|
fac, _ := factory.NewFactoryFromFile("config.json")
|
||||||
|
ctx := context.Background()
|
||||||
|
|
||||||
|
// 使用黑盒方法(无需获取对象)
|
||||||
|
fac.LogInfo("处理请求: /api/hello")
|
||||||
|
fac.RedisSet(ctx, "last_visit", time.Now().String(), time.Hour)
|
||||||
|
|
||||||
|
h.Success(map[string]interface{}{
|
||||||
|
"message": "Hello!",
|
||||||
|
"timezone": h.GetTimezone(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 3. 运行项目
|
||||||
|
|
||||||
|
```bash
|
||||||
|
go run main.go
|
||||||
|
# 访问 http://localhost:8080/api/hello
|
||||||
|
```
|
||||||
|
|
||||||
|
## 核心功能示例
|
||||||
|
|
||||||
|
详细文档请参考:[完整文档](./docs/README.md) | [快速开始](./QUICKSTART.md)
|
||||||
|
|
||||||
|
### 数据库迁移
|
||||||
|
```bash
|
||||||
|
# 编译独立工具
|
||||||
|
go build -o bin/migrate cmd/migrate/main.go
|
||||||
|
|
||||||
|
# 执行迁移
|
||||||
|
./bin/migrate up # 默认配置
|
||||||
|
./bin/migrate up -config /path/to/config.json # 指定配置
|
||||||
|
./bin/migrate status # 查看状态
|
||||||
|
```
|
||||||
|
|
||||||
|
**详细说明**:[数据库迁移指南](./MIGRATION.md) ⭐
|
||||||
|
|
||||||
|
### 工厂黑盒模式(推荐)
|
||||||
|
```go
|
||||||
|
import "git.toowon.com/jimmy/go-common/factory"
|
||||||
|
|
||||||
|
fac, _ := factory.NewFactoryFromFile("config.json")
|
||||||
|
|
||||||
|
// 中间件
|
||||||
|
chain := fac.GetMiddlewareChain()
|
||||||
|
chain.Append(yourAuthMiddleware) // 添加自定义中间件
|
||||||
|
|
||||||
|
// 日志
|
||||||
|
fac.LogInfo("用户登录成功")
|
||||||
|
|
||||||
|
// Redis
|
||||||
|
fac.RedisSet(ctx, "key", "value", time.Hour)
|
||||||
|
|
||||||
|
// 邮件/短信
|
||||||
|
fac.SendEmail([]string{"user@example.com"}, "主题", "内容")
|
||||||
|
fac.SendSMS([]string{"13800138000"}, map[string]string{"code": "123456"})
|
||||||
|
|
||||||
|
// 文件上传
|
||||||
|
url, _ := fac.UploadFile(ctx, "images/test.jpg", file, "image/jpeg")
|
||||||
|
|
||||||
|
// Excel导出
|
||||||
|
columns := []factory.ExportColumn{
|
||||||
|
{Header: "ID", Field: "ID", Width: 10},
|
||||||
|
{Header: "姓名", Field: "Name", Width: 20},
|
||||||
|
{Header: "邮箱", Field: "Email", Width: 30},
|
||||||
|
}
|
||||||
|
fac.ExportToExcelFile("users.xlsx", "用户列表", columns, users)
|
||||||
|
|
||||||
|
// 数据库(高级功能)
|
||||||
|
db, _ := fac.GetDatabase()
|
||||||
|
db.Find(&users)
|
||||||
|
```
|
||||||
|
|
||||||
|
### HTTP处理器
|
||||||
|
```go
|
||||||
|
import commonhttp "git.toowon.com/jimmy/go-common/http"
|
||||||
|
|
||||||
func GetUser(h *commonhttp.Handler) {
|
func GetUser(h *commonhttp.Handler) {
|
||||||
id := h.GetQueryInt64("id", 0) // 无需传递r
|
id := h.GetQueryInt64("id", 0)
|
||||||
h.Success(data) // 无需传递w
|
h.Success(data)
|
||||||
}
|
}
|
||||||
|
|
||||||
http.HandleFunc("/user", commonhttp.HandleFunc(GetUser))
|
http.HandleFunc("/user", commonhttp.HandleFunc(GetUser))
|
||||||
```
|
```
|
||||||
|
|
||||||
#### 中间件
|
### 日期时间
|
||||||
```go
|
**推荐方式:通过 factory 使用(黑盒模式)**
|
||||||
import (
|
|
||||||
"git.toowon.com/jimmy/go-common/middleware"
|
|
||||||
commonhttp "git.toowon.com/jimmy/go-common/http"
|
|
||||||
)
|
|
||||||
|
|
||||||
// CORS + 时区中间件
|
|
||||||
chain := middleware.NewChain(
|
|
||||||
middleware.CORS(),
|
|
||||||
middleware.Timezone,
|
|
||||||
)
|
|
||||||
handler := chain.ThenFunc(yourHandler)
|
|
||||||
|
|
||||||
// 在Handler中获取时区
|
|
||||||
func handler(h *commonhttp.Handler) {
|
|
||||||
timezone := h.GetTimezone()
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
#### 配置管理
|
|
||||||
```go
|
|
||||||
import "git.toowon.com/jimmy/go-common/config"
|
|
||||||
|
|
||||||
// 从文件加载配置
|
|
||||||
cfg, err := config.LoadFromFile("./config.json")
|
|
||||||
|
|
||||||
// 获取各种配置
|
|
||||||
dsn, _ := cfg.GetDatabaseDSN()
|
|
||||||
redisAddr := cfg.GetRedisAddr()
|
|
||||||
corsConfig := cfg.GetCORS()
|
|
||||||
```
|
|
||||||
|
|
||||||
#### 文件上传和查看(推荐使用工厂黑盒模式)
|
|
||||||
```go
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"git.toowon.com/jimmy/go-common/factory"
|
|
||||||
)
|
|
||||||
|
|
||||||
fac, _ := factory.NewFactoryFromFile("./config.json")
|
|
||||||
ctx := context.Background()
|
|
||||||
|
|
||||||
// 黑盒模式(推荐,自动选择OSS或MinIO)
|
|
||||||
file, _ := os.Open("test.jpg")
|
|
||||||
url, _ := fac.UploadFile(ctx, "images/test.jpg", file, "image/jpeg")
|
|
||||||
|
|
||||||
// 获取文件URL
|
|
||||||
url, _ := fac.GetFileURL("images/test.jpg", 0) // 永久有效
|
|
||||||
url, _ := fac.GetFileURL("images/test.jpg", 3600) // 1小时后过期
|
|
||||||
|
|
||||||
// 或使用存储处理器(需要HTTP处理器时)
|
|
||||||
storage, _ := storage.NewStorage(storage.StorageTypeOSS, cfg)
|
|
||||||
uploadHandler := storage.NewUploadHandler(...)
|
|
||||||
```
|
|
||||||
|
|
||||||
#### 邮件发送(推荐使用工厂黑盒模式)
|
|
||||||
```go
|
```go
|
||||||
import "git.toowon.com/jimmy/go-common/factory"
|
import "git.toowon.com/jimmy/go-common/factory"
|
||||||
|
|
||||||
fac, _ := factory.NewFactoryFromFile("./config.json")
|
fac, _ := factory.NewFactoryFromFile("config.json")
|
||||||
|
now := fac.Now("Asia/Shanghai")
|
||||||
// 黑盒模式(推荐)
|
str := fac.FormatDateTime(now)
|
||||||
fac.SendEmail([]string{"user@example.com"}, "主题", "正文")
|
|
||||||
fac.SendEmail([]string{"user@example.com"}, "主题", "纯文本", "<h1>HTML内容</h1>")
|
|
||||||
|
|
||||||
// 或获取客户端对象(需要高级功能时)
|
|
||||||
emailClient, _ := fac.GetEmailClient()
|
|
||||||
emailClient.SendSimple(...)
|
|
||||||
```
|
```
|
||||||
|
|
||||||
#### 短信发送(推荐使用工厂黑盒模式)
|
**或者直接使用 tools 包:**
|
||||||
|
|
||||||
```go
|
```go
|
||||||
import "git.toowon.com/jimmy/go-common/factory"
|
import "git.toowon.com/jimmy/go-common/tools"
|
||||||
|
|
||||||
fac, _ := factory.NewFactoryFromFile("./config.json")
|
tools.SetDefaultTimeZone(tools.AsiaShanghai)
|
||||||
|
now := tools.Now()
|
||||||
// 黑盒模式(推荐)
|
str := tools.FormatDateTime(now)
|
||||||
fac.SendSMS([]string{"13800138000"}, map[string]string{"code": "123456"})
|
|
||||||
|
|
||||||
// 或获取客户端对象(需要高级功能时)
|
|
||||||
smsClient, _ := fac.GetSMSClient()
|
|
||||||
smsClient.SendSimple(...)
|
|
||||||
```
|
```
|
||||||
|
|
||||||
#### 使用工厂(黑盒模式,推荐)
|
更多示例:[examples目录](./examples/)
|
||||||
```go
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"git.toowon.com/jimmy/go-common/factory"
|
|
||||||
)
|
|
||||||
|
|
||||||
// 从配置文件创建工厂(最推荐)
|
|
||||||
fac, _ := factory.NewFactoryFromFile("./config.json")
|
|
||||||
ctx := context.Background()
|
|
||||||
|
|
||||||
// 日志(黑盒模式,直接调用)
|
|
||||||
fac.LogInfo("用户登录成功")
|
|
||||||
fac.LogError("登录失败: %v", err)
|
|
||||||
|
|
||||||
// 邮件发送(黑盒模式,直接调用)
|
|
||||||
fac.SendEmail([]string{"user@example.com"}, "验证码", "您的验证码是:123456")
|
|
||||||
|
|
||||||
// 短信发送(黑盒模式,直接调用)
|
|
||||||
fac.SendSMS([]string{"13800138000"}, map[string]string{"code": "123456"})
|
|
||||||
|
|
||||||
// 文件上传(黑盒模式,自动选择OSS或MinIO)
|
|
||||||
file, _ := os.Open("test.jpg")
|
|
||||||
url, _ := fac.UploadFile(ctx, "images/test.jpg", file, "image/jpeg")
|
|
||||||
|
|
||||||
// 获取文件URL
|
|
||||||
url, _ := fac.GetFileURL("images/test.jpg", 0) // 永久有效
|
|
||||||
url, _ := fac.GetFileURL("images/test.jpg", 3600) // 1小时后过期
|
|
||||||
|
|
||||||
// Redis操作(黑盒模式,直接调用)
|
|
||||||
fac.RedisSet(ctx, "key", "value", time.Hour)
|
|
||||||
value, _ := fac.RedisGet(ctx, "key")
|
|
||||||
fac.RedisDelete(ctx, "key")
|
|
||||||
|
|
||||||
// 数据库(黑盒模式,获取已初始化对象)
|
|
||||||
db, _ := fac.GetDatabase()
|
|
||||||
db.Find(&users)
|
|
||||||
|
|
||||||
// Redis客户端(黑盒模式,获取已初始化对象)
|
|
||||||
redisClient, _ := fac.GetRedisClient()
|
|
||||||
redisClient.HGet(ctx, "key", "field").Result()
|
|
||||||
```
|
|
||||||
|
|
||||||
更多示例请查看 [examples](./examples/) 目录。
|
|
||||||
|
|
||||||
## 版本管理
|
## 版本管理
|
||||||
|
|
||||||
@@ -276,3 +362,62 @@ go get git.toowon.com/jimmy/go-common@v1.0.0
|
|||||||
|
|
||||||
**详细版本管理说明请参考 [VERSION.md](./VERSION.md)**
|
**详细版本管理说明请参考 [VERSION.md](./VERSION.md)**
|
||||||
|
|
||||||
|
## 最佳实践
|
||||||
|
|
||||||
|
### 生产环境配置
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"logger": {
|
||||||
|
"async": true, // 开启异步日志
|
||||||
|
"bufferSize": 1000
|
||||||
|
},
|
||||||
|
"database": {
|
||||||
|
"maxOpenConns": 100, // 连接池配置
|
||||||
|
"maxIdleConns": 10,
|
||||||
|
"connMaxLifetime": 3600
|
||||||
|
},
|
||||||
|
"rateLimit": {
|
||||||
|
"enable": true, // 开启限流
|
||||||
|
"rate": 100,
|
||||||
|
"period": 60,
|
||||||
|
"byIP": true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 使用建议
|
||||||
|
- ✅ 使用工厂黑盒模式,减少重复代码
|
||||||
|
- ✅ 生产环境开启异步日志和限流
|
||||||
|
- ✅ 配置Recovery中间件防止panic
|
||||||
|
- ✅ 明确指定CORS允许的源
|
||||||
|
- ❌ 避免在循环中创建logger
|
||||||
|
- ❌ 避免使用同步日志记录大量日志
|
||||||
|
|
||||||
|
## 故障排除
|
||||||
|
|
||||||
|
常见问题请查看 [TROUBLESHOOTING.md](./TROUBLESHOOTING.md)
|
||||||
|
|
||||||
|
## 贡献指南
|
||||||
|
|
||||||
|
欢迎贡献代码!请遵循以下步骤:
|
||||||
|
|
||||||
|
1. Fork 本仓库
|
||||||
|
2. 创建特性分支 (`git checkout -b feature/AmazingFeature`)
|
||||||
|
3. 提交更改 (`git commit -m 'Add some AmazingFeature'`)
|
||||||
|
4. 推送到分支 (`git push origin feature/AmazingFeature`)
|
||||||
|
5. 创建 Pull Request
|
||||||
|
|
||||||
|
## 许可证
|
||||||
|
|
||||||
|
MIT License
|
||||||
|
|
||||||
|
## 联系方式
|
||||||
|
|
||||||
|
- 作者:Jimmy
|
||||||
|
- 邮箱:jimmy@toowon.com
|
||||||
|
- 项目地址:git.toowon.com/jimmy/go-common
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
⭐ 如果这个项目对你有帮助,请给个 Star!
|
||||||
|
|
||||||
|
|||||||
@@ -5,8 +5,6 @@ import (
|
|||||||
"fmt"
|
"fmt"
|
||||||
"os"
|
"os"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
|
|
||||||
"git.toowon.com/jimmy/go-common/middleware"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
// Config 应用配置
|
// Config 应用配置
|
||||||
@@ -19,6 +17,7 @@ type Config struct {
|
|||||||
Email *EmailConfig `json:"email"`
|
Email *EmailConfig `json:"email"`
|
||||||
SMS *SMSConfig `json:"sms"`
|
SMS *SMSConfig `json:"sms"`
|
||||||
Logger *LoggerConfig `json:"logger"`
|
Logger *LoggerConfig `json:"logger"`
|
||||||
|
RateLimit *RateLimitConfig `json:"rateLimit"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// DatabaseConfig 数据库配置
|
// DatabaseConfig 数据库配置
|
||||||
@@ -246,6 +245,24 @@ type LoggerConfig struct {
|
|||||||
BufferSize int `json:"bufferSize"`
|
BufferSize int `json:"bufferSize"`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// RateLimitConfig 限流配置
|
||||||
|
type RateLimitConfig struct {
|
||||||
|
// Enable 是否启用限流
|
||||||
|
Enable bool `json:"enable"`
|
||||||
|
|
||||||
|
// Rate 每个时间窗口允许的请求数量
|
||||||
|
Rate int `json:"rate"`
|
||||||
|
|
||||||
|
// Period 时间窗口(秒)
|
||||||
|
Period int `json:"period"`
|
||||||
|
|
||||||
|
// ByIP 按IP限流
|
||||||
|
ByIP bool `json:"byIP"`
|
||||||
|
|
||||||
|
// ByUserID 按用户ID限流(从X-User-ID header获取)
|
||||||
|
ByUserID bool `json:"byUserID"`
|
||||||
|
}
|
||||||
|
|
||||||
// LoadFromFile 从文件加载配置
|
// LoadFromFile 从文件加载配置
|
||||||
// filePath: 配置文件路径(支持绝对路径和相对路径)
|
// filePath: 配置文件路径(支持绝对路径和相对路径)
|
||||||
func LoadFromFile(filePath string) (*Config, error) {
|
func LoadFromFile(filePath string) (*Config, error) {
|
||||||
@@ -380,6 +397,19 @@ func (c *Config) setDefaults() {
|
|||||||
c.Logger.Output = "stdout"
|
c.Logger.Output = "stdout"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 限流默认值
|
||||||
|
if c.RateLimit != nil {
|
||||||
|
if c.RateLimit.Rate == 0 {
|
||||||
|
c.RateLimit.Rate = 100 // 默认每个窗口100个请求
|
||||||
|
}
|
||||||
|
if c.RateLimit.Period == 0 {
|
||||||
|
c.RateLimit.Period = 60 // 默认时间窗口60秒
|
||||||
|
}
|
||||||
|
if !c.RateLimit.ByIP && !c.RateLimit.ByUserID {
|
||||||
|
c.RateLimit.ByIP = true // 默认按IP限流
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// GetDatabase 获取数据库配置
|
// GetDatabase 获取数据库配置
|
||||||
@@ -397,20 +427,11 @@ func (c *Config) GetRedis() *RedisConfig {
|
|||||||
return c.Redis
|
return c.Redis
|
||||||
}
|
}
|
||||||
|
|
||||||
// GetCORS 获取CORS配置,并转换为middleware.CORSConfig
|
// GetCORS 获取CORS配置
|
||||||
func (c *Config) GetCORS() *middleware.CORSConfig {
|
// 返回的是 config.CORSConfig,需要转换为 middleware.CORSConfig 时
|
||||||
if c.CORS == nil {
|
// 可以使用 middleware.CORSFromConfig() 函数
|
||||||
return middleware.DefaultCORSConfig()
|
func (c *Config) GetCORS() *CORSConfig {
|
||||||
}
|
return c.CORS
|
||||||
|
|
||||||
return &middleware.CORSConfig{
|
|
||||||
AllowedOrigins: c.CORS.AllowedOrigins,
|
|
||||||
AllowedMethods: c.CORS.AllowedMethods,
|
|
||||||
AllowedHeaders: c.CORS.AllowedHeaders,
|
|
||||||
ExposedHeaders: c.CORS.ExposedHeaders,
|
|
||||||
AllowCredentials: c.CORS.AllowCredentials,
|
|
||||||
MaxAge: c.CORS.MaxAge,
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// GetMinIO 获取MinIO配置
|
// GetMinIO 获取MinIO配置
|
||||||
|
|||||||
@@ -78,6 +78,13 @@
|
|||||||
"disableTimestamp": false,
|
"disableTimestamp": false,
|
||||||
"async": false,
|
"async": false,
|
||||||
"bufferSize": 1000
|
"bufferSize": 1000
|
||||||
|
},
|
||||||
|
"rateLimit": {
|
||||||
|
"enable": true,
|
||||||
|
"rate": 100,
|
||||||
|
"period": 60,
|
||||||
|
"byIP": true,
|
||||||
|
"byUserID": false
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -3,15 +3,18 @@
|
|||||||
## 目录
|
## 目录
|
||||||
|
|
||||||
- [数据库迁移工具](./migration.md) - 数据库版本管理和迁移
|
- [数据库迁移工具](./migration.md) - 数据库版本管理和迁移
|
||||||
|
- [完整使用指南](../MIGRATION.md) ⭐ - 独立工具,零耦合,Docker友好
|
||||||
- [日期转换工具](./datetime.md) - 日期时间处理和时区转换
|
- [日期转换工具](./datetime.md) - 日期时间处理和时区转换
|
||||||
- [HTTP Restful工具](./http.md) - HTTP请求响应处理和分页
|
- [HTTP Restful工具](./http.md) - HTTP请求响应处理和分页
|
||||||
- [中间件工具](./middleware.md) - CORS和时区处理中间件
|
- [中间件工具](./middleware.md) - 生产级HTTP中间件(CORS、时区、日志、Recovery、限流)
|
||||||
- [配置工具](./config.md) - 外部配置文件加载和管理
|
- [配置工具](./config.md) - 外部配置文件加载和管理
|
||||||
- [存储工具](./storage.md) - 文件上传和查看(OSS、MinIO)
|
- [存储工具](./storage.md) - 文件上传和查看(OSS、MinIO)
|
||||||
- [邮件工具](./email.md) - SMTP邮件发送
|
- [邮件工具](./email.md) - SMTP邮件发送
|
||||||
- [短信工具](./sms.md) - 阿里云短信发送
|
- [短信工具](./sms.md) - 阿里云短信发送
|
||||||
|
- [Excel导出工具](./excel.md) - 数据导出到Excel文件
|
||||||
- [工厂工具](./factory.md) - 从配置直接创建已初始化客户端对象
|
- [工厂工具](./factory.md) - 从配置直接创建已初始化客户端对象
|
||||||
- [日志工具](./logger.md) - 统一的日志记录功能
|
- [日志工具](./logger.md) - 统一的日志记录功能
|
||||||
|
- [国际化工具](./i18n.md) - 多语言内容管理和国际化支持
|
||||||
|
|
||||||
## 快速开始
|
## 快速开始
|
||||||
|
|
||||||
@@ -23,66 +26,101 @@ go get git.toowon.com/jimmy/go-common
|
|||||||
|
|
||||||
### 使用示例
|
### 使用示例
|
||||||
|
|
||||||
#### 数据库迁移
|
#### 数据库迁移(独立工具,零耦合)
|
||||||
|
|
||||||
```go
|
```bash
|
||||||
import "git.toowon.com/jimmy/go-common/migration"
|
# 1. 复制模板:templates/migrate/main.go -> cmd/migrate/main.go
|
||||||
|
# 2. 创建迁移文件:migrations/20240101000001_create_users.sql
|
||||||
|
|
||||||
migrator := migration.NewMigrator(db)
|
# 3. 开发环境
|
||||||
migrator.AddMigration(migration.Migration{
|
go run cmd/migrate/main.go up
|
||||||
Version: "20240101000001",
|
|
||||||
Description: "create_users_table",
|
# 4. 生产环境(编译后使用,推荐)
|
||||||
Up: func(db *gorm.DB) error {
|
go build -o bin/migrate cmd/migrate/main.go
|
||||||
return db.Exec("CREATE TABLE users ...").Error
|
./bin/migrate up # 使用默认配置
|
||||||
},
|
./bin/migrate up -config /path/to/config.json # 指定配置
|
||||||
})
|
./bin/migrate status # 查看状态
|
||||||
migrator.Up()
|
|
||||||
|
# 5. Docker(挂载配置,修改无需重启)
|
||||||
|
# docker-compose.yml:
|
||||||
|
# volumes:
|
||||||
|
# - ./config.json:/app/config.json:ro
|
||||||
|
# command: sh -c "./migrate up && ./server"
|
||||||
```
|
```
|
||||||
|
|
||||||
|
**迁移文件示例**(`migrations/20240101000001_create_users.sql`):
|
||||||
|
```sql
|
||||||
|
CREATE TABLE users (id BIGINT PRIMARY KEY AUTO_INCREMENT, ...);
|
||||||
|
```
|
||||||
|
|
||||||
|
**优势**:独立工具,零耦合,支持命令行参数,Docker友好
|
||||||
|
|
||||||
|
详细说明:[MIGRATION.md](../MIGRATION.md)
|
||||||
|
|
||||||
#### 日期转换
|
#### 日期转换
|
||||||
|
|
||||||
```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)
|
||||||
```
|
```
|
||||||
|
|
||||||
#### 中间件
|
#### 中间件(生产级配置)
|
||||||
|
|
||||||
```go
|
```go
|
||||||
import (
|
import (
|
||||||
"net/http"
|
"time"
|
||||||
"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"
|
||||||
)
|
)
|
||||||
|
|
||||||
// CORS + 时区中间件
|
// 完整的中间件链
|
||||||
chain := middleware.NewChain(
|
chain := middleware.NewChain(
|
||||||
middleware.CORS(),
|
middleware.Recovery(nil), // Panic恢复
|
||||||
middleware.Timezone,
|
middleware.Logging(nil), // 请求日志
|
||||||
|
middleware.RateLimitByIP(100, time.Minute), // 限流
|
||||||
|
middleware.CORS(nil), // CORS
|
||||||
|
middleware.Timezone, // 时区
|
||||||
)
|
)
|
||||||
|
|
||||||
handler := chain.ThenFunc(func(w http.ResponseWriter, r *http.Request) {
|
handler := chain.ThenFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
h := commonhttp.NewHandler(w, r)
|
h := commonhttp.NewHandler(w, r)
|
||||||
// 在Handler中获取时区
|
|
||||||
timezone := h.GetTimezone()
|
timezone := h.GetTimezone()
|
||||||
h.Success(data)
|
h.Success(data)
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -163,13 +163,26 @@ addr := config.GetRedisAddr()
|
|||||||
### 5. 获取CORS配置
|
### 5. 获取CORS配置
|
||||||
|
|
||||||
```go
|
```go
|
||||||
// 获取CORS配置(返回middleware.CORSConfig类型,可直接用于中间件)
|
// 获取CORS配置(返回config.CORSConfig类型)
|
||||||
corsConfig := config.GetCORS()
|
configCORS := config.GetCORS()
|
||||||
|
|
||||||
// 使用CORS中间件
|
// 转换为middleware.CORSConfig并使用CORS中间件
|
||||||
import "git.toowon.com/jimmy/go-common/middleware"
|
import "git.toowon.com/jimmy/go-common/middleware"
|
||||||
|
|
||||||
|
var middlewareCORS *middleware.CORSConfig
|
||||||
|
if configCORS != nil {
|
||||||
|
middlewareCORS = middleware.NewCORSConfig(
|
||||||
|
configCORS.AllowedOrigins,
|
||||||
|
configCORS.AllowedMethods,
|
||||||
|
configCORS.AllowedHeaders,
|
||||||
|
configCORS.ExposedHeaders,
|
||||||
|
configCORS.AllowCredentials,
|
||||||
|
configCORS.MaxAge,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
chain := middleware.NewChain(
|
chain := middleware.NewChain(
|
||||||
middleware.CORS(corsConfig),
|
middleware.CORS(middlewareCORS),
|
||||||
)
|
)
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -328,9 +341,20 @@ func main() {
|
|||||||
fmt.Printf("Redis Address: %s\n", redisAddr)
|
fmt.Printf("Redis Address: %s\n", redisAddr)
|
||||||
|
|
||||||
// 使用CORS配置
|
// 使用CORS配置
|
||||||
corsConfig := cfg.GetCORS()
|
configCORS := cfg.GetCORS()
|
||||||
|
var middlewareCORS *middleware.CORSConfig
|
||||||
|
if configCORS != nil {
|
||||||
|
middlewareCORS = middleware.NewCORSConfig(
|
||||||
|
configCORS.AllowedOrigins,
|
||||||
|
configCORS.AllowedMethods,
|
||||||
|
configCORS.AllowedHeaders,
|
||||||
|
configCORS.ExposedHeaders,
|
||||||
|
configCORS.AllowCredentials,
|
||||||
|
configCORS.MaxAge,
|
||||||
|
)
|
||||||
|
}
|
||||||
chain := middleware.NewChain(
|
chain := middleware.NewChain(
|
||||||
middleware.CORS(corsConfig),
|
middleware.CORS(middlewareCORS),
|
||||||
)
|
)
|
||||||
|
|
||||||
// 使用OSS配置
|
// 使用OSS配置
|
||||||
|
|||||||
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转换示例
|
|
||||||
|
|
||||||
|
|||||||
447
docs/excel.md
Normal file
447
docs/excel.md
Normal file
@@ -0,0 +1,447 @@
|
|||||||
|
# Excel导出工具文档
|
||||||
|
|
||||||
|
## 概述
|
||||||
|
|
||||||
|
Excel导出工具提供了将数据导出到Excel文件的功能,支持结构体切片、自定义格式化、多工作表等特性。通过工厂模式,外部项目可以方便地使用Excel导出功能。
|
||||||
|
|
||||||
|
## 功能特性
|
||||||
|
|
||||||
|
- **黑盒模式**:提供直接调用的方法,无需获取Excel对象
|
||||||
|
- **延迟初始化**:Excel导出器在首次使用时才创建
|
||||||
|
- **支持结构体切片**:自动将结构体切片转换为Excel行数据
|
||||||
|
- **支持嵌套字段**:支持访问嵌套结构体字段(如 "User.Name")
|
||||||
|
- **自定义格式化**:支持自定义字段值的格式化函数
|
||||||
|
- **自动列宽**:自动调整列宽以适应内容
|
||||||
|
- **表头样式**:自动应用表头样式(加粗、背景色等)
|
||||||
|
- **智能工作表管理**:自动处理工作表的创建和删除,避免产生空sheet
|
||||||
|
- **ExportData接口**:支持实现ExportData接口进行高级定制
|
||||||
|
- **空数据处理**:即使数据为空(nil或空切片),也会正常生成表头
|
||||||
|
- **统一接口**:只暴露 `ExportToWriter` 一个核心方法
|
||||||
|
|
||||||
|
## 使用方法
|
||||||
|
|
||||||
|
### 1. 创建工厂
|
||||||
|
|
||||||
|
```go
|
||||||
|
import "git.toowon.com/jimmy/go-common/factory"
|
||||||
|
|
||||||
|
// 从配置文件创建
|
||||||
|
fac, err := factory.NewFactoryFromFile("./config.json")
|
||||||
|
|
||||||
|
// 或Excel导出不需要配置,可以传nil
|
||||||
|
fac := factory.NewFactory(nil)
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2. 导出结构体切片到文件
|
||||||
|
|
||||||
|
```go
|
||||||
|
// 定义结构体
|
||||||
|
type User struct {
|
||||||
|
ID int `json:"id"`
|
||||||
|
Name string `json:"name"`
|
||||||
|
Email string `json:"email"`
|
||||||
|
CreatedAt time.Time `json:"created_at"`
|
||||||
|
Status int `json:"status"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// 准备数据
|
||||||
|
users := []User{
|
||||||
|
{ID: 1, Name: "Alice", Email: "alice@example.com", CreatedAt: time.Now(), Status: 1},
|
||||||
|
{ID: 2, Name: "Bob", Email: "bob@example.com", CreatedAt: time.Now(), Status: 1},
|
||||||
|
}
|
||||||
|
|
||||||
|
// 定义导出列
|
||||||
|
columns := []factory.ExportColumn{
|
||||||
|
{Header: "ID", Field: "ID", Width: 10},
|
||||||
|
{Header: "姓名", Field: "Name", Width: 20},
|
||||||
|
{Header: "邮箱", Field: "Email", Width: 30},
|
||||||
|
{Header: "创建时间", Field: "CreatedAt", Width: 20},
|
||||||
|
{Header: "状态", Field: "Status", Width: 10},
|
||||||
|
}
|
||||||
|
|
||||||
|
// 导出到文件
|
||||||
|
err := fac.ExportToExcelFile("users.xlsx", "用户列表", columns, users)
|
||||||
|
if err != nil {
|
||||||
|
log.Fatal(err)
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 3. 导出到HTTP响应
|
||||||
|
|
||||||
|
```go
|
||||||
|
import "net/http"
|
||||||
|
|
||||||
|
func exportUsersHandler(w http.ResponseWriter, r *http.Request) {
|
||||||
|
fac, _ := factory.NewFactoryFromFile("./config.json")
|
||||||
|
|
||||||
|
users := []User{
|
||||||
|
{ID: 1, Name: "Alice", Email: "alice@example.com", CreatedAt: time.Now(), Status: 1},
|
||||||
|
{ID: 2, Name: "Bob", Email: "bob@example.com", CreatedAt: time.Now(), Status: 1},
|
||||||
|
}
|
||||||
|
|
||||||
|
columns := []factory.ExportColumn{
|
||||||
|
{Header: "ID", Field: "ID"},
|
||||||
|
{Header: "姓名", Field: "Name"},
|
||||||
|
{Header: "邮箱", Field: "Email"},
|
||||||
|
}
|
||||||
|
|
||||||
|
// 设置HTTP响应头
|
||||||
|
w.Header().Set("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
|
||||||
|
w.Header().Set("Content-Disposition", "attachment; filename=users.xlsx")
|
||||||
|
|
||||||
|
// 导出到响应
|
||||||
|
err := fac.ExportToExcel(w, "用户列表", columns, users)
|
||||||
|
if err != nil {
|
||||||
|
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 4. 使用格式化函数
|
||||||
|
|
||||||
|
```go
|
||||||
|
import "git.toowon.com/jimmy/go-common/excel"
|
||||||
|
|
||||||
|
columns := []factory.ExportColumn{
|
||||||
|
{Header: "ID", Field: "ID", Width: 10},
|
||||||
|
{Header: "姓名", Field: "Name", Width: 20},
|
||||||
|
{
|
||||||
|
Header: "创建时间",
|
||||||
|
Field: "CreatedAt",
|
||||||
|
Width: 20,
|
||||||
|
Format: excel.AdaptTimeFormatter(tools.FormatDateTime), // 使用适配器直接调用tools函数
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Header: "状态",
|
||||||
|
Field: "Status",
|
||||||
|
Width: 10,
|
||||||
|
Format: func(value interface{}) string {
|
||||||
|
// 自定义格式化函数
|
||||||
|
if status, ok := value.(int); ok {
|
||||||
|
if status == 1 {
|
||||||
|
return "启用"
|
||||||
|
}
|
||||||
|
return "禁用"
|
||||||
|
}
|
||||||
|
return ""
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
err := fac.ExportToExcelFile("users.xlsx", "用户列表", columns, users)
|
||||||
|
```
|
||||||
|
|
||||||
|
### 5. 使用ExportData接口(高级功能)
|
||||||
|
|
||||||
|
```go
|
||||||
|
// 实现ExportData接口
|
||||||
|
type UserExportData struct {
|
||||||
|
users []User
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetExportColumns 获取导出列定义
|
||||||
|
func (d *UserExportData) GetExportColumns() []excel.ExportColumn {
|
||||||
|
return []excel.ExportColumn{
|
||||||
|
{Header: "ID", Field: "ID", Width: 10},
|
||||||
|
{Header: "姓名", Field: "Name", Width: 20},
|
||||||
|
{Header: "邮箱", Field: "Email", Width: 30},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetExportRows 获取导出数据行
|
||||||
|
func (d *UserExportData) GetExportRows() [][]interface{} {
|
||||||
|
rows := make([][]interface{}, 0, len(d.users))
|
||||||
|
for _, user := range d.users {
|
||||||
|
row := []interface{}{
|
||||||
|
user.ID,
|
||||||
|
user.Name,
|
||||||
|
user.Email,
|
||||||
|
}
|
||||||
|
rows = append(rows, row)
|
||||||
|
}
|
||||||
|
return rows
|
||||||
|
}
|
||||||
|
|
||||||
|
// 使用
|
||||||
|
exportData := &UserExportData{users: users}
|
||||||
|
columns := exportData.GetExportColumns()
|
||||||
|
err := fac.ExportToExcelFile("users.xlsx", "用户列表", columns, exportData)
|
||||||
|
```
|
||||||
|
|
||||||
|
### 6. 获取Excel对象(高级功能)
|
||||||
|
|
||||||
|
```go
|
||||||
|
// 获取Excel导出器对象(仅在需要高级功能时使用)
|
||||||
|
excel, err := fac.GetExcel()
|
||||||
|
if err != nil {
|
||||||
|
log.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// 获取excelize.File对象,用于高级操作
|
||||||
|
file := excel.GetFile()
|
||||||
|
|
||||||
|
// 创建多个工作表
|
||||||
|
file.NewSheet("Sheet2")
|
||||||
|
file.SetCellValue("Sheet2", "A1", "数据")
|
||||||
|
|
||||||
|
// 自定义样式
|
||||||
|
style, _ := file.NewStyle(&excelize.Style{
|
||||||
|
Font: &excelize.Font{
|
||||||
|
Bold: true,
|
||||||
|
Size: 14,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
file.SetCellStyle("Sheet2", "A1", "A1", style)
|
||||||
|
```
|
||||||
|
|
||||||
|
## API 参考
|
||||||
|
|
||||||
|
### 工厂方法
|
||||||
|
|
||||||
|
#### ExportToExcel(w io.Writer, sheetName string, columns []ExportColumn, data interface{}) error
|
||||||
|
|
||||||
|
导出数据到Writer。
|
||||||
|
|
||||||
|
**参数:**
|
||||||
|
- `w`: Writer对象(如http.ResponseWriter)
|
||||||
|
- `sheetName`: 工作表名称(可选,默认为"Sheet1")
|
||||||
|
- `columns`: 列定义
|
||||||
|
- `data`: 数据列表(可以是结构体切片或实现了ExportData接口的对象)
|
||||||
|
|
||||||
|
**返回:** 错误信息
|
||||||
|
|
||||||
|
**数据为空处理:**
|
||||||
|
- 支持 `nil`、空切片、指针类型等空数据情况
|
||||||
|
- 即使数据为空,表头也会正常生成
|
||||||
|
|
||||||
|
**工作表处理逻辑:**
|
||||||
|
- 如果 `sheetName` 为空,默认使用 "Sheet1"
|
||||||
|
- 如果指定的工作表不存在,会自动创建
|
||||||
|
- 使用自定义名称时会自动删除默认的"Sheet1",避免产生空sheet
|
||||||
|
|
||||||
|
**示例:**
|
||||||
|
```go
|
||||||
|
fac.ExportToExcel(w, "用户列表", columns, users)
|
||||||
|
fac.ExportToExcel(w, "空数据", columns, []User{}) // 空数据也会生成表头
|
||||||
|
```
|
||||||
|
|
||||||
|
#### ExportToExcelFile(filePath string, sheetName string, columns []ExportColumn, data interface{}) error
|
||||||
|
|
||||||
|
导出数据到文件。
|
||||||
|
|
||||||
|
**参数:**
|
||||||
|
- `filePath`: 文件路径
|
||||||
|
- `sheetName`: 工作表名称(可选,默认为"Sheet1")
|
||||||
|
- `columns`: 列定义
|
||||||
|
- `data`: 数据列表(可以是结构体切片或实现了ExportData接口的对象)
|
||||||
|
|
||||||
|
**返回:** 错误信息
|
||||||
|
|
||||||
|
**实现说明:**
|
||||||
|
- 此方法内部创建文件并调用 `ExportToWriter`
|
||||||
|
- 文件相关的封装由工厂方法处理
|
||||||
|
|
||||||
|
**工作表处理逻辑:**
|
||||||
|
- 如果 `sheetName` 为空,默认使用 "Sheet1"
|
||||||
|
- 如果指定的工作表不存在,会自动创建
|
||||||
|
- 使用自定义名称时会自动删除默认的"Sheet1",避免产生空sheet
|
||||||
|
|
||||||
|
**示例:**
|
||||||
|
```go
|
||||||
|
fac.ExportToExcelFile("users.xlsx", "用户列表", columns, users)
|
||||||
|
fac.ExportToExcelFile("empty.xlsx", "空数据", columns, []User{}) // 空数据也会生成表头
|
||||||
|
```
|
||||||
|
|
||||||
|
### 高级方法
|
||||||
|
|
||||||
|
#### GetExcel() (*excel.Excel, error)
|
||||||
|
|
||||||
|
获取Excel导出器对象。
|
||||||
|
|
||||||
|
**返回:** Excel导出器对象和错误信息
|
||||||
|
|
||||||
|
**说明:** 仅在需要使用高级功能时使用,推荐使用黑盒方法
|
||||||
|
|
||||||
|
### 结构体类型
|
||||||
|
|
||||||
|
#### ExportColumn
|
||||||
|
|
||||||
|
导出列定义。
|
||||||
|
|
||||||
|
```go
|
||||||
|
type ExportColumn struct {
|
||||||
|
Header string // 表头名称
|
||||||
|
Field string // 数据字段名(支持嵌套字段,如 "User.Name")
|
||||||
|
Width float64 // 列宽(可选,0表示自动)
|
||||||
|
Format func(interface{}) string // 格式化函数(可选)
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**字段说明:**
|
||||||
|
- `Header`: 表头显示的名称
|
||||||
|
- `Field`: 数据字段名,支持嵌套字段(如 "User.Name")
|
||||||
|
- `Width`: 列宽,0表示自动调整
|
||||||
|
- `Format`: 格式化函数,用于自定义字段值的显示格式
|
||||||
|
|
||||||
|
### 格式化函数适配器
|
||||||
|
|
||||||
|
#### excel.AdaptTimeFormatter(fn func(time.Time, ...string) string) func(interface{}) string
|
||||||
|
|
||||||
|
适配器函数:将tools包的格式化函数转换为Excel Format字段需要的函数类型。
|
||||||
|
|
||||||
|
**参数:**
|
||||||
|
- `fn`: tools包的格式化函数(如 `tools.FormatDate`、`tools.FormatDateTime` 等)
|
||||||
|
|
||||||
|
**返回:** Excel Format字段需要的格式化函数
|
||||||
|
|
||||||
|
**说明:**
|
||||||
|
- 允许直接使用tools包的任何格式化函数
|
||||||
|
|
||||||
|
**示例:**
|
||||||
|
```go
|
||||||
|
import (
|
||||||
|
"git.toowon.com/jimmy/go-common/excel"
|
||||||
|
"git.toowon.com/jimmy/go-common/tools"
|
||||||
|
)
|
||||||
|
|
||||||
|
// 使用tools.FormatDate
|
||||||
|
Format: excel.AdaptTimeFormatter(tools.FormatDate)
|
||||||
|
|
||||||
|
// 使用tools.FormatDateTime
|
||||||
|
Format: excel.AdaptTimeFormatter(tools.FormatDateTime)
|
||||||
|
|
||||||
|
// 使用tools.FormatTime
|
||||||
|
Format: excel.AdaptTimeFormatter(tools.FormatTime)
|
||||||
|
|
||||||
|
// 使用自定义格式化函数
|
||||||
|
Format: excel.AdaptTimeFormatter(func(t time.Time) string {
|
||||||
|
return tools.Format(t, "2006-01-02 15:04:05", "Asia/Shanghai")
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
### ExportData接口
|
||||||
|
|
||||||
|
实现此接口的结构体可以直接导出。
|
||||||
|
|
||||||
|
```go
|
||||||
|
type ExportData interface {
|
||||||
|
// GetExportColumns 获取导出列定义
|
||||||
|
GetExportColumns() []ExportColumn
|
||||||
|
// GetExportRows 获取导出数据行
|
||||||
|
GetExportRows() [][]interface{}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## 完整示例
|
||||||
|
|
||||||
|
```go
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"git.toowon.com/jimmy/go-common/excel"
|
||||||
|
"git.toowon.com/jimmy/go-common/factory"
|
||||||
|
)
|
||||||
|
|
||||||
|
type User struct {
|
||||||
|
ID int `json:"id"`
|
||||||
|
Name string `json:"name"`
|
||||||
|
Email string `json:"email"`
|
||||||
|
CreatedAt time.Time `json:"created_at"`
|
||||||
|
Status int `json:"status"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func exportUsersHandler(w http.ResponseWriter, r *http.Request) {
|
||||||
|
fac, _ := factory.NewFactoryFromFile("./config.json")
|
||||||
|
|
||||||
|
// 从数据库或其他数据源获取数据
|
||||||
|
users := []User{
|
||||||
|
{ID: 1, Name: "Alice", Email: "alice@example.com", CreatedAt: time.Now(), Status: 1},
|
||||||
|
{ID: 2, Name: "Bob", Email: "bob@example.com", CreatedAt: time.Now(), Status: 1},
|
||||||
|
}
|
||||||
|
|
||||||
|
// 定义导出列
|
||||||
|
columns := []factory.ExportColumn{
|
||||||
|
{Header: "ID", Field: "ID", Width: 10},
|
||||||
|
{Header: "姓名", Field: "Name", Width: 20},
|
||||||
|
{Header: "邮箱", Field: "Email", Width: 30},
|
||||||
|
{
|
||||||
|
Header: "创建时间",
|
||||||
|
Field: "CreatedAt",
|
||||||
|
Width: 20,
|
||||||
|
Format: excel.AdaptTimeFormatter(tools.FormatDateTime),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Header: "状态",
|
||||||
|
Field: "Status",
|
||||||
|
Width: 10,
|
||||||
|
Format: func(value interface{}) string {
|
||||||
|
if status, ok := value.(int); ok {
|
||||||
|
if status == 1 {
|
||||||
|
return "启用"
|
||||||
|
}
|
||||||
|
return "禁用"
|
||||||
|
}
|
||||||
|
return ""
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
// 设置HTTP响应头
|
||||||
|
w.Header().Set("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
|
||||||
|
w.Header().Set("Content-Disposition", "attachment; filename=users.xlsx")
|
||||||
|
|
||||||
|
// 导出到响应
|
||||||
|
err := fac.ExportToExcel(w, "用户列表", columns, users)
|
||||||
|
if err != nil {
|
||||||
|
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
http.HandleFunc("/export/users", exportUsersHandler)
|
||||||
|
http.ListenAndServe(":8080", nil)
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## 设计优势
|
||||||
|
|
||||||
|
1. **降低复杂度**:调用方无需关心Excel文件对象的创建和管理
|
||||||
|
2. **延迟初始化**:Excel导出器在首次使用时才创建
|
||||||
|
3. **统一接口**:所有操作通过工厂方法调用
|
||||||
|
4. **灵活扩展**:支持结构体切片、自定义格式化、ExportData接口等多种方式
|
||||||
|
5. **自动优化**:自动调整列宽、应用表头样式等
|
||||||
|
|
||||||
|
## 注意事项
|
||||||
|
|
||||||
|
1. **配置**:Excel导出不需要配置,可以传nil创建工厂
|
||||||
|
2. **错误处理**:所有方法都可能返回错误,需要正确处理
|
||||||
|
3. **延迟初始化**:Excel导出器在首次使用时才创建,首次调用可能稍慢
|
||||||
|
4. **字段名匹配**:Field字段名必须与结构体字段名匹配(区分大小写)
|
||||||
|
5. **嵌套字段**:支持嵌套字段访问(如 "User.Name"),但需要确保字段路径正确
|
||||||
|
6. **格式化函数**:格式化函数返回的字符串会直接写入Excel单元格
|
||||||
|
7. **列宽设置**:Width为0时会自动调整列宽,但可能影响性能(大数据量时建议设置固定宽度)
|
||||||
|
8. **工作表处理**:工具会自动处理工作表的创建和删除,确保不会产生空sheet
|
||||||
|
9. **空数据处理**:即使数据为 `nil` 或空切片,表头也会正常生成
|
||||||
|
10. **方法设计**:
|
||||||
|
- `excel` 包只暴露 `ExportToWriter` 一个核心方法
|
||||||
|
- 文件相关的封装由工厂方法 `ExportToExcelFile` 处理
|
||||||
|
|
||||||
|
## 最佳实践
|
||||||
|
|
||||||
|
1. **使用工厂方法**:推荐使用 `ExportToExcel()` 和 `ExportToExcelFile()`
|
||||||
|
2. **设置列宽**:对于大数据量,建议设置固定列宽以提高性能
|
||||||
|
3. **使用格式化函数**:对于日期时间、状态等字段,使用格式化函数提高可读性
|
||||||
|
4. **错误处理**:始终检查导出方法的返回值
|
||||||
|
5. **HTTP响应**:导出到HTTP响应时,记得设置正确的Content-Type和Content-Disposition头
|
||||||
|
6. **工作表命名**:推荐使用有意义的工作表名称,工具会自动处理工作表的创建和删除
|
||||||
|
7. **空数据场景**:即使查询结果为空,也可以导出包含表头的Excel文件
|
||||||
|
|
||||||
|
## 示例
|
||||||
|
|
||||||
|
完整示例请参考 `examples/excel_example.go`
|
||||||
|
|
||||||
776
docs/factory.md
776
docs/factory.md
@@ -12,6 +12,40 @@
|
|||||||
- **统一接口**:所有操作通过工厂方法调用
|
- **统一接口**:所有操作通过工厂方法调用
|
||||||
- **向后兼容**:保留 `GetXXX()` 方法,需要时可获取对象
|
- **向后兼容**:保留 `GetXXX()` 方法,需要时可获取对象
|
||||||
|
|
||||||
|
## 方法分类总览
|
||||||
|
|
||||||
|
### 🌟 推荐使用:黑盒方法(一行代码搞定)
|
||||||
|
|
||||||
|
外部项目直接调用,无需获取内部对象:
|
||||||
|
|
||||||
|
| 功能 | 方法 | 示例 |
|
||||||
|
|------|------|------|
|
||||||
|
| **中间件** | `GetMiddlewareChain()` | `chain := fac.GetMiddlewareChain()` |
|
||||||
|
| **日志** | `LogInfo()`, `LogError()` 等 | `fac.LogInfo("用户登录")` |
|
||||||
|
| **Redis** | `RedisSet()`, `RedisGet()` 等 | `fac.RedisSet(ctx, "key", "val", time.Hour)` |
|
||||||
|
| **邮件** | `SendEmail()` | `fac.SendEmail(to, subject, body)` |
|
||||||
|
| **短信** | `SendSMS()` | `fac.SendSMS(phones, params)` |
|
||||||
|
| **存储** | `UploadFile()`, `GetFileURL()` | `fac.UploadFile(ctx, key, file)` |
|
||||||
|
| **Excel导出** | `ExportToExcel()`, `ExportToExcelFile()` | `fac.ExportToExcelFile("users.xlsx", "用户列表", columns, users)` |
|
||||||
|
| **日期时间** | `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方法(仅在必要时使用)
|
||||||
|
|
||||||
|
返回客户端对象,用于复杂操作:
|
||||||
|
|
||||||
|
| 方法 | 返回类型 | 使用场景 |
|
||||||
|
|------|----------|----------|
|
||||||
|
| `GetDatabase()` | `*gorm.DB` | 数据库复杂查询、事务、关联查询等 |
|
||||||
|
| `GetRedisClient()` | `*redis.Client` | Hash、List、Set、ZSet、Pub/Sub等高级操作 |
|
||||||
|
| `GetExcel()` | `*excel.Excel` | 多工作表、自定义样式、图表等高级操作 |
|
||||||
|
| `GetLogger()` | `*logger.Logger` | Close()、设置全局logger等 |
|
||||||
|
|
||||||
## 使用方法
|
## 使用方法
|
||||||
|
|
||||||
### 1. 创建工厂(推荐)
|
### 1. 创建工厂(推荐)
|
||||||
@@ -113,7 +147,54 @@ url, _ := fac.GetFileURL("images/test.jpg", 0)
|
|||||||
url, _ := fac.GetFileURL("images/test.jpg", 3600)
|
url, _ := fac.GetFileURL("images/test.jpg", 3600)
|
||||||
```
|
```
|
||||||
|
|
||||||
### 6. Redis操作(黑盒模式,推荐)
|
### 6. Excel导出(黑盒模式,推荐)
|
||||||
|
|
||||||
|
```go
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
"time"
|
||||||
|
"git.toowon.com/jimmy/go-common/excel"
|
||||||
|
)
|
||||||
|
|
||||||
|
// 定义结构体
|
||||||
|
type User struct {
|
||||||
|
ID int `json:"id"`
|
||||||
|
Name string `json:"name"`
|
||||||
|
Email string `json:"email"`
|
||||||
|
CreatedAt time.Time `json:"created_at"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// 准备数据
|
||||||
|
users := []User{
|
||||||
|
{ID: 1, Name: "Alice", Email: "alice@example.com", CreatedAt: time.Now()},
|
||||||
|
{ID: 2, Name: "Bob", Email: "bob@example.com", CreatedAt: time.Now()},
|
||||||
|
}
|
||||||
|
|
||||||
|
// 定义导出列
|
||||||
|
columns := []factory.ExportColumn{
|
||||||
|
{Header: "ID", Field: "ID", Width: 10},
|
||||||
|
{Header: "姓名", Field: "Name", Width: 20},
|
||||||
|
{Header: "邮箱", Field: "Email", Width: 30},
|
||||||
|
{
|
||||||
|
Header: "创建时间",
|
||||||
|
Field: "CreatedAt",
|
||||||
|
Width: 20,
|
||||||
|
Format: excel.AdaptTimeFormatter(tools.FormatDateTime),
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
// 导出到文件
|
||||||
|
err := fac.ExportToExcelFile("users.xlsx", "用户列表", columns, users)
|
||||||
|
|
||||||
|
// 导出到HTTP响应
|
||||||
|
func exportUsersHandler(w http.ResponseWriter, r *http.Request) {
|
||||||
|
w.Header().Set("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
|
||||||
|
w.Header().Set("Content-Disposition", "attachment; filename=users.xlsx")
|
||||||
|
fac.ExportToExcel(w, "用户列表", columns, users)
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 7. Redis操作(黑盒模式,推荐)
|
||||||
|
|
||||||
```go
|
```go
|
||||||
import "context"
|
import "context"
|
||||||
@@ -136,7 +217,7 @@ err := fac.RedisDelete(ctx, "user:123", "user:456")
|
|||||||
exists, err := fac.RedisExists(ctx, "user:123")
|
exists, err := fac.RedisExists(ctx, "user:123")
|
||||||
```
|
```
|
||||||
|
|
||||||
### 7. 数据库操作(黑盒模式)
|
### 8. 数据库操作(黑盒模式)
|
||||||
|
|
||||||
```go
|
```go
|
||||||
// 获取数据库对象(已初始化,黑盒模式)
|
// 获取数据库对象(已初始化,黑盒模式)
|
||||||
@@ -151,7 +232,124 @@ db.Find(&users)
|
|||||||
db.Create(&user)
|
db.Create(&user)
|
||||||
```
|
```
|
||||||
|
|
||||||
### 8. Redis操作(获取客户端对象)
|
### 9. 日期时间操作(黑盒模式)
|
||||||
|
|
||||||
|
```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")
|
||||||
|
```
|
||||||
|
|
||||||
|
### 10. 时间操作(黑盒模式)
|
||||||
|
|
||||||
|
```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)
|
||||||
|
```
|
||||||
|
|
||||||
|
### 11. 金额计算(黑盒模式)
|
||||||
|
|
||||||
|
```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 (
|
||||||
@@ -376,6 +574,54 @@ func main() {
|
|||||||
|
|
||||||
**返回:** 文件访问URL和错误信息
|
**返回:** 文件访问URL和错误信息
|
||||||
|
|
||||||
|
### Excel导出方法(黑盒模式)
|
||||||
|
|
||||||
|
#### ExportToExcel(w io.Writer, sheetName string, columns []ExportColumn, data interface{}) error
|
||||||
|
|
||||||
|
导出数据到Writer。
|
||||||
|
|
||||||
|
**参数:**
|
||||||
|
- `w`: Writer对象(如http.ResponseWriter)
|
||||||
|
- `sheetName`: 工作表名称(可选,默认为"Sheet1")
|
||||||
|
- `columns`: 列定义
|
||||||
|
- `data`: 数据列表(可以是结构体切片或实现了ExportData接口的对象)
|
||||||
|
|
||||||
|
**返回:** 错误信息
|
||||||
|
|
||||||
|
**示例:**
|
||||||
|
```go
|
||||||
|
fac.ExportToExcel(w, "用户列表", columns, users)
|
||||||
|
```
|
||||||
|
|
||||||
|
#### ExportToExcelFile(filePath string, sheetName string, columns []ExportColumn, data interface{}) error
|
||||||
|
|
||||||
|
导出数据到文件。
|
||||||
|
|
||||||
|
**参数:**
|
||||||
|
- `filePath`: 文件路径
|
||||||
|
- `sheetName`: 工作表名称(可选,默认为"Sheet1")
|
||||||
|
- `columns`: 列定义
|
||||||
|
- `data`: 数据列表
|
||||||
|
|
||||||
|
**返回:** 错误信息
|
||||||
|
|
||||||
|
**示例:**
|
||||||
|
```go
|
||||||
|
fac.ExportToExcelFile("users.xlsx", "用户列表", columns, users)
|
||||||
|
```
|
||||||
|
|
||||||
|
#### GetExcel() (*excel.Excel, error)
|
||||||
|
|
||||||
|
获取Excel导出器对象(高级功能时使用)。
|
||||||
|
|
||||||
|
**返回:** Excel导出器对象和错误信息
|
||||||
|
|
||||||
|
**说明:**
|
||||||
|
- 仅在需要使用高级功能时使用
|
||||||
|
- 推荐使用黑盒方法:`ExportToExcel()`、`ExportToExcelFile()`
|
||||||
|
|
||||||
|
**详细说明请参考:[Excel导出工具文档](./excel.md)**
|
||||||
|
|
||||||
### Redis方法(黑盒模式)
|
### Redis方法(黑盒模式)
|
||||||
|
|
||||||
#### RedisGet(ctx context.Context, key string) (string, error)
|
#### RedisGet(ctx context.Context, key string) (string, error)
|
||||||
@@ -456,6 +702,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` 中读取
|
||||||
|
- 如果没有设置环境变量,则使用默认版本号
|
||||||
|
|
||||||
## 设计优势
|
## 设计优势
|
||||||
|
|
||||||
### 优势总结
|
### 优势总结
|
||||||
|
|||||||
659
docs/http.md
659
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
|
||||||
|
var req struct {
|
||||||
|
Name string `json:"name"`
|
||||||
|
}
|
||||||
|
if err := commonhttp.ParseJSON(r, &req); err != nil {
|
||||||
|
commonhttp.WriteJSON(w, http.StatusBadRequest, 400, "请求参数解析失败", nil)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
// 方式2:手动创建Handler(需要更多控制时)
|
// 返回成功响应
|
||||||
http.HandleFunc("/user", func(w http.ResponseWriter, r *http.Request) {
|
commonhttp.Success(w, data, "创建成功")
|
||||||
h := commonhttp.NewHandler(w, r)
|
}
|
||||||
GetUser(h)
|
|
||||||
})
|
|
||||||
```
|
```
|
||||||
|
|
||||||
### 2. 成功响应
|
### 成功响应
|
||||||
|
|
||||||
```go
|
```go
|
||||||
func handler(h *commonhttp.Handler) {
|
// 使用Factory(推荐)
|
||||||
// 简单成功响应(data为nil)
|
fac.Success(w, data) // 只有数据,使用默认消息 "success"
|
||||||
h.Success(nil)
|
fac.Success(w, data, "操作成功") // 数据+消息
|
||||||
|
|
||||||
// 带数据的成功响应
|
// 或直接使用公共方法
|
||||||
data := map[string]interface{}{
|
commonhttp.Success(w, data) // 只有数据
|
||||||
"id": 1,
|
commonhttp.Success(w, data, "操作成功") // 数据+消息
|
||||||
"name": "test",
|
|
||||||
}
|
|
||||||
h.Success(data)
|
|
||||||
|
|
||||||
// 带消息的成功响应
|
|
||||||
h.SuccessWithMessage("操作成功", data)
|
|
||||||
}
|
|
||||||
```
|
```
|
||||||
|
|
||||||
### 3. 错误响应
|
### 错误响应
|
||||||
|
|
||||||
```go
|
```go
|
||||||
func handler(h *commonhttp.Handler) {
|
// 使用Factory(推荐)
|
||||||
// 业务错误(HTTP 200,业务code非0)
|
fac.Error(w, 1001, "用户不存在") // 业务错误(HTTP 200,业务code非0)
|
||||||
h.Error(1001, "用户不存在")
|
fac.SystemError(w, "服务器内部错误") // 系统错误(HTTP 500)
|
||||||
|
|
||||||
// 系统错误(HTTP 500)
|
// 或直接使用公共方法
|
||||||
h.SystemError("服务器内部错误")
|
commonhttp.Error(w, 1001, "用户不存在")
|
||||||
|
commonhttp.SystemError(w, "服务器内部错误")
|
||||||
// 其他HTTP错误状态码,使用WriteJSON直接指定
|
commonhttp.WriteJSON(w, http.StatusBadRequest, 400, "请求参数错误", nil) // 自定义HTTP状态码(仅公共方法)
|
||||||
// 请求错误(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.SuccessPage(w, list, total, page, pageSize)
|
||||||
pagination := h.ParsePaginationRequest()
|
fac.SuccessPage(w, list, total, page, pageSize, "查询成功")
|
||||||
page := pagination.GetPage()
|
|
||||||
pageSize := pagination.GetSize()
|
|
||||||
|
|
||||||
// 查询数据(示例)
|
// 或直接使用公共方法
|
||||||
list, total := getDataList(page, pageSize)
|
commonhttp.SuccessPage(w, list, total, page, pageSize)
|
||||||
|
commonhttp.SuccessPage(w, list, total, page, pageSize, "查询成功")
|
||||||
// 返回分页响应(使用默认消息)
|
|
||||||
h.SuccessPage(list, total, page, pageSize)
|
|
||||||
|
|
||||||
// 返回分页响应(自定义消息)
|
|
||||||
h.SuccessPage(list, total, page, pageSize, "查询成功")
|
|
||||||
}
|
|
||||||
```
|
```
|
||||||
|
|
||||||
### 5. 解析请求
|
### 解析请求
|
||||||
|
|
||||||
#### 解析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")
|
|
||||||
|
|
||||||
// 获取整数参数
|
// 字符串直接获取
|
||||||
id := h.GetQueryInt("id", 0)
|
name := r.URL.Query().Get("name")
|
||||||
age := h.GetQueryInt("age", 18)
|
|
||||||
|
|
||||||
// 获取int64参数
|
// 使用类型转换方法
|
||||||
userId := h.GetQueryInt64("userId", 0)
|
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)
|
||||||
isActive := h.GetQueryBool("isActive", false)
|
price := tools.ConvertFloat64(r.URL.Query().Get("price"), 0.0)
|
||||||
|
|
||||||
// 获取浮点数参数
|
|
||||||
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", "")
|
|
||||||
|
|
||||||
// 获取表单整数
|
// 字符串直接获取
|
||||||
age := h.GetFormInt("age", 0)
|
name := r.FormValue("name")
|
||||||
|
|
||||||
// 获取表单int64
|
// 使用类型转换方法
|
||||||
userId := h.GetFormInt64("userId", 0)
|
age := tools.ConvertInt(r.FormValue("age"), 0)
|
||||||
|
userId := tools.ConvertInt64(r.FormValue("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,7 +296,6 @@ 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"`
|
||||||
@@ -216,63 +304,49 @@ func handler(h *commonhttp.Handler) {
|
|||||||
|
|
||||||
// 从JSON请求体解析(分页字段会自动解析)
|
// 从JSON请求体解析(分页字段会自动解析)
|
||||||
var req ListUserRequest
|
var req ListUserRequest
|
||||||
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
|
||||||
}
|
}
|
||||||
|
|
||||||
// 使用分页方法
|
// 使用分页方法
|
||||||
page := req.GetPage() // 获取页码(默认1)
|
page := req.GetPage() // 获取页码(默认1)
|
||||||
size := req.GetSize() // 获取每页数量(默认20,最大100,优先使用page_size)
|
pageSize := req.GetPageSize() // 获取每页数量(默认20,最大100)
|
||||||
offset := req.GetOffset() // 计算偏移量
|
offset := req.GetOffset() // 计算偏移量
|
||||||
}
|
```
|
||||||
|
|
||||||
// 或者从查询参数/form解析分页
|
**方式2:从查询参数/form解析分页**
|
||||||
func handler(h *commonhttp.Handler) {
|
|
||||||
pagination := h.ParsePaginationRequest()
|
```go
|
||||||
|
// 使用公共方法
|
||||||
|
pagination := commonhttp.ParsePaginationRequest(r)
|
||||||
page := pagination.GetPage()
|
page := pagination.GetPage()
|
||||||
size := pagination.GetSize()
|
pageSize := pagination.GetPageSize()
|
||||||
offset := pagination.GetOffset()
|
offset := pagination.GetOffset()
|
||||||
}
|
|
||||||
```
|
```
|
||||||
|
|
||||||
#### 获取时区
|
#### 获取时区
|
||||||
|
|
||||||
```go
|
```go
|
||||||
func handler(h *commonhttp.Handler) {
|
// 使用公共方法
|
||||||
// 从请求的context中获取时区
|
|
||||||
// 如果使用了middleware.Timezone中间件,可以从context中获取时区信息
|
// 如果使用了middleware.Timezone中间件,可以从context中获取时区信息
|
||||||
// 如果未设置,返回默认时区 AsiaShanghai
|
// 如果未设置,返回默认时区 AsiaShanghai
|
||||||
timezone := h.GetTimezone()
|
timezone := commonhttp.GetTimezone(r)
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
### 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)
|
||||||
@@ -2,12 +2,15 @@
|
|||||||
|
|
||||||
## 概述
|
## 概述
|
||||||
|
|
||||||
中间件工具提供了常用的HTTP中间件功能,包括CORS处理和时区管理。
|
中间件工具提供了常用的HTTP中间件功能,包括CORS处理、时区管理、请求日志、Panic恢复和限流等。
|
||||||
|
|
||||||
## 功能特性
|
## 功能特性
|
||||||
|
|
||||||
- **CORS中间件**:支持跨域资源共享配置
|
- **CORS中间件**:支持跨域资源共享配置
|
||||||
- **时区中间件**:从请求头读取时区信息,支持默认时区设置
|
- **时区中间件**:从请求头读取时区信息,支持默认时区设置
|
||||||
|
- **日志中间件**:自动记录每个HTTP请求的详细信息
|
||||||
|
- **Recovery中间件**:捕获panic并恢复,防止服务崩溃
|
||||||
|
- **限流中间件**:基于令牌桶算法的请求限流
|
||||||
- **中间件链**:提供便捷的中间件链式调用
|
- **中间件链**:提供便捷的中间件链式调用
|
||||||
|
|
||||||
## CORS中间件
|
## CORS中间件
|
||||||
@@ -133,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) {
|
||||||
@@ -143,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),
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -165,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) {
|
||||||
@@ -174,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)
|
||||||
}
|
}
|
||||||
@@ -182,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) {
|
||||||
@@ -196,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),
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
@@ -233,6 +268,371 @@ X-Timezone: Asia/Shanghai
|
|||||||
3. 时区信息存储在context中,可以在整个请求生命周期中使用
|
3. 时区信息存储在context中,可以在整个请求生命周期中使用
|
||||||
4. 建议在CORS配置中包含 `X-Timezone` 请求头
|
4. 建议在CORS配置中包含 `X-Timezone` 请求头
|
||||||
|
|
||||||
|
## 日志中间件
|
||||||
|
|
||||||
|
### 功能说明
|
||||||
|
|
||||||
|
日志中间件用于自动记录每个HTTP请求的详细信息,帮助监控和调试应用。
|
||||||
|
|
||||||
|
记录内容包括:
|
||||||
|
- 请求方法、路径、查询参数
|
||||||
|
- 响应状态码、响应大小
|
||||||
|
- 请求处理时间(毫秒)
|
||||||
|
- 客户端IP地址(支持X-Forwarded-For)
|
||||||
|
- User-Agent、Referer等信息
|
||||||
|
|
||||||
|
### 使用方法
|
||||||
|
|
||||||
|
#### 基本使用(使用默认logger)
|
||||||
|
|
||||||
|
```go
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
"git.toowon.com/jimmy/go-common/middleware"
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
chain := middleware.NewChain(
|
||||||
|
middleware.Logging(nil), // 使用默认配置
|
||||||
|
middleware.CORS(),
|
||||||
|
middleware.Timezone,
|
||||||
|
)
|
||||||
|
|
||||||
|
handler := chain.ThenFunc(apiHandler)
|
||||||
|
http.Handle("/api", handler)
|
||||||
|
http.ListenAndServe(":8080", nil)
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
#### 使用自定义logger
|
||||||
|
|
||||||
|
```go
|
||||||
|
import (
|
||||||
|
"git.toowon.com/jimmy/go-common/middleware"
|
||||||
|
"git.toowon.com/jimmy/go-common/logger"
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
// 创建自定义logger(异步模式,输出到文件)
|
||||||
|
loggerConfig := &logger.LoggerConfig{
|
||||||
|
Level: "info",
|
||||||
|
Output: "file",
|
||||||
|
FilePath: "./logs/app.log",
|
||||||
|
Async: true, // 异步模式,不阻塞请求
|
||||||
|
BufferSize: 1000,
|
||||||
|
}
|
||||||
|
myLogger, _ := logger.NewLogger(loggerConfig)
|
||||||
|
|
||||||
|
// 配置日志中间件
|
||||||
|
loggingConfig := &middleware.LoggingConfig{
|
||||||
|
Logger: myLogger,
|
||||||
|
SkipPaths: []string{"/health", "/metrics"}, // 跳过健康检查接口
|
||||||
|
}
|
||||||
|
|
||||||
|
chain := middleware.NewChain(
|
||||||
|
middleware.Logging(loggingConfig),
|
||||||
|
middleware.CORS(),
|
||||||
|
middleware.Timezone,
|
||||||
|
)
|
||||||
|
|
||||||
|
handler := chain.ThenFunc(apiHandler)
|
||||||
|
http.Handle("/api", handler)
|
||||||
|
http.ListenAndServe(":8080", nil)
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### LoggingConfig 配置说明
|
||||||
|
|
||||||
|
| 字段 | 类型 | 说明 | 默认值 |
|
||||||
|
|------|------|------|--------|
|
||||||
|
| Logger | *logger.Logger | 日志记录器 | 创建默认logger(stdout) |
|
||||||
|
| SkipPaths | []string | 跳过记录的路径列表 | [] |
|
||||||
|
| LogRequestBody | bool | 是否记录请求体(慎用) | false |
|
||||||
|
| LogResponseBody | bool | 是否记录响应体(慎用) | false |
|
||||||
|
|
||||||
|
### 日志输出示例
|
||||||
|
|
||||||
|
```
|
||||||
|
[INFO] HTTP Request method=GET path=/api/users query= status=200 size=1024 duration=45 ip=192.168.1.100 user_agent=Mozilla/5.0 referer=
|
||||||
|
[WARN] HTTP Request method=POST path=/api/users query= status=400 size=128 duration=12 ip=192.168.1.100 user_agent=PostmanRuntime/7.29
|
||||||
|
[ERROR] HTTP Request method=GET path=/api/error query= status=500 size=256 duration=89 ip=192.168.1.100 user_agent=curl/7.64.1 referer=
|
||||||
|
```
|
||||||
|
|
||||||
|
### 注意事项
|
||||||
|
|
||||||
|
1. **异步模式推荐**:生产环境建议使用异步logger,避免日志写入阻塞请求
|
||||||
|
2. **跳过路径**:健康检查、监控接口等高频接口建议跳过日志记录
|
||||||
|
3. **日志级别**:根据状态码自动选择日志级别(5xx=ERROR, 4xx=WARN, 2xx-3xx=INFO)
|
||||||
|
4. **客户端IP**:自动从X-Forwarded-For、X-Real-IP或RemoteAddr获取真实IP
|
||||||
|
|
||||||
|
## Recovery中间件
|
||||||
|
|
||||||
|
### 功能说明
|
||||||
|
|
||||||
|
Recovery中间件用于捕获HTTP处理过程中的panic,防止panic导致整个服务崩溃。
|
||||||
|
|
||||||
|
功能包括:
|
||||||
|
- 捕获panic并恢复服务
|
||||||
|
- 记录panic信息和堆栈跟踪
|
||||||
|
- 返回500错误响应
|
||||||
|
- 支持自定义错误处理
|
||||||
|
|
||||||
|
### 使用方法
|
||||||
|
|
||||||
|
#### 基本使用(使用默认配置)
|
||||||
|
|
||||||
|
```go
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
"git.toowon.com/jimmy/go-common/middleware"
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
chain := middleware.NewChain(
|
||||||
|
middleware.Recovery(nil), // 使用默认配置
|
||||||
|
middleware.Logging(nil),
|
||||||
|
middleware.CORS(),
|
||||||
|
middleware.Timezone,
|
||||||
|
)
|
||||||
|
|
||||||
|
handler := chain.ThenFunc(apiHandler)
|
||||||
|
http.Handle("/api", handler)
|
||||||
|
http.ListenAndServe(":8080", nil)
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
#### 使用自定义logger
|
||||||
|
|
||||||
|
```go
|
||||||
|
import (
|
||||||
|
"git.toowon.com/jimmy/go-common/middleware"
|
||||||
|
"git.toowon.com/jimmy/go-common/logger"
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
myLogger, _ := logger.NewLogger(nil)
|
||||||
|
|
||||||
|
recoveryConfig := &middleware.RecoveryConfig{
|
||||||
|
Logger: myLogger,
|
||||||
|
EnableStackTrace: true, // 启用堆栈跟踪
|
||||||
|
}
|
||||||
|
|
||||||
|
chain := middleware.NewChain(
|
||||||
|
middleware.Recovery(recoveryConfig),
|
||||||
|
middleware.Logging(nil),
|
||||||
|
)
|
||||||
|
|
||||||
|
handler := chain.ThenFunc(apiHandler)
|
||||||
|
http.Handle("/api", handler)
|
||||||
|
http.ListenAndServe(":8080", nil)
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
#### 自定义错误响应
|
||||||
|
|
||||||
|
```go
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
commonhttp "git.toowon.com/jimmy/go-common/http"
|
||||||
|
"git.toowon.com/jimmy/go-common/middleware"
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
recoveryConfig := &middleware.RecoveryConfig{
|
||||||
|
EnableStackTrace: true,
|
||||||
|
CustomHandler: func(w http.ResponseWriter, r *http.Request, err interface{}) {
|
||||||
|
// 使用统一的JSON响应格式
|
||||||
|
h := commonhttp.NewHandler(w, r)
|
||||||
|
h.SystemError("服务器内部错误")
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
chain := middleware.NewChain(
|
||||||
|
middleware.Recovery(recoveryConfig),
|
||||||
|
)
|
||||||
|
|
||||||
|
handler := chain.ThenFunc(apiHandler)
|
||||||
|
http.Handle("/api", handler)
|
||||||
|
http.ListenAndServe(":8080", nil)
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### RecoveryConfig 配置说明
|
||||||
|
|
||||||
|
| 字段 | 类型 | 说明 | 默认值 |
|
||||||
|
|------|------|------|--------|
|
||||||
|
| Logger | *logger.Logger | 日志记录器 | 创建默认logger |
|
||||||
|
| EnableStackTrace | bool | 是否记录堆栈跟踪 | true |
|
||||||
|
| CustomHandler | func(...) | 自定义错误处理函数 | nil(返回500文本) |
|
||||||
|
|
||||||
|
### 注意事项
|
||||||
|
|
||||||
|
1. **放在最外层**:Recovery中间件应该放在中间件链的最前面,以捕获所有panic
|
||||||
|
2. **日志记录**:建议配置logger,确保panic信息被记录下来
|
||||||
|
3. **堆栈跟踪**:生产环境建议启用,方便排查问题
|
||||||
|
4. **自定义响应**:可以自定义错误响应格式,统一错误处理
|
||||||
|
|
||||||
|
## 限流中间件
|
||||||
|
|
||||||
|
### 功能说明
|
||||||
|
|
||||||
|
限流中间件用于限制请求频率,防止API被滥用或遭受攻击。
|
||||||
|
|
||||||
|
特性:
|
||||||
|
- 基于令牌桶算法
|
||||||
|
- 支持按IP、用户ID等维度限流
|
||||||
|
- 自动设置限流响应头
|
||||||
|
- 内存存储,自动清理过期数据
|
||||||
|
|
||||||
|
### 使用方法
|
||||||
|
|
||||||
|
#### 基本使用(默认配置:100请求/分钟)
|
||||||
|
|
||||||
|
```go
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
"git.toowon.com/jimmy/go-common/middleware"
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
chain := middleware.NewChain(
|
||||||
|
middleware.Recovery(nil),
|
||||||
|
middleware.Logging(nil),
|
||||||
|
middleware.RateLimit(nil), // 默认100请求/分钟,按IP限流
|
||||||
|
middleware.CORS(),
|
||||||
|
)
|
||||||
|
|
||||||
|
handler := chain.ThenFunc(apiHandler)
|
||||||
|
http.Handle("/api", handler)
|
||||||
|
http.ListenAndServe(":8080", nil)
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
#### 自定义限流规则
|
||||||
|
|
||||||
|
```go
|
||||||
|
import (
|
||||||
|
"time"
|
||||||
|
"git.toowon.com/jimmy/go-common/middleware"
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
// 创建限流器:10请求/分钟
|
||||||
|
limiter := middleware.NewTokenBucketLimiter(10, time.Minute)
|
||||||
|
|
||||||
|
rateLimitConfig := &middleware.RateLimitConfig{
|
||||||
|
Limiter: limiter,
|
||||||
|
}
|
||||||
|
|
||||||
|
chain := middleware.NewChain(
|
||||||
|
middleware.RateLimit(rateLimitConfig),
|
||||||
|
)
|
||||||
|
|
||||||
|
handler := chain.ThenFunc(apiHandler)
|
||||||
|
http.Handle("/api", handler)
|
||||||
|
http.ListenAndServe(":8080", nil)
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
#### 按用户ID限流
|
||||||
|
|
||||||
|
```go
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
"time"
|
||||||
|
"git.toowon.com/jimmy/go-common/middleware"
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
limiter := middleware.NewTokenBucketLimiter(100, time.Minute)
|
||||||
|
|
||||||
|
rateLimitConfig := &middleware.RateLimitConfig{
|
||||||
|
Limiter: limiter,
|
||||||
|
KeyFunc: func(r *http.Request) string {
|
||||||
|
// 从请求头或JWT token中获取用户ID
|
||||||
|
userID := r.Header.Get("X-User-ID")
|
||||||
|
if userID != "" {
|
||||||
|
return "user:" + userID
|
||||||
|
}
|
||||||
|
// 如果没有用户ID,使用IP
|
||||||
|
return "ip:" + r.RemoteAddr
|
||||||
|
},
|
||||||
|
OnRateLimitExceeded: func(w http.ResponseWriter, r *http.Request, key string) {
|
||||||
|
// 记录限流事件
|
||||||
|
println("Rate limit exceeded for:", key)
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
chain := middleware.NewChain(
|
||||||
|
middleware.RateLimit(rateLimitConfig),
|
||||||
|
)
|
||||||
|
|
||||||
|
handler := chain.ThenFunc(apiHandler)
|
||||||
|
http.Handle("/api", handler)
|
||||||
|
http.ListenAndServe(":8080", nil)
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
#### 便捷函数
|
||||||
|
|
||||||
|
```go
|
||||||
|
// 按IP限流:10请求/分钟
|
||||||
|
chain := middleware.NewChain(
|
||||||
|
middleware.RateLimitByIP(10, time.Minute),
|
||||||
|
)
|
||||||
|
|
||||||
|
// 或使用自定义速率
|
||||||
|
chain := middleware.NewChain(
|
||||||
|
middleware.RateLimitWithRate(50, time.Minute),
|
||||||
|
)
|
||||||
|
```
|
||||||
|
|
||||||
|
### RateLimitConfig 配置说明
|
||||||
|
|
||||||
|
| 字段 | 类型 | 说明 | 默认值 |
|
||||||
|
|------|------|------|--------|
|
||||||
|
| Limiter | RateLimiter | 限流器实例 | 100请求/分钟 |
|
||||||
|
| KeyFunc | func(*http.Request) string | 生成限流键的函数 | 使用客户端IP |
|
||||||
|
| OnRateLimitExceeded | func(...) | 限流触发回调 | nil |
|
||||||
|
|
||||||
|
### 响应头说明
|
||||||
|
|
||||||
|
限流中间件会自动设置以下响应头:
|
||||||
|
|
||||||
|
| 响应头 | 说明 |
|
||||||
|
|--------|------|
|
||||||
|
| X-RateLimit-Limit | 窗口期内允许的请求数 |
|
||||||
|
| X-RateLimit-Remaining | 当前窗口剩余配额 |
|
||||||
|
| X-RateLimit-Reset | 配额重置时间(Unix时间戳) |
|
||||||
|
| Retry-After | 限流时,建议重试的等待时间(秒) |
|
||||||
|
|
||||||
|
### 响应示例
|
||||||
|
|
||||||
|
正常请求:
|
||||||
|
```
|
||||||
|
HTTP/1.1 200 OK
|
||||||
|
X-RateLimit-Limit: 100
|
||||||
|
X-RateLimit-Remaining: 95
|
||||||
|
X-RateLimit-Reset: 1640000000
|
||||||
|
```
|
||||||
|
|
||||||
|
触发限流:
|
||||||
|
```
|
||||||
|
HTTP/1.1 429 Too Many Requests
|
||||||
|
X-RateLimit-Limit: 100
|
||||||
|
X-RateLimit-Remaining: 0
|
||||||
|
X-RateLimit-Reset: 1640000000
|
||||||
|
Retry-After: 45
|
||||||
|
Too Many Requests
|
||||||
|
```
|
||||||
|
|
||||||
|
### 注意事项
|
||||||
|
|
||||||
|
1. **内存存储**:当前实现使用内存存储,适用于单机部署。如需分布式限流,建议使用Redis
|
||||||
|
2. **键设计**:合理设计限流键,可以按IP、用户、API等维度限流
|
||||||
|
3. **清理机制**:自动清理过期的限流数据,避免内存泄漏
|
||||||
|
4. **算法选择**:使用令牌桶算法,支持突发流量
|
||||||
|
|
||||||
## 中间件链
|
## 中间件链
|
||||||
|
|
||||||
### 功能说明
|
### 功能说明
|
||||||
@@ -277,7 +677,107 @@ handler := chain.ThenFunc(handler)
|
|||||||
|
|
||||||
## 完整示例
|
## 完整示例
|
||||||
|
|
||||||
### 示例1:CORS + 时区中间件
|
### 示例1:完整的生产级中间件配置
|
||||||
|
|
||||||
|
```go
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"log"
|
||||||
|
"net/http"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"git.toowon.com/jimmy/go-common/middleware"
|
||||||
|
"git.toowon.com/jimmy/go-common/logger"
|
||||||
|
commonhttp "git.toowon.com/jimmy/go-common/http"
|
||||||
|
"git.toowon.com/jimmy/go-common/tools"
|
||||||
|
)
|
||||||
|
|
||||||
|
func apiHandler(w http.ResponseWriter, r *http.Request) {
|
||||||
|
h := commonhttp.NewHandler(w, r)
|
||||||
|
|
||||||
|
// 从Handler获取时区
|
||||||
|
timezone := h.GetTimezone()
|
||||||
|
now := tools.Now(timezone)
|
||||||
|
|
||||||
|
h.Success(map[string]interface{}{
|
||||||
|
"message": "Hello",
|
||||||
|
"timezone": timezone,
|
||||||
|
"time": tools.FormatDateTime(now),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
// 1. 配置logger(异步模式,输出到文件)
|
||||||
|
loggerConfig := &logger.LoggerConfig{
|
||||||
|
Level: "info",
|
||||||
|
Output: "both", // 同时输出到stdout和文件
|
||||||
|
FilePath: "./logs/app.log",
|
||||||
|
Async: true,
|
||||||
|
BufferSize: 1000,
|
||||||
|
}
|
||||||
|
myLogger, err := logger.NewLogger(loggerConfig)
|
||||||
|
if err != nil {
|
||||||
|
log.Fatal(err)
|
||||||
|
}
|
||||||
|
defer myLogger.Close() // 确保程序退出时关闭logger
|
||||||
|
|
||||||
|
// 2. 配置CORS
|
||||||
|
corsConfig := &middleware.CORSConfig{
|
||||||
|
AllowedOrigins: []string{"*"},
|
||||||
|
AllowedMethods: []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"},
|
||||||
|
AllowedHeaders: []string{"Content-Type", "Authorization", "X-Timezone"},
|
||||||
|
}
|
||||||
|
|
||||||
|
// 3. 配置日志中间件
|
||||||
|
loggingConfig := &middleware.LoggingConfig{
|
||||||
|
Logger: myLogger,
|
||||||
|
SkipPaths: []string{"/health", "/metrics"},
|
||||||
|
}
|
||||||
|
|
||||||
|
// 4. 配置Recovery中间件
|
||||||
|
recoveryConfig := &middleware.RecoveryConfig{
|
||||||
|
Logger: myLogger,
|
||||||
|
EnableStackTrace: true,
|
||||||
|
CustomHandler: func(w http.ResponseWriter, r *http.Request, err interface{}) {
|
||||||
|
h := commonhttp.NewHandler(w, r)
|
||||||
|
h.SystemError("服务器内部错误")
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
// 5. 配置限流中间件(100请求/分钟)
|
||||||
|
rateLimiter := middleware.NewTokenBucketLimiter(100, time.Minute)
|
||||||
|
rateLimitConfig := &middleware.RateLimitConfig{
|
||||||
|
Limiter: rateLimiter,
|
||||||
|
OnRateLimitExceeded: func(w http.ResponseWriter, r *http.Request, key string) {
|
||||||
|
myLogger.Warnf(map[string]interface{}{
|
||||||
|
"key": key,
|
||||||
|
"path": r.URL.Path,
|
||||||
|
}, "Rate limit exceeded")
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
// 6. 创建中间件链(顺序很重要!)
|
||||||
|
chain := middleware.NewChain(
|
||||||
|
middleware.Recovery(recoveryConfig), // 最外层:捕获panic
|
||||||
|
middleware.Logging(loggingConfig), // 日志记录
|
||||||
|
middleware.RateLimit(rateLimitConfig), // 限流
|
||||||
|
middleware.CORS(corsConfig), // CORS处理
|
||||||
|
middleware.Timezone, // 时区处理
|
||||||
|
)
|
||||||
|
|
||||||
|
// 7. 应用中间件
|
||||||
|
http.Handle("/api", chain.ThenFunc(apiHandler))
|
||||||
|
http.HandleFunc("/health", func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
w.Write([]byte("OK"))
|
||||||
|
})
|
||||||
|
|
||||||
|
log.Println("Server started on :8080")
|
||||||
|
log.Fatal(http.ListenAndServe(":8080", nil))
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 示例2:基础的CORS + 时区中间件
|
||||||
|
|
||||||
```go
|
```go
|
||||||
package main
|
package main
|
||||||
@@ -288,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) {
|
||||||
@@ -296,33 +796,23 @@ 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),
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
// 配置CORS
|
// 创建简单的中间件链
|
||||||
corsConfig := &middleware.CORSConfig{
|
|
||||||
AllowedOrigins: []string{"*"},
|
|
||||||
AllowedMethods: []string{"GET", "POST", "OPTIONS"},
|
|
||||||
AllowedHeaders: []string{"Content-Type", "Authorization", "X-Timezone"},
|
|
||||||
}
|
|
||||||
|
|
||||||
// 创建中间件链
|
|
||||||
chain := middleware.NewChain(
|
chain := middleware.NewChain(
|
||||||
middleware.CORS(corsConfig),
|
middleware.CORS(nil), // 使用默认CORS配置
|
||||||
middleware.Timezone,
|
middleware.Timezone, // 使用默认时区
|
||||||
)
|
)
|
||||||
|
|
||||||
// 应用中间件
|
http.Handle("/api", chain.ThenFunc(apiHandler))
|
||||||
handler := chain.ThenFunc(apiHandler)
|
|
||||||
|
|
||||||
http.Handle("/api", handler)
|
|
||||||
|
|
||||||
log.Println("Server started on :8080")
|
log.Println("Server started on :8080")
|
||||||
log.Fatal(http.ListenAndServe(":8080", nil))
|
log.Fatal(http.ListenAndServe(":8080", nil))
|
||||||
@@ -408,6 +898,65 @@ func getPosts(w http.ResponseWriter, r *http.Request) {
|
|||||||
|
|
||||||
从context中获取时区。
|
从context中获取时区。
|
||||||
|
|
||||||
|
### 日志中间件
|
||||||
|
|
||||||
|
#### Logging(config *LoggingConfig) func(http.Handler) http.Handler
|
||||||
|
|
||||||
|
创建日志中间件。
|
||||||
|
|
||||||
|
**参数:**
|
||||||
|
- `config`: 日志配置,nil则使用默认配置
|
||||||
|
|
||||||
|
**返回:** 中间件函数
|
||||||
|
|
||||||
|
### Recovery中间件
|
||||||
|
|
||||||
|
#### Recovery(config *RecoveryConfig) func(http.Handler) http.Handler
|
||||||
|
|
||||||
|
创建Recovery中间件。
|
||||||
|
|
||||||
|
**参数:**
|
||||||
|
- `config`: Recovery配置,nil则使用默认配置
|
||||||
|
|
||||||
|
**返回:** 中间件函数
|
||||||
|
|
||||||
|
#### RecoveryWithLogger(log *logger.Logger) func(http.Handler) http.Handler
|
||||||
|
|
||||||
|
使用指定logger的Recovery中间件(便捷函数)。
|
||||||
|
|
||||||
|
#### RecoveryWithCustomHandler(customHandler func(...)) func(http.Handler) http.Handler
|
||||||
|
|
||||||
|
使用自定义错误处理的Recovery中间件(便捷函数)。
|
||||||
|
|
||||||
|
### 限流中间件
|
||||||
|
|
||||||
|
#### RateLimit(config *RateLimitConfig) func(http.Handler) http.Handler
|
||||||
|
|
||||||
|
创建限流中间件。
|
||||||
|
|
||||||
|
**参数:**
|
||||||
|
- `config`: 限流配置,nil则使用默认配置(100请求/分钟)
|
||||||
|
|
||||||
|
**返回:** 中间件函数
|
||||||
|
|
||||||
|
#### NewTokenBucketLimiter(rate int, windowSize time.Duration) RateLimiter
|
||||||
|
|
||||||
|
创建令牌桶限流器。
|
||||||
|
|
||||||
|
**参数:**
|
||||||
|
- `rate`: 每个窗口期允许的请求数
|
||||||
|
- `windowSize`: 窗口大小
|
||||||
|
|
||||||
|
**返回:** 限流器实例
|
||||||
|
|
||||||
|
#### RateLimitWithRate(rate int, windowSize time.Duration) func(http.Handler) http.Handler
|
||||||
|
|
||||||
|
使用指定速率创建限流中间件(便捷函数)。
|
||||||
|
|
||||||
|
#### RateLimitByIP(rate int, windowSize time.Duration) func(http.Handler) http.Handler
|
||||||
|
|
||||||
|
按IP限流(便捷函数)。
|
||||||
|
|
||||||
### 中间件链
|
### 中间件链
|
||||||
|
|
||||||
#### NewChain(middlewares ...func(http.Handler) http.Handler) *Chain
|
#### NewChain(middlewares ...func(http.Handler) http.Handler) *Chain
|
||||||
@@ -428,19 +977,63 @@ func getPosts(w http.ResponseWriter, r *http.Request) {
|
|||||||
|
|
||||||
## 注意事项
|
## 注意事项
|
||||||
|
|
||||||
1. **CORS配置**:
|
### 1. CORS配置
|
||||||
- 生产环境建议明确指定允许的源,避免使用 "*"
|
- 生产环境建议明确指定允许的源,避免使用 "*"
|
||||||
- 如果使用凭证(cookies),必须明确指定源,不能使用 "*"
|
- 如果使用凭证(cookies),必须明确指定源,不能使用 "*"
|
||||||
|
- CORS中间件应该在Recovery和Logging之后,以便正确处理预检请求
|
||||||
|
|
||||||
2. **时区处理**:
|
### 2. 时区处理
|
||||||
- 时区信息存储在context中,确保中间件在处理器之前执行
|
- 时区信息存储在context中,确保中间件在处理器之前执行
|
||||||
- 时区验证失败时会自动回退到默认时区,不会返回错误
|
- 时区验证失败时会自动回退到默认时区,不会返回错误
|
||||||
|
- 建议在CORS配置中包含 `X-Timezone` 请求头
|
||||||
|
|
||||||
3. **中间件顺序**:
|
### 3. 日志记录
|
||||||
- CORS中间件应该放在最外层,以便处理预检请求
|
- **生产环境推荐异步模式**:避免日志写入阻塞请求,提升性能
|
||||||
- 时区中间件可以放在CORS之后
|
- **跳过高频接口**:健康检查、监控接口等高频接口建议跳过日志
|
||||||
|
- **日志轮转**:使用文件输出时,建议配合日志轮转工具(如logrotate)
|
||||||
|
- **敏感信息**:不要记录请求体和响应体,避免泄露敏感信息
|
||||||
|
|
||||||
4. **性能考虑**:
|
### 4. Panic恢复
|
||||||
- CORS预检请求会被缓存,减少重复请求
|
- **放在最外层**:Recovery中间件应该放在中间件链的最前面
|
||||||
- 时区验证只在请求头存在时进行,性能影响很小
|
- **记录日志**:务必配置logger,确保panic信息被记录
|
||||||
|
- **监控告警**:建议将panic事件接入监控系统,及时发现问题
|
||||||
|
- **堆栈跟踪**:生产环境建议启用,方便排查问题
|
||||||
|
|
||||||
|
### 5. 限流配置
|
||||||
|
- **合理设置阈值**:根据实际业务需求设置限流阈值
|
||||||
|
- **分布式部署**:当前实现使用内存存储,适用于单机。分布式部署建议使用Redis
|
||||||
|
- **键设计**:合理设计限流键,可以按IP、用户、API等维度限流
|
||||||
|
- **响应头**:客户端可以根据X-RateLimit-*响应头实现智能重试
|
||||||
|
|
||||||
|
### 6. 中间件顺序(推荐)
|
||||||
|
建议的中间件顺序(从外到内):
|
||||||
|
1. **Recovery** - 最外层,捕获所有panic
|
||||||
|
2. **Logging** - 记录所有请求(包括限流的请求)
|
||||||
|
3. **RateLimit** - 限流保护
|
||||||
|
4. **CORS** - 处理跨域
|
||||||
|
5. **Timezone** - 时区处理
|
||||||
|
6. **业务中间件** - 认证、授权等
|
||||||
|
|
||||||
|
```go
|
||||||
|
chain := middleware.NewChain(
|
||||||
|
middleware.Recovery(recoveryConfig), // 1. Panic恢复
|
||||||
|
middleware.Logging(loggingConfig), // 2. 日志记录
|
||||||
|
middleware.RateLimit(rateLimitConfig), // 3. 限流
|
||||||
|
middleware.CORS(corsConfig), // 4. CORS
|
||||||
|
middleware.Timezone, // 5. 时区
|
||||||
|
)
|
||||||
|
```
|
||||||
|
|
||||||
|
### 7. 性能考虑
|
||||||
|
- **异步日志**:使用异步logger,避免IO阻塞
|
||||||
|
- **限流算法**:令牌桶算法支持突发流量
|
||||||
|
- **自动清理**:限流数据会自动清理,避免内存泄漏
|
||||||
|
- **跳过路径**:合理使用SkipPaths,减少不必要的处理
|
||||||
|
|
||||||
|
### 8. 生产环境建议
|
||||||
|
- 使用异步logger,配置日志文件和轮转
|
||||||
|
- 启用Recovery中间件,配置告警
|
||||||
|
- 根据业务设置合理的限流阈值
|
||||||
|
- 配置监控指标(请求量、错误率、限流触发次数等)
|
||||||
|
- 定期review日志,优化性能瓶颈
|
||||||
|
|
||||||
|
|||||||
@@ -13,7 +13,101 @@
|
|||||||
- 自动创建迁移记录表
|
- 自动创建迁移记录表
|
||||||
- 事务支持,确保迁移的原子性
|
- 事务支持,确保迁移的原子性
|
||||||
|
|
||||||
## 使用方法
|
## 🚀 最简单的使用方式(黑盒模式,推荐)
|
||||||
|
|
||||||
|
这是最简单的迁移方式,内部自动处理配置加载、数据库连接、迁移执行等所有细节。
|
||||||
|
|
||||||
|
### 方式一:使用独立迁移工具(推荐)
|
||||||
|
|
||||||
|
1. **复制迁移工具模板到你的项目**:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
mkdir -p cmd/migrate
|
||||||
|
cp /path/to/go-common/templates/migrate/main.go cmd/migrate/
|
||||||
|
```
|
||||||
|
|
||||||
|
2. **创建迁移文件**:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
mkdir -p migrations
|
||||||
|
# 或使用其他目录,如 scripts/sql
|
||||||
|
```
|
||||||
|
|
||||||
|
创建 `migrations/01_init_schema.sql`:
|
||||||
|
|
||||||
|
```sql
|
||||||
|
CREATE TABLE users (
|
||||||
|
id BIGINT PRIMARY KEY AUTO_INCREMENT,
|
||||||
|
username VARCHAR(255) NOT NULL,
|
||||||
|
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
||||||
|
);
|
||||||
|
```
|
||||||
|
|
||||||
|
3. **编译和使用**:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 编译
|
||||||
|
go build -o bin/migrate cmd/migrate/main.go
|
||||||
|
|
||||||
|
# 使用(最简单,使用默认配置和默认迁移目录)
|
||||||
|
./bin/migrate up
|
||||||
|
|
||||||
|
# 指定配置文件
|
||||||
|
./bin/migrate up -config config.json
|
||||||
|
|
||||||
|
# 指定配置和迁移目录
|
||||||
|
./bin/migrate up -config config.json -dir scripts/sql
|
||||||
|
|
||||||
|
# 查看状态
|
||||||
|
./bin/migrate status
|
||||||
|
|
||||||
|
# 回滚
|
||||||
|
./bin/migrate down
|
||||||
|
```
|
||||||
|
|
||||||
|
**特点**:
|
||||||
|
- ✅ 零配置:使用默认值即可运行
|
||||||
|
- ✅ 自动查找配置:支持环境变量、默认路径
|
||||||
|
- ✅ 自动处理:配置加载、数据库连接、迁移执行全自动
|
||||||
|
|
||||||
|
### 方式二:在代码中直接调用(简单场景)
|
||||||
|
|
||||||
|
```go
|
||||||
|
import "git.toowon.com/jimmy/go-common/migration"
|
||||||
|
|
||||||
|
// 最简单:使用默认配置和默认迁移目录
|
||||||
|
err := migration.RunMigrationsFromConfigWithCommand("", "", "up")
|
||||||
|
|
||||||
|
// 指定配置文件,使用默认迁移目录
|
||||||
|
err := migration.RunMigrationsFromConfigWithCommand("config.json", "", "up")
|
||||||
|
|
||||||
|
// 指定配置和迁移目录
|
||||||
|
err := migration.RunMigrationsFromConfigWithCommand("config.json", "scripts/sql", "up")
|
||||||
|
|
||||||
|
// 查看状态
|
||||||
|
err := migration.RunMigrationsFromConfigWithCommand("config.json", "migrations", "status")
|
||||||
|
```
|
||||||
|
|
||||||
|
**参数说明**:
|
||||||
|
- `configFile`: 配置文件路径,空字符串时自动查找(config.json, ../config.json)
|
||||||
|
- `migrationsDir`: 迁移文件目录,空字符串时使用默认值 "migrations"
|
||||||
|
- `command`: 命令,支持 "up", "down", "status"
|
||||||
|
|
||||||
|
### 方式三:使用Factory(如果项目已使用Factory)
|
||||||
|
|
||||||
|
```go
|
||||||
|
import "git.toowon.com/jimmy/go-common/factory"
|
||||||
|
|
||||||
|
fac, _ := factory.NewFactoryFromFile("config.json")
|
||||||
|
// 使用默认目录 "migrations"
|
||||||
|
err := fac.RunMigrations()
|
||||||
|
// 或指定目录
|
||||||
|
err := fac.RunMigrations("scripts/sql")
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 详细使用方法(高级功能)
|
||||||
|
|
||||||
### 1. 创建迁移器
|
### 1. 创建迁移器
|
||||||
|
|
||||||
@@ -86,14 +180,16 @@ migrations := []migration.Migration{
|
|||||||
migrator.AddMigrations(migrations...)
|
migrator.AddMigrations(migrations...)
|
||||||
```
|
```
|
||||||
|
|
||||||
#### 方式三:从文件加载迁移
|
#### 方式三:从文件加载迁移(推荐)
|
||||||
|
|
||||||
```go
|
```go
|
||||||
// 文件命名格式: {version}_{description}.sql 或 {version}_{description}.up.sql
|
// 支持的文件命名格式:
|
||||||
// 例如: 20240101000001_create_users_table.up.sql
|
// 1. 数字前缀: 01_init_schema.sql
|
||||||
// 对应的回滚文件: 20240101000001_create_users_table.down.sql
|
// 2. 时间戳: 20240101000001_create_users.sql
|
||||||
|
// 3. 带.up后缀: 20240101000001_create_users.up.sql
|
||||||
|
// 对应的回滚文件: 20240101000001_create_users.down.sql
|
||||||
|
|
||||||
migrations, err := migration.LoadMigrationsFromFiles("./migrations", "*.up.sql")
|
migrations, err := migration.LoadMigrationsFromFiles("./migrations", "*.sql")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatal(err)
|
log.Fatal(err)
|
||||||
}
|
}
|
||||||
@@ -101,6 +197,12 @@ if err != nil {
|
|||||||
migrator.AddMigrations(migrations...)
|
migrator.AddMigrations(migrations...)
|
||||||
```
|
```
|
||||||
|
|
||||||
|
**新特性:**
|
||||||
|
- ✅ 支持数字前缀命名(如 `01_init_schema.sql`)
|
||||||
|
- ✅ 自动分割多行 SQL 语句
|
||||||
|
- ✅ 自动处理注释(单行 `--` 和多行 `/* */`)
|
||||||
|
- ✅ 记录执行时间(毫秒)
|
||||||
|
|
||||||
### 3. 执行迁移
|
### 3. 执行迁移
|
||||||
|
|
||||||
```go
|
```go
|
||||||
@@ -289,15 +391,31 @@ type MigrationStatus struct {
|
|||||||
|
|
||||||
**参数:**
|
**参数:**
|
||||||
- `dir`: 迁移文件目录
|
- `dir`: 迁移文件目录
|
||||||
- `pattern`: 文件匹配模式,如 "*.up.sql"
|
- `pattern`: 文件匹配模式,如 "*.sql" 或 "*.up.sql"
|
||||||
|
|
||||||
**返回:** 迁移列表和错误信息
|
**返回:** 迁移列表和错误信息
|
||||||
|
|
||||||
**文件命名格式:** `{version}_{description}.up.sql`
|
**支持的文件命名格式:**
|
||||||
|
|
||||||
**示例:**
|
1. **数字前缀格式**(新支持):
|
||||||
- `20240101000001_create_users_table.up.sql` - 升级文件
|
- `01_init_schema.sql`
|
||||||
- `20240101000001_create_users_table.down.sql` - 回滚文件(可选)
|
- `02_init_data.sql`
|
||||||
|
- `03_add_log_schema.sql`
|
||||||
|
|
||||||
|
2. **时间戳格式**(现有):
|
||||||
|
- `20240101000001_create_users.sql`
|
||||||
|
- `20240101000002_add_index.sql`
|
||||||
|
|
||||||
|
3. **带.up后缀格式**(现有):
|
||||||
|
- `20240101000001_create_users.up.sql` - 升级文件
|
||||||
|
- `20240101000001_create_users.down.sql` - 回滚文件(可选)
|
||||||
|
|
||||||
|
**新特性:**
|
||||||
|
- ✅ 自动识别文件命名格式(数字前缀或时间戳)
|
||||||
|
- ✅ 自动分割多行 SQL 语句(按分号分割)
|
||||||
|
- ✅ 自动处理注释(单行 `--` 和多行 `/* */`)
|
||||||
|
- ✅ 自动跳过空行和空白字符
|
||||||
|
- ✅ 支持一个文件包含多个 SQL 语句
|
||||||
|
|
||||||
#### GenerateVersion() string
|
#### GenerateVersion() string
|
||||||
|
|
||||||
|
|||||||
@@ -325,8 +325,20 @@ func main() {
|
|||||||
proxyHandler := storage.NewProxyHandler(ossStorage)
|
proxyHandler := storage.NewProxyHandler(ossStorage)
|
||||||
|
|
||||||
// 创建中间件链
|
// 创建中间件链
|
||||||
|
var corsConfig *middleware.CORSConfig
|
||||||
|
if cfg.GetCORS() != nil {
|
||||||
|
c := cfg.GetCORS()
|
||||||
|
corsConfig = middleware.NewCORSConfig(
|
||||||
|
c.AllowedOrigins,
|
||||||
|
c.AllowedMethods,
|
||||||
|
c.AllowedHeaders,
|
||||||
|
c.ExposedHeaders,
|
||||||
|
c.AllowCredentials,
|
||||||
|
c.MaxAge,
|
||||||
|
)
|
||||||
|
}
|
||||||
chain := middleware.NewChain(
|
chain := middleware.NewChain(
|
||||||
middleware.CORS(cfg.GetCORS()),
|
middleware.CORS(corsConfig),
|
||||||
middleware.Timezone,
|
middleware.Timezone,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|||||||
183
email/email.go
183
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正文(可选,如果设置了会优先使用)
|
||||||
// Content 文件内容
|
func (e *Email) SendEmail(to []string, subject, body string, htmlBody ...string) error {
|
||||||
Content []byte
|
cfg, err := e.getEmailConfig()
|
||||||
|
if err != nil {
|
||||||
// ContentType 文件类型(如:application/pdf)
|
return err
|
||||||
ContentType string
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// SendRaw 发送原始邮件内容
|
msg := &Message{
|
||||||
// recipients: 收件人列表(To、Cc、Bcc的合并列表)
|
To: to,
|
||||||
// body: 完整的邮件内容(MIME格式),由外部构建
|
Subject: subject,
|
||||||
func (e *Email) SendRaw(recipients []string, body []byte) error {
|
Body: body,
|
||||||
if len(recipients) == 0 {
|
}
|
||||||
|
|
||||||
|
if len(htmlBody) > 0 && htmlBody[0] != "" {
|
||||||
|
msg.HTMLBody = htmlBody[0]
|
||||||
|
}
|
||||||
|
|
||||||
|
return e.send(msg, cfg)
|
||||||
|
}
|
||||||
|
|
||||||
|
// send 发送邮件(内部方法)
|
||||||
|
func (e *Email) send(msg *Message, cfg *config.EmailConfig) error {
|
||||||
|
if msg == nil {
|
||||||
|
return fmt.Errorf("message is nil")
|
||||||
|
}
|
||||||
|
|
||||||
|
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,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -65,16 +65,27 @@ func main() {
|
|||||||
|
|
||||||
// 4. 使用CORS配置
|
// 4. 使用CORS配置
|
||||||
fmt.Println("\n=== CORS Config ===")
|
fmt.Println("\n=== CORS Config ===")
|
||||||
corsConfig := cfg.GetCORS()
|
configCORS := cfg.GetCORS()
|
||||||
if corsConfig != nil {
|
if configCORS != nil {
|
||||||
fmt.Printf("Allowed Origins: %v\n", corsConfig.AllowedOrigins)
|
fmt.Printf("Allowed Origins: %v\n", configCORS.AllowedOrigins)
|
||||||
fmt.Printf("Allowed Methods: %v\n", corsConfig.AllowedMethods)
|
fmt.Printf("Allowed Methods: %v\n", configCORS.AllowedMethods)
|
||||||
fmt.Printf("Max Age: %d\n", corsConfig.MaxAge)
|
fmt.Printf("Max Age: %d\n", configCORS.MaxAge)
|
||||||
}
|
}
|
||||||
|
|
||||||
// 使用CORS配置创建中间件
|
// 使用CORS配置创建中间件
|
||||||
|
var middlewareCORS *middleware.CORSConfig
|
||||||
|
if configCORS != nil {
|
||||||
|
middlewareCORS = middleware.NewCORSConfig(
|
||||||
|
configCORS.AllowedOrigins,
|
||||||
|
configCORS.AllowedMethods,
|
||||||
|
configCORS.AllowedHeaders,
|
||||||
|
configCORS.ExposedHeaders,
|
||||||
|
configCORS.AllowCredentials,
|
||||||
|
configCORS.MaxAge,
|
||||||
|
)
|
||||||
|
}
|
||||||
chain := middleware.NewChain(
|
chain := middleware.NewChain(
|
||||||
middleware.CORS(corsConfig),
|
middleware.CORS(middlewareCORS),
|
||||||
)
|
)
|
||||||
fmt.Printf("CORS middleware created: %v\n", chain != nil)
|
fmt.Printf("CORS middleware created: %v\n", chain != nil)
|
||||||
|
|
||||||
|
|||||||
@@ -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))
|
|
||||||
}
|
|
||||||
|
|
||||||
233
examples/excel_example.go
Normal file
233
examples/excel_example.go
Normal file
@@ -0,0 +1,233 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"log"
|
||||||
|
"net/http"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"git.toowon.com/jimmy/go-common/excel"
|
||||||
|
"git.toowon.com/jimmy/go-common/factory"
|
||||||
|
"git.toowon.com/jimmy/go-common/tools"
|
||||||
|
)
|
||||||
|
|
||||||
|
// User 用户结构体示例
|
||||||
|
type User struct {
|
||||||
|
ID int `json:"id"`
|
||||||
|
Name string `json:"name"`
|
||||||
|
Email string `json:"email"`
|
||||||
|
CreatedAt time.Time `json:"created_at"`
|
||||||
|
Status int `json:"status"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
// 创建工厂(可选,Excel导出不需要配置)
|
||||||
|
fac, err := factory.NewFactoryFromFile("./config/example.json")
|
||||||
|
if err != nil {
|
||||||
|
// Excel导出不需要配置,可以传nil
|
||||||
|
fac = factory.NewFactory(nil)
|
||||||
|
}
|
||||||
|
|
||||||
|
// 示例1:导出结构体切片到文件
|
||||||
|
fmt.Println("=== Example 1: Export Struct Slice to File ===")
|
||||||
|
example1(fac)
|
||||||
|
|
||||||
|
// 示例2:导出到HTTP响应
|
||||||
|
fmt.Println("\n=== Example 2: Export to HTTP Response ===")
|
||||||
|
example2(fac)
|
||||||
|
|
||||||
|
// 示例3:使用格式化函数
|
||||||
|
fmt.Println("\n=== Example 3: Export with Format Functions ===")
|
||||||
|
example3(fac)
|
||||||
|
|
||||||
|
// 示例4:使用ExportData接口
|
||||||
|
fmt.Println("\n=== Example 4: Export with ExportData Interface ===")
|
||||||
|
example4(fac)
|
||||||
|
}
|
||||||
|
|
||||||
|
// 示例1:导出结构体切片到文件
|
||||||
|
func example1(fac *factory.Factory) {
|
||||||
|
users := []User{
|
||||||
|
{ID: 1, Name: "Alice", Email: "alice@example.com", CreatedAt: time.Now(), Status: 1},
|
||||||
|
{ID: 2, Name: "Bob", Email: "bob@example.com", CreatedAt: time.Now().Add(-24 * time.Hour), Status: 1},
|
||||||
|
{ID: 3, Name: "Charlie", Email: "charlie@example.com", CreatedAt: time.Now().Add(-48 * time.Hour), Status: 0},
|
||||||
|
}
|
||||||
|
|
||||||
|
columns := []factory.ExportColumn{
|
||||||
|
{Header: "ID", Field: "ID", Width: 10},
|
||||||
|
{Header: "姓名", Field: "Name", Width: 20},
|
||||||
|
{Header: "邮箱", Field: "Email", Width: 30},
|
||||||
|
{Header: "创建时间", Field: "CreatedAt", Width: 20},
|
||||||
|
{Header: "状态", Field: "Status", Width: 10},
|
||||||
|
}
|
||||||
|
|
||||||
|
err := fac.ExportToExcelFile("users.xlsx", "用户列表", columns, users)
|
||||||
|
if err != nil {
|
||||||
|
log.Printf("Failed to export to file: %v", err)
|
||||||
|
} else {
|
||||||
|
fmt.Println("Excel file exported successfully: users.xlsx")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 示例2:导出到HTTP响应
|
||||||
|
func example2(fac *factory.Factory) {
|
||||||
|
// 模拟HTTP响应
|
||||||
|
w := &mockResponseWriter{}
|
||||||
|
|
||||||
|
users := []User{
|
||||||
|
{ID: 1, Name: "Alice", Email: "alice@example.com", CreatedAt: time.Now(), Status: 1},
|
||||||
|
{ID: 2, Name: "Bob", Email: "bob@example.com", CreatedAt: time.Now(), Status: 1},
|
||||||
|
}
|
||||||
|
|
||||||
|
columns := []factory.ExportColumn{
|
||||||
|
{Header: "ID", Field: "ID"},
|
||||||
|
{Header: "姓名", Field: "Name"},
|
||||||
|
{Header: "邮箱", Field: "Email"},
|
||||||
|
}
|
||||||
|
|
||||||
|
// 设置HTTP响应头
|
||||||
|
w.Header().Set("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
|
||||||
|
w.Header().Set("Content-Disposition", "attachment; filename=users.xlsx")
|
||||||
|
|
||||||
|
err := fac.ExportToExcel(w, "用户列表", columns, users)
|
||||||
|
if err != nil {
|
||||||
|
log.Printf("Failed to export to HTTP response: %v", err)
|
||||||
|
} else {
|
||||||
|
fmt.Printf("Excel exported to HTTP response successfully, size: %d bytes\n", len(w.data))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 示例3:使用格式化函数
|
||||||
|
func example3(fac *factory.Factory) {
|
||||||
|
users := []User{
|
||||||
|
{ID: 1, Name: "Alice", Email: "alice@example.com", CreatedAt: time.Now(), Status: 1},
|
||||||
|
{ID: 2, Name: "Bob", Email: "bob@example.com", CreatedAt: time.Now().Add(-24 * time.Hour), Status: 0},
|
||||||
|
}
|
||||||
|
|
||||||
|
columns := []factory.ExportColumn{
|
||||||
|
{Header: "ID", Field: "ID", Width: 10},
|
||||||
|
{Header: "姓名", Field: "Name", Width: 20},
|
||||||
|
{Header: "邮箱", Field: "Email", Width: 30},
|
||||||
|
{
|
||||||
|
Header: "创建时间",
|
||||||
|
Field: "CreatedAt",
|
||||||
|
Width: 20,
|
||||||
|
Format: excel.AdaptTimeFormatter(tools.FormatDateTime), // 使用适配器直接调用tools函数
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Header: "状态",
|
||||||
|
Field: "Status",
|
||||||
|
Width: 10,
|
||||||
|
Format: func(value interface{}) string {
|
||||||
|
// 自定义格式化函数
|
||||||
|
if status, ok := value.(int); ok {
|
||||||
|
if status == 1 {
|
||||||
|
return "启用"
|
||||||
|
}
|
||||||
|
return "禁用"
|
||||||
|
}
|
||||||
|
return ""
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
err := fac.ExportToExcelFile("users_formatted.xlsx", "用户列表", columns, users)
|
||||||
|
if err != nil {
|
||||||
|
log.Printf("Failed to export with format: %v", err)
|
||||||
|
} else {
|
||||||
|
fmt.Println("Excel file exported with format successfully: users_formatted.xlsx")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 示例4:使用ExportData接口
|
||||||
|
func example4(fac *factory.Factory) {
|
||||||
|
// 创建实现了ExportData接口的数据对象
|
||||||
|
exportData := &UserExportData{
|
||||||
|
users: []User{
|
||||||
|
{ID: 1, Name: "Alice", Email: "alice@example.com", CreatedAt: time.Now(), Status: 1},
|
||||||
|
{ID: 2, Name: "Bob", Email: "bob@example.com", CreatedAt: time.Now(), Status: 1},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
// 使用接口方法获取列定义和数据
|
||||||
|
columns := exportData.GetExportColumns()
|
||||||
|
|
||||||
|
err := fac.ExportToExcelFile("users_interface.xlsx", "用户列表", columns, exportData)
|
||||||
|
if err != nil {
|
||||||
|
log.Printf("Failed to export with interface: %v", err)
|
||||||
|
} else {
|
||||||
|
fmt.Println("Excel file exported with interface successfully: users_interface.xlsx")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// UserExportData 实现了ExportData接口的用户导出数据
|
||||||
|
type UserExportData struct {
|
||||||
|
users []User
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetExportColumns 获取导出列定义
|
||||||
|
func (d *UserExportData) GetExportColumns() []excel.ExportColumn {
|
||||||
|
return []excel.ExportColumn{
|
||||||
|
{Header: "ID", Field: "ID", Width: 10},
|
||||||
|
{Header: "姓名", Field: "Name", Width: 20},
|
||||||
|
{Header: "邮箱", Field: "Email", Width: 30},
|
||||||
|
{
|
||||||
|
Header: "创建时间",
|
||||||
|
Field: "CreatedAt",
|
||||||
|
Width: 20,
|
||||||
|
Format: excel.AdaptTimeFormatter(tools.FormatDateTime),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Header: "状态",
|
||||||
|
Field: "Status",
|
||||||
|
Width: 10,
|
||||||
|
Format: func(value interface{}) string {
|
||||||
|
if status, ok := value.(int); ok {
|
||||||
|
if status == 1 {
|
||||||
|
return "启用"
|
||||||
|
}
|
||||||
|
return "禁用"
|
||||||
|
}
|
||||||
|
return ""
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetExportRows 获取导出数据行
|
||||||
|
func (d *UserExportData) GetExportRows() [][]interface{} {
|
||||||
|
rows := make([][]interface{}, 0, len(d.users))
|
||||||
|
for _, user := range d.users {
|
||||||
|
row := []interface{}{
|
||||||
|
user.ID,
|
||||||
|
user.Name,
|
||||||
|
user.Email,
|
||||||
|
user.CreatedAt,
|
||||||
|
user.Status,
|
||||||
|
}
|
||||||
|
rows = append(rows, row)
|
||||||
|
}
|
||||||
|
return rows
|
||||||
|
}
|
||||||
|
|
||||||
|
// mockResponseWriter 模拟HTTP响应写入器(用于示例)
|
||||||
|
type mockResponseWriter struct {
|
||||||
|
header http.Header
|
||||||
|
data []byte
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *mockResponseWriter) Header() http.Header {
|
||||||
|
if w.header == nil {
|
||||||
|
w.header = make(http.Header)
|
||||||
|
}
|
||||||
|
return w.header
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *mockResponseWriter) Write(data []byte) (int, error) {
|
||||||
|
w.data = append(w.data, data...)
|
||||||
|
return len(data), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *mockResponseWriter) WriteHeader(statusCode int) {
|
||||||
|
// 模拟实现
|
||||||
|
}
|
||||||
166
examples/factory_blackbox_example.go
Normal file
166
examples/factory_blackbox_example.go
Normal file
@@ -0,0 +1,166 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"log"
|
||||||
|
"net/http"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"git.toowon.com/jimmy/go-common/factory"
|
||||||
|
)
|
||||||
|
|
||||||
|
// 示例:Factory黑盒模式 - 最简化的使用方式
|
||||||
|
//
|
||||||
|
// 核心理念:
|
||||||
|
//
|
||||||
|
// 外部项目只需要传递一个配置文件路径,
|
||||||
|
// 直接使用 factory 的黑盒方法,无需获取内部对象
|
||||||
|
func main() {
|
||||||
|
// ====== 第1步:创建工厂(只需要配置文件路径)======
|
||||||
|
fac, err := factory.NewFactoryFromFile("config.json")
|
||||||
|
if err != nil {
|
||||||
|
log.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ====== 第2步:使用黑盒方法(推荐)======
|
||||||
|
|
||||||
|
// 1. 获取中间件链(自动配置所有基础中间件)
|
||||||
|
chain := fac.GetMiddlewareChain()
|
||||||
|
|
||||||
|
// 2. 添加项目特定的自定义中间件
|
||||||
|
chain.Append(authMiddleware, metricsMiddleware)
|
||||||
|
|
||||||
|
// 3. 注册路由
|
||||||
|
http.Handle("/api/users", chain.ThenFunc(handleUsers))
|
||||||
|
http.Handle("/api/upload", chain.ThenFunc(handleUpload))
|
||||||
|
|
||||||
|
// 4. 启动服务
|
||||||
|
log.Println("Server started on :8080")
|
||||||
|
log.Fatal(http.ListenAndServe(":8080", nil))
|
||||||
|
}
|
||||||
|
|
||||||
|
// ====== API处理器 ======
|
||||||
|
|
||||||
|
// 用户列表
|
||||||
|
func handleUsers(w http.ResponseWriter, r *http.Request) {
|
||||||
|
// 创建工厂(在处理器中也可以复用)
|
||||||
|
fac, _ := factory.NewFactoryFromFile("config.json")
|
||||||
|
ctx := context.Background()
|
||||||
|
|
||||||
|
// 1. 使用数据库(需要获取对象,因为GORM很复杂)
|
||||||
|
db, _ := fac.GetDatabase()
|
||||||
|
var users []map[string]interface{}
|
||||||
|
db.Table("users").Find(&users)
|
||||||
|
|
||||||
|
// 2. 使用Redis(黑盒方法,推荐)
|
||||||
|
cacheKey := "users:list"
|
||||||
|
cached, _ := fac.RedisGet(ctx, cacheKey)
|
||||||
|
if cached != "" {
|
||||||
|
fac.Success(w, cached)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// 3. 记录日志(黑盒方法,推荐)
|
||||||
|
fac.LogInfof(map[string]interface{}{
|
||||||
|
"action": "list_users",
|
||||||
|
"count": len(users),
|
||||||
|
}, "查询用户列表")
|
||||||
|
|
||||||
|
// 4. 缓存结果
|
||||||
|
fac.RedisSet(ctx, cacheKey, users, 5*time.Minute)
|
||||||
|
|
||||||
|
fac.Success(w, users)
|
||||||
|
}
|
||||||
|
|
||||||
|
// 文件上传
|
||||||
|
func handleUpload(w http.ResponseWriter, r *http.Request) {
|
||||||
|
fac, _ := factory.NewFactoryFromFile("config.json")
|
||||||
|
ctx := context.Background()
|
||||||
|
|
||||||
|
// 解析上传的文件
|
||||||
|
file, header, err := r.FormFile("file")
|
||||||
|
if err != nil {
|
||||||
|
fac.LogError("文件上传失败: %v", err)
|
||||||
|
fac.Error(w, 400, "文件上传失败")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
defer file.Close()
|
||||||
|
|
||||||
|
// 上传文件(黑盒方法,自动选择OSS或MinIO)
|
||||||
|
objectKey := "uploads/" + header.Filename
|
||||||
|
url, err := fac.UploadFile(ctx, objectKey, file, header.Header.Get("Content-Type"))
|
||||||
|
if err != nil {
|
||||||
|
fac.LogError("文件上传到存储失败: %v", err)
|
||||||
|
fac.Error(w, 500, "文件上传失败")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// 记录上传日志
|
||||||
|
fac.LogInfof(map[string]interface{}{
|
||||||
|
"filename": header.Filename,
|
||||||
|
"size": header.Size,
|
||||||
|
"url": url,
|
||||||
|
}, "文件上传成功")
|
||||||
|
|
||||||
|
fac.Success(w, map[string]interface{}{
|
||||||
|
"url": url,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// ====== 自定义中间件 ======
|
||||||
|
|
||||||
|
// 认证中间件
|
||||||
|
func authMiddleware(next http.Handler) http.Handler {
|
||||||
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
fac, _ := factory.NewFactoryFromFile("config.json")
|
||||||
|
ctx := context.Background()
|
||||||
|
|
||||||
|
// 获取token
|
||||||
|
token := r.Header.Get("Authorization")
|
||||||
|
if token == "" {
|
||||||
|
fac.Error(w, 401, "未授权")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// 从Redis验证token(黑盒方法)
|
||||||
|
userID, err := fac.RedisGet(ctx, "token:"+token)
|
||||||
|
if err != nil || userID == "" {
|
||||||
|
fac.Error(w, 401, "token无效")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// 记录日志(黑盒方法)
|
||||||
|
fac.LogInfof(map[string]interface{}{
|
||||||
|
"user_id": userID,
|
||||||
|
"path": r.URL.Path,
|
||||||
|
}, "用户请求")
|
||||||
|
|
||||||
|
// 将用户ID存入context(或header)
|
||||||
|
r.Header.Set("X-User-ID", userID)
|
||||||
|
next.ServeHTTP(w, r)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// 指标中间件
|
||||||
|
func metricsMiddleware(next http.Handler) http.Handler {
|
||||||
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
fac, _ := factory.NewFactoryFromFile("config.json")
|
||||||
|
ctx := context.Background()
|
||||||
|
|
||||||
|
start := time.Now()
|
||||||
|
|
||||||
|
// 继续处理请求
|
||||||
|
next.ServeHTTP(w, r)
|
||||||
|
|
||||||
|
// 记录请求耗时到Redis(黑盒方法)
|
||||||
|
latency := time.Since(start).Milliseconds()
|
||||||
|
key := "metrics:" + r.URL.Path
|
||||||
|
fac.RedisSet(ctx, key, latency, time.Minute)
|
||||||
|
|
||||||
|
// 记录指标日志(黑盒方法)
|
||||||
|
fac.LogDebugf(map[string]interface{}{
|
||||||
|
"path": r.URL.Path,
|
||||||
|
"latency": latency,
|
||||||
|
}, "请求指标")
|
||||||
|
})
|
||||||
|
}
|
||||||
@@ -1,186 +0,0 @@
|
|||||||
package main
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"fmt"
|
|
||||||
"log"
|
|
||||||
"os"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"git.toowon.com/jimmy/go-common/factory"
|
|
||||||
"github.com/redis/go-redis/v9"
|
|
||||||
)
|
|
||||||
|
|
||||||
func main() {
|
|
||||||
// 方式1:直接从配置文件创建工厂(推荐)
|
|
||||||
fac, err := factory.NewFactoryFromFile("./config/example.json")
|
|
||||||
if err != nil {
|
|
||||||
log.Fatal("Failed to create factory:", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
ctx := context.Background()
|
|
||||||
|
|
||||||
// ========== 日志记录(黑盒模式,推荐) ==========
|
|
||||||
fac.LogInfo("应用启动")
|
|
||||||
fac.LogDebug("调试信息: %s", "test")
|
|
||||||
fac.LogWarn("警告信息")
|
|
||||||
fac.LogError("错误信息: %v", fmt.Errorf("test error"))
|
|
||||||
|
|
||||||
// 带字段的日志
|
|
||||||
fac.LogInfof(map[string]interface{}{
|
|
||||||
"user_id": 123,
|
|
||||||
"ip": "192.168.1.1",
|
|
||||||
}, "用户登录成功")
|
|
||||||
|
|
||||||
fac.LogErrorf(map[string]interface{}{
|
|
||||||
"error_code": 1001,
|
|
||||||
"user_id": 123,
|
|
||||||
}, "登录失败: %v", fmt.Errorf("invalid password"))
|
|
||||||
|
|
||||||
// ========== 邮件发送(黑盒模式,推荐) ==========
|
|
||||||
err = fac.SendEmail(
|
|
||||||
[]string{"user@example.com"},
|
|
||||||
"验证码",
|
|
||||||
"您的验证码是:123456",
|
|
||||||
)
|
|
||||||
if err != nil {
|
|
||||||
fac.LogError("发送邮件失败: %v", err)
|
|
||||||
} else {
|
|
||||||
fac.LogInfo("邮件发送成功")
|
|
||||||
}
|
|
||||||
|
|
||||||
// HTML邮件
|
|
||||||
err = fac.SendEmail(
|
|
||||||
[]string{"user@example.com"},
|
|
||||||
"欢迎",
|
|
||||||
"纯文本内容",
|
|
||||||
"<h1>HTML内容</h1>",
|
|
||||||
)
|
|
||||||
if err != nil {
|
|
||||||
fac.LogError("发送HTML邮件失败: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
// ========== 短信发送(黑盒模式,推荐) ==========
|
|
||||||
resp, err := fac.SendSMS(
|
|
||||||
[]string{"13800138000"},
|
|
||||||
map[string]string{"code": "123456"},
|
|
||||||
)
|
|
||||||
if err != nil {
|
|
||||||
fac.LogError("发送短信失败: %v", err)
|
|
||||||
} else {
|
|
||||||
fac.LogInfo("短信发送成功: %s", resp.RequestID)
|
|
||||||
}
|
|
||||||
|
|
||||||
// 指定模板代码
|
|
||||||
resp, err = fac.SendSMS(
|
|
||||||
[]string{"13800138000"},
|
|
||||||
map[string]string{"code": "123456"},
|
|
||||||
"SMS_123456789", // 模板代码
|
|
||||||
)
|
|
||||||
if err != nil {
|
|
||||||
fac.LogError("发送短信失败: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
// ========== 文件上传(黑盒模式,推荐,自动选择OSS或MinIO) ==========
|
|
||||||
file, err := os.Open("test.jpg")
|
|
||||||
if err == nil {
|
|
||||||
defer file.Close()
|
|
||||||
|
|
||||||
url, err := fac.UploadFile(ctx, "images/test.jpg", file, "image/jpeg")
|
|
||||||
if err != nil {
|
|
||||||
fac.LogError("上传文件失败: %v", err)
|
|
||||||
} else {
|
|
||||||
fac.LogInfo("文件上传成功: %s", url)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// ========== 获取文件URL(黑盒模式) ==========
|
|
||||||
// 永久有效
|
|
||||||
url, err := fac.GetFileURL("images/test.jpg", 0)
|
|
||||||
if err != nil {
|
|
||||||
fac.LogError("获取文件URL失败: %v", err)
|
|
||||||
} else {
|
|
||||||
fac.LogInfo("文件URL: %s", url)
|
|
||||||
}
|
|
||||||
|
|
||||||
// 临时访问URL(1小时后过期)
|
|
||||||
url, err = fac.GetFileURL("images/test.jpg", 3600)
|
|
||||||
if err != nil {
|
|
||||||
fac.LogError("获取临时URL失败: %v", err)
|
|
||||||
} else {
|
|
||||||
fac.LogInfo("临时URL: %s", url)
|
|
||||||
}
|
|
||||||
|
|
||||||
// ========== Redis操作(黑盒模式,推荐) ==========
|
|
||||||
// 设置值(不过期)
|
|
||||||
err = fac.RedisSet(ctx, "user:123", "value")
|
|
||||||
if err != nil {
|
|
||||||
fac.LogError("Redis设置失败: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
// 设置值(带过期时间)
|
|
||||||
err = fac.RedisSet(ctx, "user:123", "value", time.Hour)
|
|
||||||
if err != nil {
|
|
||||||
fac.LogError("Redis设置失败: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
// 获取值
|
|
||||||
value, err := fac.RedisGet(ctx, "user:123")
|
|
||||||
if err != nil {
|
|
||||||
fac.LogError("Redis获取失败: %v", err)
|
|
||||||
} else {
|
|
||||||
fac.LogInfo("Redis值: %s", value)
|
|
||||||
}
|
|
||||||
|
|
||||||
// 删除键
|
|
||||||
err = fac.RedisDelete(ctx, "user:123", "user:456")
|
|
||||||
if err != nil {
|
|
||||||
fac.LogError("Redis删除失败: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
// 检查键是否存在
|
|
||||||
exists, err := fac.RedisExists(ctx, "user:123")
|
|
||||||
if err != nil {
|
|
||||||
fac.LogError("Redis检查失败: %v", err)
|
|
||||||
} else {
|
|
||||||
fac.LogInfo("键是否存在: %v", exists)
|
|
||||||
}
|
|
||||||
|
|
||||||
// ========== 数据库操作(黑盒模式,获取对象) ==========
|
|
||||||
db, err := fac.GetDatabase()
|
|
||||||
if err != nil {
|
|
||||||
fac.LogError("数据库连接失败: %v", err)
|
|
||||||
} else {
|
|
||||||
// 直接使用GORM,无需自己实现创建逻辑
|
|
||||||
var count int64
|
|
||||||
if err := db.Table("users").Count(&count).Error; err != nil {
|
|
||||||
fac.LogError("查询用户数量失败: %v", err)
|
|
||||||
} else {
|
|
||||||
fac.LogInfo("用户数量: %d", count)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// ========== Redis操作(获取客户端对象,黑盒模式) ==========
|
|
||||||
redisClient, err := fac.GetRedisClient()
|
|
||||||
if err != nil {
|
|
||||||
fac.LogError("Redis客户端不可用: %v", err)
|
|
||||||
} else {
|
|
||||||
// 直接使用Redis客户端,无需自己实现创建逻辑
|
|
||||||
val, err := redisClient.Get(ctx, "test_key").Result()
|
|
||||||
if err != nil && err != redis.Nil {
|
|
||||||
fac.LogError("Redis错误: %v", err)
|
|
||||||
} else if err == redis.Nil {
|
|
||||||
fac.LogInfo("Redis键不存在")
|
|
||||||
} else {
|
|
||||||
fac.LogInfo("Redis值: %s", val)
|
|
||||||
}
|
|
||||||
|
|
||||||
// 使用高级功能(如Hash操作)
|
|
||||||
redisClient.HSet(ctx, "user:123", "name", "John")
|
|
||||||
name, _ := redisClient.HGet(ctx, "user:123", "name").Result()
|
|
||||||
fac.LogInfo("Redis Hash值: %s", name)
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
fac.LogInfo("示例执行完成")
|
|
||||||
}
|
|
||||||
@@ -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,6 +4,7 @@ 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"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -20,26 +21,27 @@ 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() // 计算偏移量
|
||||||
|
|
||||||
// 模拟查询数据
|
// 模拟查询数据
|
||||||
@@ -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 条新消息"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,66 +0,0 @@
|
|||||||
package main
|
|
||||||
|
|
||||||
import (
|
|
||||||
"log"
|
|
||||||
"net/http"
|
|
||||||
|
|
||||||
"git.toowon.com/jimmy/go-common/datetime"
|
|
||||||
commonhttp "git.toowon.com/jimmy/go-common/http"
|
|
||||||
"git.toowon.com/jimmy/go-common/middleware"
|
|
||||||
)
|
|
||||||
|
|
||||||
// 示例:使用CORS和时区中间件
|
|
||||||
func main() {
|
|
||||||
// 配置CORS
|
|
||||||
corsConfig := &middleware.CORSConfig{
|
|
||||||
AllowedOrigins: []string{"*"},
|
|
||||||
AllowedMethods: []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"},
|
|
||||||
AllowedHeaders: []string{
|
|
||||||
"Content-Type",
|
|
||||||
"Authorization",
|
|
||||||
"X-Requested-With",
|
|
||||||
"X-Timezone",
|
|
||||||
},
|
|
||||||
AllowCredentials: false,
|
|
||||||
MaxAge: 3600,
|
|
||||||
}
|
|
||||||
|
|
||||||
// 创建中间件链
|
|
||||||
chain := middleware.NewChain(
|
|
||||||
middleware.CORS(corsConfig),
|
|
||||||
middleware.Timezone,
|
|
||||||
)
|
|
||||||
|
|
||||||
// 定义处理器(使用Handler模式)
|
|
||||||
handler := chain.ThenFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
||||||
h := commonhttp.NewHandler(w, r)
|
|
||||||
apiHandler(h)
|
|
||||||
})
|
|
||||||
|
|
||||||
// 注册路由
|
|
||||||
http.Handle("/api", handler)
|
|
||||||
|
|
||||||
log.Println("Server started on :8080")
|
|
||||||
log.Println("Try: curl -H 'X-Timezone: America/New_York' http://localhost:8080/api")
|
|
||||||
log.Fatal(http.ListenAndServe(":8080", nil))
|
|
||||||
}
|
|
||||||
|
|
||||||
// apiHandler 处理API请求(使用Handler模式)
|
|
||||||
func apiHandler(h *commonhttp.Handler) {
|
|
||||||
// 从Handler获取时区
|
|
||||||
timezone := h.GetTimezone()
|
|
||||||
|
|
||||||
// 使用时区进行时间处理
|
|
||||||
now := datetime.Now(timezone)
|
|
||||||
startOfDay := datetime.StartOfDay(now, timezone)
|
|
||||||
endOfDay := datetime.EndOfDay(now, timezone)
|
|
||||||
|
|
||||||
// 返回响应
|
|
||||||
h.Success(map[string]interface{}{
|
|
||||||
"message": "Hello from API",
|
|
||||||
"timezone": timezone,
|
|
||||||
"currentTime": datetime.FormatDateTime(now),
|
|
||||||
"startOfDay": datetime.FormatDateTime(startOfDay),
|
|
||||||
"endOfDay": datetime.FormatDateTime(endOfDay),
|
|
||||||
})
|
|
||||||
}
|
|
||||||
40
examples/middleware_simple_example.go
Normal file
40
examples/middleware_simple_example.go
Normal file
@@ -0,0 +1,40 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"log"
|
||||||
|
"net/http"
|
||||||
|
|
||||||
|
commonhttp "git.toowon.com/jimmy/go-common/http"
|
||||||
|
"git.toowon.com/jimmy/go-common/middleware"
|
||||||
|
)
|
||||||
|
|
||||||
|
// 示例:简单的中间件配置
|
||||||
|
// 包括:Recovery、Logging、CORS、Timezone
|
||||||
|
func main() {
|
||||||
|
// 创建简单的中间件链(使用默认配置)
|
||||||
|
chain := middleware.NewChain(
|
||||||
|
middleware.Recovery(nil), // Panic恢复(使用默认logger)
|
||||||
|
middleware.Logging(nil), // 请求日志(使用默认logger)
|
||||||
|
middleware.CORS(nil), // CORS(允许所有源)
|
||||||
|
middleware.Timezone, // 时区处理(默认AsiaShanghai)
|
||||||
|
)
|
||||||
|
|
||||||
|
// 定义API处理器
|
||||||
|
http.Handle("/api/hello", chain.ThenFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
// 获取时区(使用公共方法)
|
||||||
|
timezone := commonhttp.GetTimezone(r)
|
||||||
|
|
||||||
|
// 返回响应(使用公共方法)
|
||||||
|
commonhttp.Success(w, map[string]interface{}{
|
||||||
|
"message": "Hello, World!",
|
||||||
|
"timezone": timezone,
|
||||||
|
})
|
||||||
|
}))
|
||||||
|
|
||||||
|
// 启动服务器
|
||||||
|
addr := ":8080"
|
||||||
|
log.Printf("Server starting on %s", addr)
|
||||||
|
log.Printf("Try: http://localhost%s/api/hello", addr)
|
||||||
|
log.Fatal(http.ListenAndServe(addr, nil))
|
||||||
|
}
|
||||||
|
|
||||||
@@ -1,58 +0,0 @@
|
|||||||
package main
|
|
||||||
|
|
||||||
import (
|
|
||||||
"fmt"
|
|
||||||
"log"
|
|
||||||
|
|
||||||
"gorm.io/driver/mysql"
|
|
||||||
"gorm.io/gorm"
|
|
||||||
"git.toowon.com/jimmy/go-common/migration"
|
|
||||||
)
|
|
||||||
|
|
||||||
func main() {
|
|
||||||
// 初始化数据库连接
|
|
||||||
dsn := "user:password@tcp(localhost:3306)/dbname?charset=utf8mb4&parseTime=True&loc=Local"
|
|
||||||
db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
|
|
||||||
if err != nil {
|
|
||||||
log.Fatal(err)
|
|
||||||
}
|
|
||||||
|
|
||||||
// 创建迁移器
|
|
||||||
migrator := migration.NewMigrator(db)
|
|
||||||
|
|
||||||
// 添加迁移
|
|
||||||
migrator.AddMigration(migration.Migration{
|
|
||||||
Version: "20240101000001",
|
|
||||||
Description: "create_users_table",
|
|
||||||
Up: func(db *gorm.DB) error {
|
|
||||||
return db.Exec(`
|
|
||||||
CREATE TABLE IF NOT EXISTS users (
|
|
||||||
id INT PRIMARY KEY AUTO_INCREMENT,
|
|
||||||
name VARCHAR(255) NOT NULL,
|
|
||||||
email VARCHAR(255) UNIQUE NOT NULL,
|
|
||||||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
|
||||||
)
|
|
||||||
`).Error
|
|
||||||
},
|
|
||||||
Down: func(db *gorm.DB) error {
|
|
||||||
return db.Exec("DROP TABLE IF EXISTS users").Error
|
|
||||||
},
|
|
||||||
})
|
|
||||||
|
|
||||||
// 执行迁移
|
|
||||||
if err := migrator.Up(); err != nil {
|
|
||||||
log.Fatal(err)
|
|
||||||
}
|
|
||||||
|
|
||||||
// 查看迁移状态
|
|
||||||
status, err := migrator.Status()
|
|
||||||
if err != nil {
|
|
||||||
log.Fatal(err)
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, s := range status {
|
|
||||||
fmt.Printf("Version: %s, Description: %s, Applied: %v\n",
|
|
||||||
s.Version, s.Description, s.Applied)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@@ -1,105 +0,0 @@
|
|||||||
package main
|
|
||||||
|
|
||||||
import (
|
|
||||||
"fmt"
|
|
||||||
"log"
|
|
||||||
|
|
||||||
"git.toowon.com/jimmy/go-common/migration"
|
|
||||||
"gorm.io/driver/sqlite"
|
|
||||||
"gorm.io/gorm"
|
|
||||||
)
|
|
||||||
|
|
||||||
func main() {
|
|
||||||
// 初始化数据库连接(使用SQLite作为示例)
|
|
||||||
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})
|
|
||||||
if err != nil {
|
|
||||||
log.Fatal("Failed to connect to database:", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
// 创建迁移器
|
|
||||||
migrator := migration.NewMigrator(db)
|
|
||||||
|
|
||||||
// 添加一些迁移
|
|
||||||
migrator.AddMigrations(
|
|
||||||
migration.Migration{
|
|
||||||
Version: "20240101000001",
|
|
||||||
Description: "create_users_table",
|
|
||||||
Up: func(db *gorm.DB) error {
|
|
||||||
return db.Exec(`
|
|
||||||
CREATE TABLE users (
|
|
||||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
||||||
name VARCHAR(255) NOT NULL,
|
|
||||||
email VARCHAR(255) UNIQUE NOT NULL
|
|
||||||
)
|
|
||||||
`).Error
|
|
||||||
},
|
|
||||||
Down: func(db *gorm.DB) error {
|
|
||||||
return db.Exec("DROP TABLE IF EXISTS users").Error
|
|
||||||
},
|
|
||||||
},
|
|
||||||
migration.Migration{
|
|
||||||
Version: "20240101000002",
|
|
||||||
Description: "add_created_at_to_users",
|
|
||||||
Up: func(db *gorm.DB) error {
|
|
||||||
return db.Exec("ALTER TABLE users ADD COLUMN created_at DATETIME").Error
|
|
||||||
},
|
|
||||||
Down: func(db *gorm.DB) error {
|
|
||||||
return db.Exec("ALTER TABLE users DROP COLUMN created_at").Error
|
|
||||||
},
|
|
||||||
},
|
|
||||||
)
|
|
||||||
|
|
||||||
// 执行迁移
|
|
||||||
fmt.Println("=== Executing migrations ===")
|
|
||||||
err = migrator.Up()
|
|
||||||
if err != nil {
|
|
||||||
log.Fatal("Failed to run migrations:", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
// 查看状态
|
|
||||||
fmt.Println("\n=== Migration status ===")
|
|
||||||
status, err := migrator.Status()
|
|
||||||
if err != nil {
|
|
||||||
log.Fatal("Failed to get status:", err)
|
|
||||||
}
|
|
||||||
for _, s := range status {
|
|
||||||
fmt.Printf("Version: %s, Description: %s, Applied: %v\n",
|
|
||||||
s.Version, s.Description, s.Applied)
|
|
||||||
}
|
|
||||||
|
|
||||||
// 示例1:仅清空迁移记录(不回滚数据库变更)
|
|
||||||
fmt.Println("\n=== Example 1: Reset migration records only ===")
|
|
||||||
fmt.Println("Note: This only clears records, not database changes")
|
|
||||||
// 直接调用(需要确认标志)
|
|
||||||
// err = migrator.Reset(true)
|
|
||||||
// if err != nil {
|
|
||||||
// log.Fatal("Failed to reset:", err)
|
|
||||||
// }
|
|
||||||
|
|
||||||
// 交互式确认(推荐)
|
|
||||||
// 取消注释下面的代码来测试交互式重置
|
|
||||||
// err = migrator.ResetWithConfirm()
|
|
||||||
// if err != nil {
|
|
||||||
// log.Fatal("Failed to reset with confirm:", err)
|
|
||||||
// }
|
|
||||||
|
|
||||||
// 示例2:回滚所有迁移并清空记录
|
|
||||||
fmt.Println("\n=== Example 2: Reset all migrations (rollback + clear records) ===")
|
|
||||||
fmt.Println("Note: This will rollback all migrations and clear records")
|
|
||||||
// 直接调用(需要确认标志)
|
|
||||||
// err = migrator.ResetAll(true)
|
|
||||||
// if err != nil {
|
|
||||||
// log.Fatal("Failed to reset all:", err)
|
|
||||||
// }
|
|
||||||
|
|
||||||
// 交互式确认(推荐)
|
|
||||||
// 取消注释下面的代码来测试交互式重置
|
|
||||||
// err = migrator.ResetAllWithConfirm()
|
|
||||||
// if err != nil {
|
|
||||||
// log.Fatal("Failed to reset all with confirm:", err)
|
|
||||||
// }
|
|
||||||
|
|
||||||
fmt.Println("\nNote: Reset functions are commented out for safety.")
|
|
||||||
fmt.Println("Uncomment the code above to test reset functionality.")
|
|
||||||
}
|
|
||||||
|
|
||||||
139
examples/migrations/README.md
Normal file
139
examples/migrations/README.md
Normal file
@@ -0,0 +1,139 @@
|
|||||||
|
# 数据库迁移示例
|
||||||
|
|
||||||
|
这个目录包含了数据库迁移的示例SQL文件。
|
||||||
|
|
||||||
|
## 文件说明
|
||||||
|
|
||||||
|
```
|
||||||
|
examples/migrations/
|
||||||
|
├── migrations/ # 迁移文件目录
|
||||||
|
│ ├── 20240101000001_create_users_table.sql # 迁移SQL
|
||||||
|
│ └── 20240101000001_create_users_table.down.sql # 回滚SQL
|
||||||
|
└── README.md # 本文件
|
||||||
|
```
|
||||||
|
|
||||||
|
## 快速开始
|
||||||
|
|
||||||
|
### 在你的项目中使用
|
||||||
|
|
||||||
|
#### 1. 创建迁移工具
|
||||||
|
|
||||||
|
在项目根目录创建 `migrate.go`:
|
||||||
|
|
||||||
|
```go
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"log"
|
||||||
|
"os"
|
||||||
|
"git.toowon.com/jimmy/go-common/migration"
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
command := "up"
|
||||||
|
if len(os.Args) > 1 {
|
||||||
|
command = os.Args[1]
|
||||||
|
}
|
||||||
|
|
||||||
|
err := migration.RunMigrationsFromConfigWithCommand("config.json", "migrations", command)
|
||||||
|
if err != nil {
|
||||||
|
log.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
#### 2. 创建迁移文件
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 创建目录
|
||||||
|
mkdir -p migrations
|
||||||
|
|
||||||
|
# 创建迁移文件(使用时间戳作为版本号)
|
||||||
|
vim migrations/20240101000001_create_users.sql
|
||||||
|
```
|
||||||
|
|
||||||
|
#### 3. 编写SQL
|
||||||
|
|
||||||
|
```sql
|
||||||
|
-- migrations/20240101000001_create_users.sql
|
||||||
|
CREATE TABLE users (
|
||||||
|
id BIGINT PRIMARY KEY AUTO_INCREMENT,
|
||||||
|
username VARCHAR(255) NOT NULL,
|
||||||
|
email VARCHAR(255) NOT NULL
|
||||||
|
);
|
||||||
|
```
|
||||||
|
|
||||||
|
#### 4. 执行迁移
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 执行迁移
|
||||||
|
go run migrate.go up
|
||||||
|
|
||||||
|
# 查看状态
|
||||||
|
go run migrate.go status
|
||||||
|
|
||||||
|
# 回滚
|
||||||
|
go run migrate.go down
|
||||||
|
```
|
||||||
|
|
||||||
|
### 更简单:在应用启动时自动执行
|
||||||
|
|
||||||
|
在你的 `main.go` 中:
|
||||||
|
|
||||||
|
```go
|
||||||
|
import "git.toowon.com/jimmy/go-common/migration"
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
// 一行代码,启动时自动迁移
|
||||||
|
migration.RunMigrationsFromConfig("config.json", "migrations")
|
||||||
|
|
||||||
|
// 继续启动应用
|
||||||
|
startServer()
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## 配置方式
|
||||||
|
|
||||||
|
### 方式1:配置文件
|
||||||
|
|
||||||
|
`config.json`:
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"database": {
|
||||||
|
"type": "mysql",
|
||||||
|
"host": "localhost",
|
||||||
|
"port": 3306,
|
||||||
|
"user": "root",
|
||||||
|
"password": "password",
|
||||||
|
"database": "mydb"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 方式2:使用配置文件(推荐)
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 使用默认配置文件 config.json
|
||||||
|
go run migrate.go up
|
||||||
|
|
||||||
|
# 或指定配置文件路径
|
||||||
|
go run migrate.go up -config /path/to/config.json
|
||||||
|
```
|
||||||
|
|
||||||
|
**Docker 中**:
|
||||||
|
```yaml
|
||||||
|
# docker-compose.yml
|
||||||
|
services:
|
||||||
|
app:
|
||||||
|
volumes:
|
||||||
|
# 挂载配置文件
|
||||||
|
- ./config.json:/app/config.json:ro
|
||||||
|
command: sh -c "go run migrate.go up && ./app"
|
||||||
|
```
|
||||||
|
|
||||||
|
**注意**:配置文件中的数据库主机应使用服务名(`db`),不是 `localhost`
|
||||||
|
|
||||||
|
## 更多信息
|
||||||
|
|
||||||
|
- [数据库迁移完整指南](../../MIGRATION.md) ⭐
|
||||||
|
- [详细功能文档](../../docs/migration.md)
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
-- Rollback: Drop users table
|
||||||
|
|
||||||
|
DROP TABLE IF EXISTS users;
|
||||||
|
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
-- Create users table
|
||||||
|
-- Created at: 2024-01-01 00:00:01
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS users (
|
||||||
|
id BIGINT PRIMARY KEY AUTO_INCREMENT,
|
||||||
|
username VARCHAR(255) NOT NULL UNIQUE,
|
||||||
|
email VARCHAR(255) NOT NULL UNIQUE,
|
||||||
|
password_hash VARCHAR(255) NOT NULL,
|
||||||
|
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
|
||||||
|
INDEX idx_username (username),
|
||||||
|
INDEX idx_email (email)
|
||||||
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
|
||||||
|
|
||||||
@@ -36,8 +36,20 @@ func main() {
|
|||||||
proxyHandler := storage.NewProxyHandler(ossStorage)
|
proxyHandler := storage.NewProxyHandler(ossStorage)
|
||||||
|
|
||||||
// 创建中间件链
|
// 创建中间件链
|
||||||
|
var corsConfig *middleware.CORSConfig
|
||||||
|
if cfg.GetCORS() != nil {
|
||||||
|
c := cfg.GetCORS()
|
||||||
|
corsConfig = middleware.NewCORSConfig(
|
||||||
|
c.AllowedOrigins,
|
||||||
|
c.AllowedMethods,
|
||||||
|
c.AllowedHeaders,
|
||||||
|
c.ExposedHeaders,
|
||||||
|
c.AllowCredentials,
|
||||||
|
c.MaxAge,
|
||||||
|
)
|
||||||
|
}
|
||||||
chain := middleware.NewChain(
|
chain := middleware.NewChain(
|
||||||
middleware.CORS(cfg.GetCORS()),
|
middleware.CORS(corsConfig),
|
||||||
middleware.Timezone,
|
middleware.Timezone,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|||||||
432
excel/excel.go
Normal file
432
excel/excel.go
Normal file
@@ -0,0 +1,432 @@
|
|||||||
|
package excel
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"reflect"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"git.toowon.com/jimmy/go-common/tools"
|
||||||
|
"github.com/xuri/excelize/v2"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Excel Excel导出器
|
||||||
|
type Excel struct {
|
||||||
|
file *excelize.File
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewExcel 创建Excel导出器
|
||||||
|
func NewExcel() *Excel {
|
||||||
|
return &Excel{
|
||||||
|
file: excelize.NewFile(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ExportColumn 导出列定义
|
||||||
|
type ExportColumn struct {
|
||||||
|
// Header 表头名称
|
||||||
|
Header string
|
||||||
|
// Field 数据字段名(支持嵌套字段,如 "User.Name")
|
||||||
|
Field string
|
||||||
|
// Width 列宽(可选,0表示自动)
|
||||||
|
Width float64
|
||||||
|
// Format 格式化函数(可选,用于自定义字段值的格式化)
|
||||||
|
Format func(value interface{}) string
|
||||||
|
}
|
||||||
|
|
||||||
|
// ExportData 导出数据接口
|
||||||
|
// 实现此接口的结构体可以直接导出
|
||||||
|
type ExportData interface {
|
||||||
|
// GetExportColumns 获取导出列定义
|
||||||
|
GetExportColumns() []ExportColumn
|
||||||
|
// GetExportRows 获取导出数据行
|
||||||
|
GetExportRows() [][]interface{}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ExportToWriter 导出数据到Writer(黑盒模式,推荐使用)
|
||||||
|
// sheetName: 工作表名称(可选,默认为"Sheet1")
|
||||||
|
// columns: 列定义
|
||||||
|
// data: 数据列表(可以是结构体切片或实现了ExportData接口的对象)
|
||||||
|
// 返回错误信息
|
||||||
|
//
|
||||||
|
// 示例1:导出结构体切片
|
||||||
|
//
|
||||||
|
// type User struct {
|
||||||
|
// ID int `json:"id"`
|
||||||
|
// Name string `json:"name"`
|
||||||
|
// Email string `json:"email"`
|
||||||
|
// }
|
||||||
|
//
|
||||||
|
// users := []User{
|
||||||
|
// {ID: 1, Name: "Alice", Email: "alice@example.com"},
|
||||||
|
// {ID: 2, Name: "Bob", Email: "bob@example.com"},
|
||||||
|
// }
|
||||||
|
//
|
||||||
|
// columns := []ExportColumn{
|
||||||
|
// {Header: "ID", Field: "ID"},
|
||||||
|
// {Header: "姓名", Field: "Name"},
|
||||||
|
// {Header: "邮箱", Field: "Email"},
|
||||||
|
// }
|
||||||
|
//
|
||||||
|
// excel := excel.NewExcel()
|
||||||
|
// err := excel.ExportToWriter(w, "用户列表", columns, users)
|
||||||
|
//
|
||||||
|
// 示例2:使用格式化函数
|
||||||
|
//
|
||||||
|
// columns := []ExportColumn{
|
||||||
|
// {Header: "ID", Field: "ID"},
|
||||||
|
// {Header: "姓名", Field: "Name"},
|
||||||
|
// {Header: "创建时间", Field: "CreatedAt", Format: func(v interface{}) string {
|
||||||
|
// if t, ok := v.(time.Time); ok {
|
||||||
|
// return t.Format("2006-01-02 15:04:05")
|
||||||
|
// }
|
||||||
|
// return ""
|
||||||
|
// }},
|
||||||
|
// }
|
||||||
|
//
|
||||||
|
// excel.ExportToWriter(w, "用户列表", columns, users)
|
||||||
|
func (e *Excel) ExportToWriter(w io.Writer, sheetName string, columns []ExportColumn, data interface{}) error {
|
||||||
|
if e.file == nil {
|
||||||
|
e.file = excelize.NewFile()
|
||||||
|
}
|
||||||
|
|
||||||
|
// 设置工作表名称
|
||||||
|
if sheetName == "" {
|
||||||
|
sheetName = "Sheet1"
|
||||||
|
}
|
||||||
|
|
||||||
|
// 检查工作表是否已存在
|
||||||
|
sheetIndex, err := e.file.GetSheetIndex(sheetName)
|
||||||
|
if err != nil || sheetIndex == 0 {
|
||||||
|
// 工作表不存在,需要创建
|
||||||
|
// 如果sheetName不是"Sheet1",且默认"Sheet1"存在,则删除它
|
||||||
|
if sheetName != "Sheet1" {
|
||||||
|
defaultIndex, _ := e.file.GetSheetIndex("Sheet1")
|
||||||
|
if defaultIndex > 0 {
|
||||||
|
e.file.DeleteSheet("Sheet1")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 创建新工作表
|
||||||
|
_, err = e.file.NewSheet(sheetName)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("failed to create sheet: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// 重新获取工作表索引
|
||||||
|
sheetIndex, err = e.file.GetSheetIndex(sheetName)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("failed to get sheet index: %w", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 设置活动工作表
|
||||||
|
if sheetIndex > 0 {
|
||||||
|
e.file.SetActiveSheet(sheetIndex)
|
||||||
|
}
|
||||||
|
|
||||||
|
// 写入表头
|
||||||
|
headerStyle, _ := e.file.NewStyle(&excelize.Style{
|
||||||
|
Font: &excelize.Font{
|
||||||
|
Bold: true,
|
||||||
|
Size: 12,
|
||||||
|
},
|
||||||
|
Fill: excelize.Fill{
|
||||||
|
Type: "pattern",
|
||||||
|
Color: []string{"#E0E0E0"},
|
||||||
|
Pattern: 1,
|
||||||
|
},
|
||||||
|
Alignment: &excelize.Alignment{
|
||||||
|
Horizontal: "center",
|
||||||
|
Vertical: "center",
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
for i, col := range columns {
|
||||||
|
cell := fmt.Sprintf("%c1", 'A'+i)
|
||||||
|
e.file.SetCellValue(sheetName, cell, col.Header)
|
||||||
|
|
||||||
|
// 设置表头样式
|
||||||
|
e.file.SetCellStyle(sheetName, cell, cell, headerStyle)
|
||||||
|
|
||||||
|
// 设置列宽
|
||||||
|
if col.Width > 0 {
|
||||||
|
colName, _ := excelize.ColumnNumberToName(i + 1)
|
||||||
|
e.file.SetColWidth(sheetName, colName, colName, col.Width)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 处理数据
|
||||||
|
var rows [][]interface{}
|
||||||
|
|
||||||
|
// 检查数据是否实现了ExportData接口
|
||||||
|
if exportData, ok := data.(ExportData); ok {
|
||||||
|
// 使用接口方法获取数据
|
||||||
|
rows = exportData.GetExportRows()
|
||||||
|
// 如果接口返回nil,初始化为空切片
|
||||||
|
if rows == nil {
|
||||||
|
rows = [][]interface{}{}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// 处理结构体切片(包括nil和空切片的情况)
|
||||||
|
rows, err = e.convertDataToRows(data, columns)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("failed to convert data to rows: %w", err)
|
||||||
|
}
|
||||||
|
// 确保rows不为nil
|
||||||
|
if rows == nil {
|
||||||
|
rows = [][]interface{}{}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 写入数据行
|
||||||
|
for rowIndex, row := range rows {
|
||||||
|
for colIndex, value := range row {
|
||||||
|
cell := fmt.Sprintf("%c%d", 'A'+colIndex, rowIndex+2) // +2 因为第一行是表头
|
||||||
|
|
||||||
|
// 应用格式化函数
|
||||||
|
var cellValue interface{} = value
|
||||||
|
if colIndex < len(columns) && columns[colIndex].Format != nil {
|
||||||
|
cellValue = columns[colIndex].Format(value)
|
||||||
|
}
|
||||||
|
|
||||||
|
e.file.SetCellValue(sheetName, cell, cellValue)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 自动调整列宽(如果未设置宽度)
|
||||||
|
for i, col := range columns {
|
||||||
|
if col.Width == 0 {
|
||||||
|
colName, _ := excelize.ColumnNumberToName(i + 1)
|
||||||
|
// 获取列的最大宽度
|
||||||
|
maxWidth := e.getColumnMaxWidth(sheetName, i+1, len(rows)+1)
|
||||||
|
if maxWidth > 0 {
|
||||||
|
e.file.SetColWidth(sheetName, colName, colName, maxWidth)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 写入到Writer
|
||||||
|
return e.file.Write(w)
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetFile 获取Excel文件对象(高级功能时使用)
|
||||||
|
// 返回excelize.File对象,可用于高级操作
|
||||||
|
//
|
||||||
|
// ℹ️ 推荐使用黑盒方法:
|
||||||
|
// - ExportToWriter():导出到Writer(可用于文件、HTTP响应等)
|
||||||
|
//
|
||||||
|
// 仅在需要使用高级功能时获取对象:
|
||||||
|
// - 多工作表操作
|
||||||
|
// - 自定义样式
|
||||||
|
// - 图表、公式等高级功能
|
||||||
|
//
|
||||||
|
// 示例(常用操作,推荐):
|
||||||
|
//
|
||||||
|
// excel := excel.NewExcel()
|
||||||
|
// file, _ := os.Create("users.xlsx")
|
||||||
|
// defer file.Close()
|
||||||
|
// excel.ExportToWriter(file, "用户列表", columns, users)
|
||||||
|
//
|
||||||
|
// 示例(高级功能):
|
||||||
|
//
|
||||||
|
// file := excel.GetFile()
|
||||||
|
// file.NewSheet("Sheet2")
|
||||||
|
// file.SetCellValue("Sheet2", "A1", "数据")
|
||||||
|
func (e *Excel) GetFile() *excelize.File {
|
||||||
|
if e.file == nil {
|
||||||
|
e.file = excelize.NewFile()
|
||||||
|
}
|
||||||
|
return e.file
|
||||||
|
}
|
||||||
|
|
||||||
|
// convertDataToRows 将数据转换为行数据
|
||||||
|
// 支持nil、空切片等情况,返回空切片而不是错误
|
||||||
|
func (e *Excel) convertDataToRows(data interface{}, columns []ExportColumn) ([][]interface{}, error) {
|
||||||
|
// 如果data为nil,返回空切片
|
||||||
|
if data == nil {
|
||||||
|
return [][]interface{}{}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// 使用反射处理数据
|
||||||
|
val := reflect.ValueOf(data)
|
||||||
|
if val.Kind() == reflect.Ptr {
|
||||||
|
// 如果是指针且指向nil,返回空切片
|
||||||
|
if val.IsNil() {
|
||||||
|
return [][]interface{}{}, nil
|
||||||
|
}
|
||||||
|
val = val.Elem()
|
||||||
|
}
|
||||||
|
|
||||||
|
// 如果解引用后仍然是无效值,返回空切片
|
||||||
|
if !val.IsValid() {
|
||||||
|
return [][]interface{}{}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// 必须是切片类型
|
||||||
|
if val.Kind() != reflect.Slice {
|
||||||
|
return nil, fmt.Errorf("data must be a slice, got %v", val.Kind())
|
||||||
|
}
|
||||||
|
|
||||||
|
// 如果是空切片,返回空切片(不返回错误)
|
||||||
|
if val.Len() == 0 {
|
||||||
|
return [][]interface{}{}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
rows := make([][]interface{}, 0, val.Len())
|
||||||
|
|
||||||
|
for i := 0; i < val.Len(); i++ {
|
||||||
|
item := val.Index(i)
|
||||||
|
if item.Kind() == reflect.Ptr {
|
||||||
|
// 如果指针指向nil,跳过该行或使用空值
|
||||||
|
if item.IsNil() {
|
||||||
|
row := make([]interface{}, len(columns))
|
||||||
|
rows = append(rows, row)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
item = item.Elem()
|
||||||
|
}
|
||||||
|
|
||||||
|
row := make([]interface{}, len(columns))
|
||||||
|
for j, col := range columns {
|
||||||
|
value := e.getFieldValue(item, col.Field)
|
||||||
|
row[j] = value
|
||||||
|
}
|
||||||
|
rows = append(rows, row)
|
||||||
|
}
|
||||||
|
|
||||||
|
return rows, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// getFieldValue 获取字段值(支持嵌套字段)
|
||||||
|
func (e *Excel) getFieldValue(v reflect.Value, fieldPath string) interface{} {
|
||||||
|
if v.Kind() == reflect.Ptr {
|
||||||
|
v = v.Elem()
|
||||||
|
}
|
||||||
|
|
||||||
|
if v.Kind() != reflect.Struct {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// 处理嵌套字段(如 "User.Name")
|
||||||
|
fields := splitFieldPath(fieldPath)
|
||||||
|
current := v
|
||||||
|
|
||||||
|
for i, fieldName := range fields {
|
||||||
|
if current.Kind() == reflect.Ptr {
|
||||||
|
current = current.Elem()
|
||||||
|
}
|
||||||
|
|
||||||
|
if current.Kind() != reflect.Struct {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
field := current.FieldByName(fieldName)
|
||||||
|
if !field.IsValid() {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// 如果是最后一个字段,返回值
|
||||||
|
if i == len(fields)-1 {
|
||||||
|
if field.CanInterface() {
|
||||||
|
return field.Interface()
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// 继续嵌套查找
|
||||||
|
current = field
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// splitFieldPath 分割字段路径(如 "User.Name" -> ["User", "Name"])
|
||||||
|
func splitFieldPath(path string) []string {
|
||||||
|
result := make([]string, 0)
|
||||||
|
current := ""
|
||||||
|
for _, char := range path {
|
||||||
|
if char == '.' {
|
||||||
|
if current != "" {
|
||||||
|
result = append(result, current)
|
||||||
|
current = ""
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
current += string(char)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if current != "" {
|
||||||
|
result = append(result, current)
|
||||||
|
}
|
||||||
|
return result
|
||||||
|
}
|
||||||
|
|
||||||
|
// getColumnMaxWidth 获取列的最大宽度(用于自动调整列宽)
|
||||||
|
func (e *Excel) getColumnMaxWidth(sheetName string, colIndex int, maxRow int) float64 {
|
||||||
|
maxWidth := 10.0 // 默认最小宽度
|
||||||
|
|
||||||
|
for row := 1; row <= maxRow; row++ {
|
||||||
|
cell, _ := excelize.CoordinatesToCellName(colIndex, row)
|
||||||
|
value, err := e.file.GetCellValue(sheetName, cell)
|
||||||
|
if err == nil {
|
||||||
|
width := float64(len(value)) + 2 // 加2作为边距
|
||||||
|
if width > maxWidth {
|
||||||
|
maxWidth = width
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 限制最大宽度
|
||||||
|
if maxWidth > 50 {
|
||||||
|
maxWidth = 50
|
||||||
|
}
|
||||||
|
|
||||||
|
return maxWidth
|
||||||
|
}
|
||||||
|
|
||||||
|
// AdaptTimeFormatter 适配器函数:将tools包的格式化函数转换为Excel Format字段需要的函数类型
|
||||||
|
// 允许直接使用tools包的任何格式化函数
|
||||||
|
//
|
||||||
|
// 示例:
|
||||||
|
//
|
||||||
|
// // 直接使用tools.FormatDate
|
||||||
|
// Format: excel.AdaptTimeFormatter(tools.FormatDate)
|
||||||
|
//
|
||||||
|
// // 使用自定义格式化函数
|
||||||
|
// Format: excel.AdaptTimeFormatter(func(t time.Time) string {
|
||||||
|
// return tools.Format(t, "2006-01-02 15:04:05", "Asia/Shanghai")
|
||||||
|
// })
|
||||||
|
func AdaptTimeFormatter(fn func(time.Time, ...string) string) func(interface{}) string {
|
||||||
|
return func(value interface{}) string {
|
||||||
|
if t, ok := value.(time.Time); ok {
|
||||||
|
return fn(t)
|
||||||
|
}
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// formatDateTime 格式化日期时间(内部便捷函数)
|
||||||
|
// 用于ExportColumn的Format字段
|
||||||
|
// layout: 时间格式,如 "2006-01-02 15:04:05"
|
||||||
|
// timezone: 可选时区,如果为空则使用时间对象本身的时区
|
||||||
|
// 直接调用 tools.Format() 方法
|
||||||
|
func formatDateTime(layout string, timezone ...string) func(interface{}) string {
|
||||||
|
return AdaptTimeFormatter(func(t time.Time, _ ...string) string {
|
||||||
|
return tools.Format(t, layout, timezone...)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// formatDate 格式化日期(内部便捷函数)
|
||||||
|
// 用于ExportColumn的Format字段,格式:2006-01-02
|
||||||
|
// 直接调用 tools.FormatDate() 方法
|
||||||
|
var formatDate = AdaptTimeFormatter(tools.FormatDate)
|
||||||
|
|
||||||
|
// formatDateTimeDefault 格式化日期时间(内部便捷函数)
|
||||||
|
// 用于ExportColumn的Format字段,格式:2006-01-02 15:04:05
|
||||||
|
// 直接调用 tools.FormatDateTime() 方法
|
||||||
|
var formatDateTimeDefault = AdaptTimeFormatter(tools.FormatDateTime)
|
||||||
|
|
||||||
|
// formatTime 格式化时间(内部便捷函数)
|
||||||
|
// 用于ExportColumn的Format字段,格式:15:04:05
|
||||||
|
// 直接调用 tools.FormatTime() 方法
|
||||||
|
var formatTime = AdaptTimeFormatter(tools.FormatTime)
|
||||||
1223
factory/factory.go
1223
factory/factory.go
File diff suppressed because it is too large
Load Diff
18
go.mod
18
go.mod
@@ -1,12 +1,14 @@
|
|||||||
module git.toowon.com/jimmy/go-common
|
module git.toowon.com/jimmy/go-common
|
||||||
|
|
||||||
go 1.23.0
|
go 1.24.0
|
||||||
|
|
||||||
toolchain go1.24.10
|
toolchain go1.24.10
|
||||||
|
|
||||||
require (
|
require (
|
||||||
github.com/minio/minio-go/v7 v7.0.97
|
github.com/minio/minio-go/v7 v7.0.97
|
||||||
github.com/redis/go-redis/v9 v9.17.1
|
github.com/redis/go-redis/v9 v9.17.1
|
||||||
|
github.com/xuri/excelize/v2 v2.10.0
|
||||||
|
golang.org/x/crypto v0.43.0
|
||||||
gorm.io/driver/mysql v1.5.2
|
gorm.io/driver/mysql v1.5.2
|
||||||
gorm.io/driver/postgres v1.6.0
|
gorm.io/driver/postgres v1.6.0
|
||||||
gorm.io/driver/sqlite v1.6.0
|
gorm.io/driver/sqlite v1.6.0
|
||||||
@@ -34,13 +36,17 @@ require (
|
|||||||
github.com/minio/crc64nvme v1.1.0 // indirect
|
github.com/minio/crc64nvme v1.1.0 // indirect
|
||||||
github.com/minio/md5-simd v1.1.2 // indirect
|
github.com/minio/md5-simd v1.1.2 // indirect
|
||||||
github.com/philhofer/fwd v1.2.0 // indirect
|
github.com/philhofer/fwd v1.2.0 // indirect
|
||||||
|
github.com/richardlehane/mscfb v1.0.4 // indirect
|
||||||
|
github.com/richardlehane/msoleps v1.0.4 // indirect
|
||||||
github.com/rogpeppe/go-internal v1.14.1 // indirect
|
github.com/rogpeppe/go-internal v1.14.1 // indirect
|
||||||
github.com/rs/xid v1.6.0 // indirect
|
github.com/rs/xid v1.6.0 // indirect
|
||||||
|
github.com/tiendc/go-deepcopy v1.7.1 // indirect
|
||||||
github.com/tinylib/msgp v1.3.0 // indirect
|
github.com/tinylib/msgp v1.3.0 // indirect
|
||||||
golang.org/x/crypto v0.36.0 // indirect
|
github.com/xuri/efp v0.0.1 // indirect
|
||||||
golang.org/x/net v0.38.0 // indirect
|
github.com/xuri/nfp v0.0.2-0.20250530014748-2ddeb826f9a9 // indirect
|
||||||
golang.org/x/sync v0.15.0 // indirect
|
golang.org/x/net v0.46.0 // indirect
|
||||||
golang.org/x/sys v0.34.0 // indirect
|
golang.org/x/sync v0.17.0 // indirect
|
||||||
golang.org/x/text v0.26.0 // indirect
|
golang.org/x/sys v0.37.0 // indirect
|
||||||
|
golang.org/x/text v0.30.0 // indirect
|
||||||
gopkg.in/yaml.v3 v3.0.1 // indirect
|
gopkg.in/yaml.v3 v3.0.1 // indirect
|
||||||
)
|
)
|
||||||
|
|||||||
39
go.sum
39
go.sum
@@ -56,6 +56,11 @@ github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZb
|
|||||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||||
github.com/redis/go-redis/v9 v9.17.1 h1:7tl732FjYPRT9H9aNfyTwKg9iTETjWjGKEJ2t/5iWTs=
|
github.com/redis/go-redis/v9 v9.17.1 h1:7tl732FjYPRT9H9aNfyTwKg9iTETjWjGKEJ2t/5iWTs=
|
||||||
github.com/redis/go-redis/v9 v9.17.1/go.mod h1:u410H11HMLoB+TP67dz8rL9s6QW2j76l0//kSOd3370=
|
github.com/redis/go-redis/v9 v9.17.1/go.mod h1:u410H11HMLoB+TP67dz8rL9s6QW2j76l0//kSOd3370=
|
||||||
|
github.com/richardlehane/mscfb v1.0.4 h1:WULscsljNPConisD5hR0+OyZjwK46Pfyr6mPu5ZawpM=
|
||||||
|
github.com/richardlehane/mscfb v1.0.4/go.mod h1:YzVpcZg9czvAuhk9T+a3avCpcFPMUWm7gK3DypaEsUk=
|
||||||
|
github.com/richardlehane/msoleps v1.0.1/go.mod h1:BWev5JBpU9Ko2WAgmZEuiz4/u3ZYTKbjLycmwiWUfWg=
|
||||||
|
github.com/richardlehane/msoleps v1.0.4 h1:WuESlvhX3gH2IHcd8UqyCuFY5yiq/GR/yqaSM/9/g00=
|
||||||
|
github.com/richardlehane/msoleps v1.0.4/go.mod h1:BWev5JBpU9Ko2WAgmZEuiz4/u3ZYTKbjLycmwiWUfWg=
|
||||||
github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ=
|
github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ=
|
||||||
github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc=
|
github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc=
|
||||||
github.com/rs/xid v1.6.0 h1:fV591PaemRlL6JfRxGDEPl69wICngIQ3shQtzfy2gxU=
|
github.com/rs/xid v1.6.0 h1:fV591PaemRlL6JfRxGDEPl69wICngIQ3shQtzfy2gxU=
|
||||||
@@ -63,20 +68,30 @@ github.com/rs/xid v1.6.0/go.mod h1:7XoLgs4eV+QndskICGsho+ADou8ySMSjJKDIan90Nz0=
|
|||||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||||
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
|
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
|
||||||
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||||
github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg=
|
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
|
||||||
github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
|
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
|
||||||
|
github.com/tiendc/go-deepcopy v1.7.1 h1:LnubftI6nYaaMOcaz0LphzwraqN8jiWTwm416sitff4=
|
||||||
|
github.com/tiendc/go-deepcopy v1.7.1/go.mod h1:4bKjNC2r7boYOkD2IOuZpYjmlDdzjbpTRyCx+goBCJQ=
|
||||||
github.com/tinylib/msgp v1.3.0 h1:ULuf7GPooDaIlbyvgAxBV/FI7ynli6LZ1/nVUNu+0ww=
|
github.com/tinylib/msgp v1.3.0 h1:ULuf7GPooDaIlbyvgAxBV/FI7ynli6LZ1/nVUNu+0ww=
|
||||||
github.com/tinylib/msgp v1.3.0/go.mod h1:ykjzy2wzgrlvpDCRc4LA8UXy6D8bzMSuAF3WD57Gok0=
|
github.com/tinylib/msgp v1.3.0/go.mod h1:ykjzy2wzgrlvpDCRc4LA8UXy6D8bzMSuAF3WD57Gok0=
|
||||||
golang.org/x/crypto v0.36.0 h1:AnAEvhDddvBdpY+uR+MyHmuZzzNqXSe/GvuDeob5L34=
|
github.com/xuri/efp v0.0.1 h1:fws5Rv3myXyYni8uwj2qKjVaRP30PdjeYe2Y6FDsCL8=
|
||||||
golang.org/x/crypto v0.36.0/go.mod h1:Y4J0ReaxCR1IMaabaSMugxJES1EpwhBHhv2bDHklZvc=
|
github.com/xuri/efp v0.0.1/go.mod h1:ybY/Jr0T0GTCnYjKqmdwxyxn2BQf2RcQIIvex5QldPI=
|
||||||
golang.org/x/net v0.38.0 h1:vRMAPTMaeGqVhG5QyLJHqNDwecKTomGeqbnfZyKlBI8=
|
github.com/xuri/excelize/v2 v2.10.0 h1:8aKsP7JD39iKLc6dH5Tw3dgV3sPRh8uRVXu/fMstfW4=
|
||||||
golang.org/x/net v0.38.0/go.mod h1:ivrbrMbzFq5J41QOQh0siUuly180yBYtLp+CKbEaFx8=
|
github.com/xuri/excelize/v2 v2.10.0/go.mod h1:SC5TzhQkaOsTWpANfm+7bJCldzcnU/jrhqkTi/iBHBU=
|
||||||
golang.org/x/sync v0.15.0 h1:KWH3jNZsfyT6xfAfKiz6MRNmd46ByHDYaZ7KSkCtdW8=
|
github.com/xuri/nfp v0.0.2-0.20250530014748-2ddeb826f9a9 h1:+C0TIdyyYmzadGaL/HBLbf3WdLgC29pgyhTjAT/0nuE=
|
||||||
golang.org/x/sync v0.15.0/go.mod h1:1dzgHSNfp02xaA81J2MS99Qcpr2w7fw1gpm99rleRqA=
|
github.com/xuri/nfp v0.0.2-0.20250530014748-2ddeb826f9a9/go.mod h1:WwHg+CVyzlv/TX9xqBFXEZAuxOPxn2k1GNHwG41IIUQ=
|
||||||
golang.org/x/sys v0.34.0 h1:H5Y5sJ2L2JRdyv7ROF1he/lPdvFsd0mJHFw2ThKHxLA=
|
golang.org/x/crypto v0.43.0 h1:dduJYIi3A3KOfdGOHX8AVZ/jGiyPa3IbBozJ5kNuE04=
|
||||||
golang.org/x/sys v0.34.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=
|
golang.org/x/crypto v0.43.0/go.mod h1:BFbav4mRNlXJL4wNeejLpWxB7wMbc79PdRGhWKncxR0=
|
||||||
golang.org/x/text v0.26.0 h1:P42AVeLghgTYr4+xUnTRKDMqpar+PtX7KWuNQL21L8M=
|
golang.org/x/image v0.25.0 h1:Y6uW6rH1y5y/LK1J8BPWZtr6yZ7hrsy6hFrXjgsc2fQ=
|
||||||
golang.org/x/text v0.26.0/go.mod h1:QK15LZJUUQVJxhz7wXgxSy/CJaTFjd0G+YLonydOVQA=
|
golang.org/x/image v0.25.0/go.mod h1:tCAmOEGthTtkalusGp1g3xa2gke8J6c2N565dTyl9Rs=
|
||||||
|
golang.org/x/net v0.46.0 h1:giFlY12I07fugqwPuWJi68oOnpfqFnJIJzaIIm2JVV4=
|
||||||
|
golang.org/x/net v0.46.0/go.mod h1:Q9BGdFy1y4nkUwiLvT5qtyhAnEHgnQ/zd8PfU6nc210=
|
||||||
|
golang.org/x/sync v0.17.0 h1:l60nONMj9l5drqw6jlhIELNv9I0A4OFgRsG9k2oT9Ug=
|
||||||
|
golang.org/x/sync v0.17.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI=
|
||||||
|
golang.org/x/sys v0.37.0 h1:fdNQudmxPjkdUTPnLn5mdQv7Zwvbvpaxqs831goi9kQ=
|
||||||
|
golang.org/x/sys v0.37.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
|
||||||
|
golang.org/x/text v0.30.0 h1:yznKA/E9zq54KzlzBEAWn1NXSQ8DIp/NYMy88xJjl4k=
|
||||||
|
golang.org/x/text v0.30.0/go.mod h1:yDdHFIX9t+tORqspjENWgzaCVXgk0yYnYuSZ8UzzBVM=
|
||||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||||
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
|
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
|
||||||
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=
|
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=
|
||||||
|
|||||||
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)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
106
http/request.go
106
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)
|
||||||
|
}
|
||||||
104
logger/logger.go
104
logger/logger.go
@@ -11,6 +11,23 @@ import (
|
|||||||
"git.toowon.com/jimmy/go-common/config"
|
"git.toowon.com/jimmy/go-common/config"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
// defaultLogger 全局默认日志记录器
|
||||||
|
// 用于中间件和其他需要快速日志记录的场景
|
||||||
|
defaultLogger *Logger
|
||||||
|
defaultMux sync.RWMutex
|
||||||
|
)
|
||||||
|
|
||||||
|
func init() {
|
||||||
|
// 初始化默认logger(同步模式,输出到stdout)
|
||||||
|
var err error
|
||||||
|
defaultLogger, err = NewLogger(nil)
|
||||||
|
if err != nil {
|
||||||
|
// 如果初始化失败,使用nil,后续会降级到标准输出
|
||||||
|
defaultLogger = nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// logMessage 异步日志消息结构
|
// logMessage 异步日志消息结构
|
||||||
type logMessage struct {
|
type logMessage struct {
|
||||||
level string // debug, info, warn, error
|
level string // debug, info, warn, error
|
||||||
@@ -357,3 +374,90 @@ func (l *Logger) Close() error {
|
|||||||
|
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ========== 全局默认Logger相关方法 ==========
|
||||||
|
|
||||||
|
// SetDefaultLogger 设置全局默认logger
|
||||||
|
// 用于在应用启动时统一配置logger
|
||||||
|
func SetDefaultLogger(log *Logger) {
|
||||||
|
defaultMux.Lock()
|
||||||
|
defer defaultMux.Unlock()
|
||||||
|
|
||||||
|
// 如果之前有logger,先关闭它
|
||||||
|
if defaultLogger != nil {
|
||||||
|
defaultLogger.Close()
|
||||||
|
}
|
||||||
|
|
||||||
|
defaultLogger = log
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetDefaultLogger 获取全局默认logger
|
||||||
|
func GetDefaultLogger() *Logger {
|
||||||
|
defaultMux.RLock()
|
||||||
|
defer defaultMux.RUnlock()
|
||||||
|
return defaultLogger
|
||||||
|
}
|
||||||
|
|
||||||
|
// Default 全局日志方法 - Debug
|
||||||
|
func Default() *Logger {
|
||||||
|
return GetDefaultLogger()
|
||||||
|
}
|
||||||
|
|
||||||
|
// ========== 全局便捷日志方法 ==========
|
||||||
|
// 以下方法使用全局默认logger,方便快速记录日志
|
||||||
|
|
||||||
|
// Debug 使用全局logger记录调试日志
|
||||||
|
func Debug(format string, v ...interface{}) {
|
||||||
|
if log := GetDefaultLogger(); log != nil {
|
||||||
|
log.Debug(format, v...)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Info 使用全局logger记录信息日志
|
||||||
|
func Info(format string, v ...interface{}) {
|
||||||
|
if log := GetDefaultLogger(); log != nil {
|
||||||
|
log.Info(format, v...)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Warn 使用全局logger记录警告日志
|
||||||
|
func Warn(format string, v ...interface{}) {
|
||||||
|
if log := GetDefaultLogger(); log != nil {
|
||||||
|
log.Warn(format, v...)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Error 使用全局logger记录错误日志
|
||||||
|
func Error(format string, v ...interface{}) {
|
||||||
|
if log := GetDefaultLogger(); log != nil {
|
||||||
|
log.Error(format, v...)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Debugf 使用全局logger记录调试日志(带字段)
|
||||||
|
func Debugf(fields map[string]interface{}, format string, v ...interface{}) {
|
||||||
|
if log := GetDefaultLogger(); log != nil {
|
||||||
|
log.Debugf(fields, format, v...)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Infof 使用全局logger记录信息日志(带字段)
|
||||||
|
func Infof(fields map[string]interface{}, format string, v ...interface{}) {
|
||||||
|
if log := GetDefaultLogger(); log != nil {
|
||||||
|
log.Infof(fields, format, v...)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Warnf 使用全局logger记录警告日志(带字段)
|
||||||
|
func Warnf(fields map[string]interface{}, format string, v ...interface{}) {
|
||||||
|
if log := GetDefaultLogger(); log != nil {
|
||||||
|
log.Warnf(fields, format, v...)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Errorf 使用全局logger记录错误日志(带字段)
|
||||||
|
func Errorf(fields map[string]interface{}, format string, v ...interface{}) {
|
||||||
|
if log := GetDefaultLogger(); log != nil {
|
||||||
|
log.Errorf(fields, format, v...)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -43,6 +43,36 @@ func DefaultCORSConfig() *CORSConfig {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// NewCORSConfig 从配置参数创建 CORSConfig
|
||||||
|
// 用于从 config 包的 CORSConfig 转换为 middleware 的 CORSConfig
|
||||||
|
// 避免循环依赖
|
||||||
|
func NewCORSConfig(allowedOrigins, allowedMethods, allowedHeaders, exposedHeaders []string, allowCredentials bool, maxAge int) *CORSConfig {
|
||||||
|
cfg := &CORSConfig{
|
||||||
|
AllowedOrigins: allowedOrigins,
|
||||||
|
AllowedMethods: allowedMethods,
|
||||||
|
AllowedHeaders: allowedHeaders,
|
||||||
|
ExposedHeaders: exposedHeaders,
|
||||||
|
AllowCredentials: allowCredentials,
|
||||||
|
MaxAge: maxAge,
|
||||||
|
}
|
||||||
|
|
||||||
|
// 设置默认值(如果为空)
|
||||||
|
if len(cfg.AllowedOrigins) == 0 {
|
||||||
|
cfg.AllowedOrigins = []string{"*"}
|
||||||
|
}
|
||||||
|
if len(cfg.AllowedMethods) == 0 {
|
||||||
|
cfg.AllowedMethods = []string{"GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS"}
|
||||||
|
}
|
||||||
|
if len(cfg.AllowedHeaders) == 0 {
|
||||||
|
cfg.AllowedHeaders = []string{"Content-Type", "Authorization", "X-Requested-With", "X-Timezone"}
|
||||||
|
}
|
||||||
|
if cfg.MaxAge == 0 {
|
||||||
|
cfg.MaxAge = 86400
|
||||||
|
}
|
||||||
|
|
||||||
|
return cfg
|
||||||
|
}
|
||||||
|
|
||||||
// CORS CORS中间件
|
// CORS CORS中间件
|
||||||
func CORS(config ...*CORSConfig) func(http.Handler) http.Handler {
|
func CORS(config ...*CORSConfig) func(http.Handler) http.Handler {
|
||||||
var cfg *CORSConfig
|
var cfg *CORSConfig
|
||||||
|
|||||||
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
|
||||||
|
}
|
||||||
221
middleware/logging.go
Normal file
221
middleware/logging.go
Normal file
@@ -0,0 +1,221 @@
|
|||||||
|
package middleware
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
"strconv"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"git.toowon.com/jimmy/go-common/logger"
|
||||||
|
)
|
||||||
|
|
||||||
|
// responseWriter 包装 http.ResponseWriter 以捕获状态码和响应大小
|
||||||
|
type responseWriter struct {
|
||||||
|
http.ResponseWriter
|
||||||
|
statusCode int
|
||||||
|
size int
|
||||||
|
}
|
||||||
|
|
||||||
|
func (rw *responseWriter) WriteHeader(statusCode int) {
|
||||||
|
rw.statusCode = statusCode
|
||||||
|
rw.ResponseWriter.WriteHeader(statusCode)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (rw *responseWriter) Write(b []byte) (int, error) {
|
||||||
|
size, err := rw.ResponseWriter.Write(b)
|
||||||
|
rw.size += size
|
||||||
|
return size, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// LoggingConfig 日志中间件配置
|
||||||
|
type LoggingConfig struct {
|
||||||
|
// Logger 日志记录器(可选,如果为nil则使用默认logger)
|
||||||
|
Logger *logger.Logger
|
||||||
|
|
||||||
|
// SkipPaths 跳过记录的路径列表(如健康检查接口)
|
||||||
|
SkipPaths []string
|
||||||
|
|
||||||
|
// LogRequestBody 是否记录请求体(谨慎使用,可能影响性能)
|
||||||
|
LogRequestBody bool
|
||||||
|
|
||||||
|
// LogResponseBody 是否记录响应体(谨慎使用,可能影响性能和内存)
|
||||||
|
LogResponseBody bool
|
||||||
|
}
|
||||||
|
|
||||||
|
// Logging HTTP请求日志中间件
|
||||||
|
// 记录每个HTTP请求的详细信息,包括:
|
||||||
|
// - 请求方法、路径、IP、User-Agent
|
||||||
|
// - 响应状态码、响应大小
|
||||||
|
// - 请求处理时间
|
||||||
|
//
|
||||||
|
// 使用方式1:使用默认logger
|
||||||
|
//
|
||||||
|
// chain := middleware.NewChain(
|
||||||
|
// middleware.Logging(nil),
|
||||||
|
// )
|
||||||
|
//
|
||||||
|
// 使用方式2:使用自定义logger
|
||||||
|
//
|
||||||
|
// myLogger, _ := logger.NewLogger(loggerConfig)
|
||||||
|
// chain := middleware.NewChain(
|
||||||
|
// middleware.Logging(&middleware.LoggingConfig{
|
||||||
|
// Logger: myLogger,
|
||||||
|
// SkipPaths: []string{"/health", "/metrics"},
|
||||||
|
// }),
|
||||||
|
// )
|
||||||
|
func Logging(config *LoggingConfig) func(http.Handler) http.Handler {
|
||||||
|
// 如果没有配置,使用默认配置
|
||||||
|
if config == nil {
|
||||||
|
config = &LoggingConfig{}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 如果没有提供logger,创建一个默认的
|
||||||
|
if config.Logger == nil {
|
||||||
|
// 使用默认配置创建logger(输出到stdout,info级别)
|
||||||
|
defaultLogger, err := logger.NewLogger(nil)
|
||||||
|
if err != nil {
|
||||||
|
// 如果创建失败,使用nil,后面会降级处理
|
||||||
|
config.Logger = nil
|
||||||
|
} else {
|
||||||
|
config.Logger = defaultLogger
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return func(next http.Handler) http.Handler {
|
||||||
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
// 检查是否跳过此路径
|
||||||
|
if shouldSkipPath(r.URL.Path, config.SkipPaths) {
|
||||||
|
next.ServeHTTP(w, r)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// 记录开始时间
|
||||||
|
startTime := time.Now()
|
||||||
|
|
||||||
|
// 包装 ResponseWriter 以捕获状态码和响应大小
|
||||||
|
rw := &responseWriter{
|
||||||
|
ResponseWriter: w,
|
||||||
|
statusCode: http.StatusOK, // 默认200
|
||||||
|
size: 0,
|
||||||
|
}
|
||||||
|
|
||||||
|
// 处理请求
|
||||||
|
next.ServeHTTP(rw, r)
|
||||||
|
|
||||||
|
// 计算处理时间
|
||||||
|
duration := time.Since(startTime)
|
||||||
|
|
||||||
|
// 记录日志
|
||||||
|
logHTTPRequest(config.Logger, r, rw, duration)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// shouldSkipPath 检查是否应该跳过该路径
|
||||||
|
func shouldSkipPath(path string, skipPaths []string) bool {
|
||||||
|
for _, skipPath := range skipPaths {
|
||||||
|
if path == skipPath {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
// logHTTPRequest 记录HTTP请求日志
|
||||||
|
func logHTTPRequest(log *logger.Logger, r *http.Request, rw *responseWriter, duration time.Duration) {
|
||||||
|
// 获取客户端IP
|
||||||
|
clientIP := GetClientIP(r)
|
||||||
|
|
||||||
|
// 构建日志字段
|
||||||
|
fields := map[string]interface{}{
|
||||||
|
"method": r.Method,
|
||||||
|
"path": r.URL.Path,
|
||||||
|
"query": r.URL.RawQuery,
|
||||||
|
"status": rw.statusCode,
|
||||||
|
"size": rw.size,
|
||||||
|
"duration": duration.Milliseconds(), // 毫秒
|
||||||
|
"ip": clientIP,
|
||||||
|
"user_agent": r.UserAgent(),
|
||||||
|
"referer": r.Referer(),
|
||||||
|
}
|
||||||
|
|
||||||
|
// 构建日志消息
|
||||||
|
message := "HTTP Request"
|
||||||
|
|
||||||
|
// 根据状态码选择日志级别
|
||||||
|
if log != nil {
|
||||||
|
// 使用提供的logger
|
||||||
|
if rw.statusCode >= 500 {
|
||||||
|
log.Errorf(fields, message)
|
||||||
|
} else if rw.statusCode >= 400 {
|
||||||
|
log.Warnf(fields, message)
|
||||||
|
} else {
|
||||||
|
log.Infof(fields, message)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// 降级处理:使用标准输出
|
||||||
|
// 注意:这是同步的,不会有性能问题
|
||||||
|
if rw.statusCode >= 500 {
|
||||||
|
logToStdout("ERROR", fields, message)
|
||||||
|
} else if rw.statusCode >= 400 {
|
||||||
|
logToStdout("WARN", fields, message)
|
||||||
|
} else {
|
||||||
|
logToStdout("INFO", fields, message)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// logToStdout 降级处理:输出到标准输出(当logger不可用时)
|
||||||
|
func logToStdout(level string, fields map[string]interface{}, message string) {
|
||||||
|
// 简单的标准输出日志
|
||||||
|
var fieldStr string
|
||||||
|
for k, v := range fields {
|
||||||
|
fieldStr += " " + k + "=" + formatValue(v)
|
||||||
|
}
|
||||||
|
println("[" + level + "] " + message + fieldStr)
|
||||||
|
}
|
||||||
|
|
||||||
|
// formatValue 格式化值(用于日志输出)
|
||||||
|
func formatValue(v interface{}) string {
|
||||||
|
switch val := v.(type) {
|
||||||
|
case string:
|
||||||
|
return val
|
||||||
|
case int:
|
||||||
|
return strconv.Itoa(val)
|
||||||
|
case int64:
|
||||||
|
return strconv.FormatInt(val, 10)
|
||||||
|
default:
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetClientIP 获取客户端真实IP
|
||||||
|
// 优先级:X-Forwarded-For > X-Real-IP > RemoteAddr
|
||||||
|
func GetClientIP(r *http.Request) string {
|
||||||
|
// 尝试从 X-Forwarded-For 获取
|
||||||
|
xff := r.Header.Get("X-Forwarded-For")
|
||||||
|
if xff != "" {
|
||||||
|
// X-Forwarded-For 可能包含多个IP,取第一个
|
||||||
|
for idx := 0; idx < len(xff); idx++ {
|
||||||
|
if xff[idx] == ',' {
|
||||||
|
return xff[:idx]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return xff
|
||||||
|
}
|
||||||
|
|
||||||
|
// 尝试从 X-Real-IP 获取
|
||||||
|
xri := r.Header.Get("X-Real-IP")
|
||||||
|
if xri != "" {
|
||||||
|
return xri
|
||||||
|
}
|
||||||
|
|
||||||
|
// 使用 RemoteAddr
|
||||||
|
remoteAddr := r.RemoteAddr
|
||||||
|
// 移除端口号
|
||||||
|
for i := len(remoteAddr) - 1; i >= 0; i-- {
|
||||||
|
if remoteAddr[i] == ':' {
|
||||||
|
return remoteAddr[:i]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return remoteAddr
|
||||||
|
}
|
||||||
286
middleware/ratelimit.go
Normal file
286
middleware/ratelimit.go
Normal file
@@ -0,0 +1,286 @@
|
|||||||
|
package middleware
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
// RateLimiter 限流器接口
|
||||||
|
type RateLimiter interface {
|
||||||
|
// Allow 检查是否允许请求
|
||||||
|
// key: 限流键(如IP地址、用户ID等)
|
||||||
|
// 返回: 是否允许, 剩余配额, 重置时间
|
||||||
|
Allow(key string) (allowed bool, remaining int, resetTime time.Time)
|
||||||
|
}
|
||||||
|
|
||||||
|
// tokenBucketLimiter 令牌桶限流器
|
||||||
|
type tokenBucketLimiter struct {
|
||||||
|
rate int // 每个窗口期允许的请求数
|
||||||
|
windowSize time.Duration // 窗口大小
|
||||||
|
buckets map[string]*bucket
|
||||||
|
mu sync.RWMutex
|
||||||
|
cleanupTicker *time.Ticker
|
||||||
|
stopCleanup chan struct{}
|
||||||
|
}
|
||||||
|
|
||||||
|
// bucket 令牌桶
|
||||||
|
type bucket struct {
|
||||||
|
tokens int // 当前令牌数
|
||||||
|
lastRefill time.Time // 上次填充时间
|
||||||
|
mu sync.Mutex
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewTokenBucketLimiter 创建令牌桶限流器
|
||||||
|
func NewTokenBucketLimiter(rate int, windowSize time.Duration) RateLimiter {
|
||||||
|
limiter := &tokenBucketLimiter{
|
||||||
|
rate: rate,
|
||||||
|
windowSize: windowSize,
|
||||||
|
buckets: make(map[string]*bucket),
|
||||||
|
stopCleanup: make(chan struct{}),
|
||||||
|
}
|
||||||
|
|
||||||
|
// 启动清理goroutine,定期清理过期的bucket
|
||||||
|
limiter.cleanupTicker = time.NewTicker(windowSize * 2)
|
||||||
|
go limiter.cleanup()
|
||||||
|
|
||||||
|
return limiter
|
||||||
|
}
|
||||||
|
|
||||||
|
// cleanup 定期清理过期的bucket
|
||||||
|
func (l *tokenBucketLimiter) cleanup() {
|
||||||
|
for {
|
||||||
|
select {
|
||||||
|
case <-l.cleanupTicker.C:
|
||||||
|
l.mu.Lock()
|
||||||
|
now := time.Now()
|
||||||
|
for key, bkt := range l.buckets {
|
||||||
|
bkt.mu.Lock()
|
||||||
|
// 如果bucket超过2个窗口期没有使用,删除它
|
||||||
|
if now.Sub(bkt.lastRefill) > l.windowSize*2 {
|
||||||
|
delete(l.buckets, key)
|
||||||
|
}
|
||||||
|
bkt.mu.Unlock()
|
||||||
|
}
|
||||||
|
l.mu.Unlock()
|
||||||
|
case <-l.stopCleanup:
|
||||||
|
l.cleanupTicker.Stop()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Allow 检查是否允许请求
|
||||||
|
func (l *tokenBucketLimiter) Allow(key string) (bool, int, time.Time) {
|
||||||
|
now := time.Now()
|
||||||
|
|
||||||
|
// 获取或创建bucket
|
||||||
|
l.mu.Lock()
|
||||||
|
bkt, exists := l.buckets[key]
|
||||||
|
if !exists {
|
||||||
|
bkt = &bucket{
|
||||||
|
tokens: l.rate,
|
||||||
|
lastRefill: now,
|
||||||
|
}
|
||||||
|
l.buckets[key] = bkt
|
||||||
|
}
|
||||||
|
l.mu.Unlock()
|
||||||
|
|
||||||
|
// 尝试消费令牌
|
||||||
|
bkt.mu.Lock()
|
||||||
|
defer bkt.mu.Unlock()
|
||||||
|
|
||||||
|
// 计算需要填充的令牌数
|
||||||
|
elapsed := now.Sub(bkt.lastRefill)
|
||||||
|
if elapsed >= l.windowSize {
|
||||||
|
// 窗口期已过,重新填充
|
||||||
|
bkt.tokens = l.rate
|
||||||
|
bkt.lastRefill = now
|
||||||
|
}
|
||||||
|
|
||||||
|
// 检查是否有可用令牌
|
||||||
|
if bkt.tokens > 0 {
|
||||||
|
bkt.tokens--
|
||||||
|
resetTime := bkt.lastRefill.Add(l.windowSize)
|
||||||
|
return true, bkt.tokens, resetTime
|
||||||
|
}
|
||||||
|
|
||||||
|
// 没有可用令牌
|
||||||
|
resetTime := bkt.lastRefill.Add(l.windowSize)
|
||||||
|
return false, 0, resetTime
|
||||||
|
}
|
||||||
|
|
||||||
|
// RateLimitConfig 限流中间件配置
|
||||||
|
type RateLimitConfig struct {
|
||||||
|
// Limiter 限流器(必需)
|
||||||
|
// 如果为nil,会使用默认的令牌桶限流器(100请求/分钟)
|
||||||
|
Limiter RateLimiter
|
||||||
|
|
||||||
|
// KeyFunc 生成限流键的函数(可选)
|
||||||
|
// 默认使用客户端IP作为键
|
||||||
|
// 可以自定义为用户ID、API Key等
|
||||||
|
KeyFunc func(r *http.Request) string
|
||||||
|
|
||||||
|
// OnRateLimitExceeded 当限流被触发时的回调(可选)
|
||||||
|
// 可以用于记录日志、发送告警等
|
||||||
|
OnRateLimitExceeded func(w http.ResponseWriter, r *http.Request, key string)
|
||||||
|
}
|
||||||
|
|
||||||
|
// RateLimit 限流中间件
|
||||||
|
// 实现基于令牌桶算法的请求限流
|
||||||
|
//
|
||||||
|
// 使用方式1:使用默认配置(100请求/分钟,按IP限流)
|
||||||
|
//
|
||||||
|
// chain := middleware.NewChain(
|
||||||
|
// middleware.RateLimit(nil),
|
||||||
|
// )
|
||||||
|
//
|
||||||
|
// 使用方式2:自定义限流规则
|
||||||
|
//
|
||||||
|
// limiter := middleware.NewTokenBucketLimiter(10, time.Minute) // 10请求/分钟
|
||||||
|
// chain := middleware.NewChain(
|
||||||
|
// middleware.RateLimit(&middleware.RateLimitConfig{
|
||||||
|
// Limiter: limiter,
|
||||||
|
// }),
|
||||||
|
// )
|
||||||
|
//
|
||||||
|
// 使用方式3:按用户ID限流
|
||||||
|
//
|
||||||
|
// chain := middleware.NewChain(
|
||||||
|
// middleware.RateLimit(&middleware.RateLimitConfig{
|
||||||
|
// Limiter: limiter,
|
||||||
|
// KeyFunc: func(r *http.Request) string {
|
||||||
|
// // 从请求头或token中获取用户ID
|
||||||
|
// return r.Header.Get("X-User-ID")
|
||||||
|
// },
|
||||||
|
// }),
|
||||||
|
// )
|
||||||
|
func RateLimit(config *RateLimitConfig) func(http.Handler) http.Handler {
|
||||||
|
// 如果没有配置,使用默认配置
|
||||||
|
if config == nil {
|
||||||
|
config = &RateLimitConfig{}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 如果没有提供限流器,创建默认的(100请求/分钟)
|
||||||
|
if config.Limiter == nil {
|
||||||
|
config.Limiter = NewTokenBucketLimiter(100, time.Minute)
|
||||||
|
}
|
||||||
|
|
||||||
|
// 如果没有提供KeyFunc,使用默认的(客户端IP)
|
||||||
|
if config.KeyFunc == nil {
|
||||||
|
config.KeyFunc = func(r *http.Request) string {
|
||||||
|
return GetClientIP(r)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return func(next http.Handler) http.Handler {
|
||||||
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
// 生成限流键
|
||||||
|
key := config.KeyFunc(r)
|
||||||
|
if key == "" {
|
||||||
|
// 如果无法生成键,允许请求通过
|
||||||
|
next.ServeHTTP(w, r)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// 检查是否允许请求
|
||||||
|
allowed, remaining, resetTime := config.Limiter.Allow(key)
|
||||||
|
|
||||||
|
// 设置限流相关的响应头
|
||||||
|
w.Header().Set("X-RateLimit-Limit", formatInt(config.Limiter.(*tokenBucketLimiter).rate))
|
||||||
|
w.Header().Set("X-RateLimit-Remaining", formatInt(remaining))
|
||||||
|
w.Header().Set("X-RateLimit-Reset", formatInt64(resetTime.Unix()))
|
||||||
|
|
||||||
|
if !allowed {
|
||||||
|
// 触发限流回调
|
||||||
|
if config.OnRateLimitExceeded != nil {
|
||||||
|
config.OnRateLimitExceeded(w, r, key)
|
||||||
|
}
|
||||||
|
|
||||||
|
// 返回429错误
|
||||||
|
w.Header().Set("Retry-After", formatInt64(int64(time.Until(resetTime).Seconds())))
|
||||||
|
http.Error(w, "Too Many Requests", http.StatusTooManyRequests)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// 允许请求通过
|
||||||
|
next.ServeHTTP(w, r)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// RateLimitWithRate 使用指定速率创建限流中间件(便捷函数)
|
||||||
|
// rate: 每个窗口期允许的请求数
|
||||||
|
// windowSize: 窗口大小
|
||||||
|
func RateLimitWithRate(rate int, windowSize time.Duration) func(http.Handler) http.Handler {
|
||||||
|
return RateLimit(&RateLimitConfig{
|
||||||
|
Limiter: NewTokenBucketLimiter(rate, windowSize),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// RateLimitByIP 按IP限流(便捷函数)
|
||||||
|
func RateLimitByIP(rate int, windowSize time.Duration) func(http.Handler) http.Handler {
|
||||||
|
return RateLimit(&RateLimitConfig{
|
||||||
|
Limiter: NewTokenBucketLimiter(rate, windowSize),
|
||||||
|
KeyFunc: func(r *http.Request) string {
|
||||||
|
return GetClientIP(r)
|
||||||
|
},
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// formatInt 格式化int为字符串
|
||||||
|
func formatInt(n int) string {
|
||||||
|
if n == 0 {
|
||||||
|
return "0"
|
||||||
|
}
|
||||||
|
|
||||||
|
// 简单的int转字符串
|
||||||
|
var buf [20]byte
|
||||||
|
i := len(buf) - 1
|
||||||
|
negative := n < 0
|
||||||
|
if negative {
|
||||||
|
n = -n
|
||||||
|
}
|
||||||
|
|
||||||
|
for n > 0 {
|
||||||
|
buf[i] = byte('0' + n%10)
|
||||||
|
n /= 10
|
||||||
|
i--
|
||||||
|
}
|
||||||
|
|
||||||
|
if negative {
|
||||||
|
buf[i] = '-'
|
||||||
|
i--
|
||||||
|
}
|
||||||
|
|
||||||
|
return string(buf[i+1:])
|
||||||
|
}
|
||||||
|
|
||||||
|
// formatInt64 格式化int64为字符串
|
||||||
|
func formatInt64(n int64) string {
|
||||||
|
if n == 0 {
|
||||||
|
return "0"
|
||||||
|
}
|
||||||
|
|
||||||
|
// 简单的int64转字符串
|
||||||
|
var buf [20]byte
|
||||||
|
i := len(buf) - 1
|
||||||
|
negative := n < 0
|
||||||
|
if negative {
|
||||||
|
n = -n
|
||||||
|
}
|
||||||
|
|
||||||
|
for n > 0 {
|
||||||
|
buf[i] = byte('0' + n%10)
|
||||||
|
n /= 10
|
||||||
|
i--
|
||||||
|
}
|
||||||
|
|
||||||
|
if negative {
|
||||||
|
buf[i] = '-'
|
||||||
|
i--
|
||||||
|
}
|
||||||
|
|
||||||
|
return string(buf[i+1:])
|
||||||
|
}
|
||||||
|
|
||||||
149
middleware/recovery.go
Normal file
149
middleware/recovery.go
Normal file
@@ -0,0 +1,149 @@
|
|||||||
|
package middleware
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"net/http"
|
||||||
|
"runtime/debug"
|
||||||
|
|
||||||
|
"git.toowon.com/jimmy/go-common/logger"
|
||||||
|
)
|
||||||
|
|
||||||
|
// RecoveryConfig Recovery中间件配置
|
||||||
|
type RecoveryConfig struct {
|
||||||
|
// Logger 日志记录器(可选,如果为nil则使用默认logger)
|
||||||
|
Logger *logger.Logger
|
||||||
|
|
||||||
|
// EnableStackTrace 是否在日志中包含堆栈跟踪
|
||||||
|
EnableStackTrace bool
|
||||||
|
|
||||||
|
// CustomHandler 自定义错误处理函数(可选)
|
||||||
|
// 如果设置了,会在记录日志后调用此函数
|
||||||
|
// 可以用于自定义错误响应格式
|
||||||
|
CustomHandler func(w http.ResponseWriter, r *http.Request, err interface{})
|
||||||
|
}
|
||||||
|
|
||||||
|
// Recovery Panic恢复中间件
|
||||||
|
// 捕获HTTP处理过程中的panic,记录错误日志并返回500错误
|
||||||
|
// 防止panic导致整个服务崩溃
|
||||||
|
//
|
||||||
|
// 使用方式1:使用默认配置
|
||||||
|
//
|
||||||
|
// chain := middleware.NewChain(
|
||||||
|
// middleware.Recovery(nil),
|
||||||
|
// )
|
||||||
|
//
|
||||||
|
// 使用方式2:使用自定义配置
|
||||||
|
//
|
||||||
|
// myLogger, _ := logger.NewLogger(loggerConfig)
|
||||||
|
// chain := middleware.NewChain(
|
||||||
|
// middleware.Recovery(&middleware.RecoveryConfig{
|
||||||
|
// Logger: myLogger,
|
||||||
|
// EnableStackTrace: true,
|
||||||
|
// }),
|
||||||
|
// )
|
||||||
|
//
|
||||||
|
// 使用方式3:自定义错误响应
|
||||||
|
//
|
||||||
|
// chain := middleware.NewChain(
|
||||||
|
// middleware.Recovery(&middleware.RecoveryConfig{
|
||||||
|
// Logger: myLogger,
|
||||||
|
// CustomHandler: func(w http.ResponseWriter, r *http.Request, err interface{}) {
|
||||||
|
// // 自定义JSON响应
|
||||||
|
// w.Header().Set("Content-Type", "application/json")
|
||||||
|
// w.WriteHeader(http.StatusInternalServerError)
|
||||||
|
// w.Write([]byte(`{"code":500,"message":"Internal Server Error"}`))
|
||||||
|
// },
|
||||||
|
// }),
|
||||||
|
// )
|
||||||
|
func Recovery(config *RecoveryConfig) func(http.Handler) http.Handler {
|
||||||
|
// 如果没有配置,使用默认配置
|
||||||
|
if config == nil {
|
||||||
|
config = &RecoveryConfig{
|
||||||
|
EnableStackTrace: true, // 默认启用堆栈跟踪
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 如果没有提供logger,创建一个默认的
|
||||||
|
if config.Logger == nil {
|
||||||
|
defaultLogger, err := logger.NewLogger(nil)
|
||||||
|
if err != nil {
|
||||||
|
config.Logger = nil
|
||||||
|
} else {
|
||||||
|
config.Logger = defaultLogger
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return func(next http.Handler) http.Handler {
|
||||||
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
defer func() {
|
||||||
|
if err := recover(); err != nil {
|
||||||
|
// 记录panic信息
|
||||||
|
logPanic(config.Logger, r, err, config.EnableStackTrace)
|
||||||
|
|
||||||
|
// 如果提供了自定义处理函数,调用它
|
||||||
|
if config.CustomHandler != nil {
|
||||||
|
config.CustomHandler(w, r, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// 默认错误响应
|
||||||
|
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
|
||||||
|
next.ServeHTTP(w, r)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// logPanic 记录panic日志
|
||||||
|
func logPanic(log *logger.Logger, r *http.Request, err interface{}, enableStackTrace bool) {
|
||||||
|
// 获取堆栈跟踪
|
||||||
|
var stack string
|
||||||
|
if enableStackTrace {
|
||||||
|
stack = string(debug.Stack())
|
||||||
|
}
|
||||||
|
|
||||||
|
// 构建日志字段
|
||||||
|
fields := map[string]interface{}{
|
||||||
|
"method": r.Method,
|
||||||
|
"path": r.URL.Path,
|
||||||
|
"query": r.URL.RawQuery,
|
||||||
|
"ip": GetClientIP(r),
|
||||||
|
"error": fmt.Sprintf("%v", err),
|
||||||
|
}
|
||||||
|
|
||||||
|
// 构建日志消息
|
||||||
|
message := "Panic recovered"
|
||||||
|
if enableStackTrace && stack != "" {
|
||||||
|
message += "\n" + stack
|
||||||
|
}
|
||||||
|
|
||||||
|
// 记录错误日志
|
||||||
|
if log != nil {
|
||||||
|
log.Errorf(fields, message)
|
||||||
|
} else {
|
||||||
|
// 降级处理:输出到标准错误
|
||||||
|
fmt.Printf("[ERROR] %s\n", message)
|
||||||
|
for k, v := range fields {
|
||||||
|
fmt.Printf(" %s: %v\n", k, v)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// RecoveryWithLogger 使用指定logger的Recovery中间件(便捷函数)
|
||||||
|
func RecoveryWithLogger(log *logger.Logger) func(http.Handler) http.Handler {
|
||||||
|
return Recovery(&RecoveryConfig{
|
||||||
|
Logger: log,
|
||||||
|
EnableStackTrace: true,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// RecoveryWithCustomHandler 使用自定义错误处理的Recovery中间件(便捷函数)
|
||||||
|
func RecoveryWithCustomHandler(customHandler func(w http.ResponseWriter, r *http.Request, err interface{})) func(http.Handler) http.Handler {
|
||||||
|
return Recovery(&RecoveryConfig{
|
||||||
|
EnableStackTrace: true,
|
||||||
|
CustomHandler: customHandler,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
@@ -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
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
222
migration/helper.go
Normal file
222
migration/helper.go
Normal file
@@ -0,0 +1,222 @@
|
|||||||
|
package migration
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"os"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"git.toowon.com/jimmy/go-common/config"
|
||||||
|
"gorm.io/driver/mysql"
|
||||||
|
"gorm.io/driver/postgres"
|
||||||
|
"gorm.io/driver/sqlite"
|
||||||
|
"gorm.io/gorm"
|
||||||
|
)
|
||||||
|
|
||||||
|
// RunMigrationsFromConfig 从配置文件运行迁移(便捷方法)
|
||||||
|
//
|
||||||
|
// 注意:推荐使用独立的迁移工具(templates/migrate/main.go),而不是在应用代码中直接调用。
|
||||||
|
// 独立工具可以实现零耦合、独立部署。
|
||||||
|
//
|
||||||
|
// 此方法主要用于:
|
||||||
|
// 1. 独立迁移工具内部调用(推荐)
|
||||||
|
// 2. 简单场景下在应用启动时调用(不推荐,会导致耦合)
|
||||||
|
//
|
||||||
|
// 用法:
|
||||||
|
//
|
||||||
|
// import "git.toowon.com/jimmy/go-common/migration"
|
||||||
|
// migration.RunMigrationsFromConfig("config.json", "migrations")
|
||||||
|
// // 或使用默认迁移目录
|
||||||
|
// migration.RunMigrationsFromConfig("config.json", "")
|
||||||
|
func RunMigrationsFromConfig(configFile, migrationsDir string) error {
|
||||||
|
return RunMigrationsFromConfigWithCommand(configFile, migrationsDir, "up")
|
||||||
|
}
|
||||||
|
|
||||||
|
// RunMigrationsFromConfigWithCommand 从配置文件运行迁移(支持命令,黑盒模式)
|
||||||
|
//
|
||||||
|
// 这是最简单的迁移方式,内部自动处理:
|
||||||
|
// - 配置加载(支持配置文件、默认路径)
|
||||||
|
// - 数据库连接(自动识别数据库类型)
|
||||||
|
// - 迁移文件加载和执行
|
||||||
|
//
|
||||||
|
// 参数:
|
||||||
|
// - configFile: 配置文件路径,支持:
|
||||||
|
// - 空字符串:自动查找(config.json, ../config.json)
|
||||||
|
// - 相对路径或绝对路径:指定配置文件路径
|
||||||
|
// - migrationsDir: 迁移文件目录,支持:
|
||||||
|
// - 空字符串:使用默认目录 "migrations"
|
||||||
|
// - 相对路径或绝对路径
|
||||||
|
// - command: 命令,支持 "up", "down", "status"
|
||||||
|
//
|
||||||
|
// 使用示例:
|
||||||
|
//
|
||||||
|
// // 最简单:使用默认配置和默认迁移目录
|
||||||
|
// migration.RunMigrationsFromConfigWithCommand("", "", "up")
|
||||||
|
//
|
||||||
|
// // 指定配置文件,使用默认迁移目录
|
||||||
|
// migration.RunMigrationsFromConfigWithCommand("config.json", "", "up")
|
||||||
|
//
|
||||||
|
// // 指定配置和迁移目录
|
||||||
|
// migration.RunMigrationsFromConfigWithCommand("config.json", "scripts/sql", "up")
|
||||||
|
func RunMigrationsFromConfigWithCommand(configFile, migrationsDir, command string) error {
|
||||||
|
// 加载配置
|
||||||
|
cfg, err := loadConfigFromFileOrEnv(configFile)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("加载配置失败: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// 连接数据库
|
||||||
|
db, err := connectDB(cfg)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("连接数据库失败: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// 使用默认迁移目录(如果未指定)
|
||||||
|
if migrationsDir == "" {
|
||||||
|
migrationsDir = "migrations"
|
||||||
|
}
|
||||||
|
|
||||||
|
// 创建迁移器(传入数据库类型,性能更好)
|
||||||
|
migrator := NewMigratorWithType(db, cfg.Database.Type)
|
||||||
|
|
||||||
|
// 加载迁移文件
|
||||||
|
migrations, err := LoadMigrationsFromFiles(migrationsDir, "*.sql")
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("加载迁移文件失败: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(migrations) == 0 {
|
||||||
|
fmt.Printf("在目录 '%s' 中没有找到迁移文件\n", migrationsDir)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
migrator.AddMigrations(migrations...)
|
||||||
|
|
||||||
|
// 执行命令
|
||||||
|
switch command {
|
||||||
|
case "up":
|
||||||
|
if err := migrator.Up(); err != nil {
|
||||||
|
return fmt.Errorf("执行迁移失败: %w", err)
|
||||||
|
}
|
||||||
|
fmt.Println("✓ 迁移执行成功")
|
||||||
|
|
||||||
|
case "down":
|
||||||
|
if err := migrator.Down(); err != nil {
|
||||||
|
return fmt.Errorf("回滚迁移失败: %w", err)
|
||||||
|
}
|
||||||
|
fmt.Println("✓ 迁移回滚成功")
|
||||||
|
|
||||||
|
case "status":
|
||||||
|
status, err := migrator.Status()
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("获取迁移状态失败: %w", err)
|
||||||
|
}
|
||||||
|
printMigrationStatus(status)
|
||||||
|
|
||||||
|
default:
|
||||||
|
return fmt.Errorf("未知命令: %s (支持: up, down, status)", command)
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// loadConfigFromFileOrEnv 从配置文件加载配置
|
||||||
|
// 支持指定配置文件路径,或自动查找默认路径
|
||||||
|
func loadConfigFromFileOrEnv(configFile string) (*config.Config, error) {
|
||||||
|
// 如果指定了配置文件路径,优先使用
|
||||||
|
if configFile != "" {
|
||||||
|
if _, err := os.Stat(configFile); err == nil {
|
||||||
|
return config.LoadFromFile(configFile)
|
||||||
|
}
|
||||||
|
// 如果指定的文件不存在,返回错误
|
||||||
|
return nil, fmt.Errorf("配置文件不存在: %s", configFile)
|
||||||
|
}
|
||||||
|
|
||||||
|
// 尝试默认路径
|
||||||
|
defaultPaths := []string{"config.json", "../config.json"}
|
||||||
|
for _, path := range defaultPaths {
|
||||||
|
if _, err := os.Stat(path); err == nil {
|
||||||
|
return config.LoadFromFile(path)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil, fmt.Errorf("未找到配置文件,请指定配置文件路径或确保存在以下文件之一: %v", defaultPaths)
|
||||||
|
}
|
||||||
|
|
||||||
|
// connectDB 连接数据库
|
||||||
|
// 与 factory.getDatabase 保持一致的实现,避免代码重复
|
||||||
|
func connectDB(cfg *config.Config) (*gorm.DB, error) {
|
||||||
|
if cfg.Database == nil {
|
||||||
|
return nil, fmt.Errorf("数据库配置为空")
|
||||||
|
}
|
||||||
|
|
||||||
|
dsn, err := cfg.GetDatabaseDSN()
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
var db *gorm.DB
|
||||||
|
switch cfg.Database.Type {
|
||||||
|
case "mysql":
|
||||||
|
db, err = gorm.Open(mysql.Open(dsn), &gorm.Config{})
|
||||||
|
case "postgres":
|
||||||
|
db, err = gorm.Open(postgres.Open(dsn), &gorm.Config{})
|
||||||
|
case "sqlite":
|
||||||
|
db, err = gorm.Open(sqlite.Open(dsn), &gorm.Config{})
|
||||||
|
default:
|
||||||
|
return nil, fmt.Errorf("不支持的数据库类型: %s", cfg.Database.Type)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// 配置连接池(与 factory.getDatabase 保持一致)
|
||||||
|
sqlDB, err := db.DB()
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// 使用配置文件中的连接池参数,如果没有配置则使用默认值
|
||||||
|
if cfg.Database.MaxOpenConns > 0 {
|
||||||
|
sqlDB.SetMaxOpenConns(cfg.Database.MaxOpenConns)
|
||||||
|
} else {
|
||||||
|
sqlDB.SetMaxOpenConns(10) // 默认值
|
||||||
|
}
|
||||||
|
|
||||||
|
if cfg.Database.MaxIdleConns > 0 {
|
||||||
|
sqlDB.SetMaxIdleConns(cfg.Database.MaxIdleConns)
|
||||||
|
} else {
|
||||||
|
sqlDB.SetMaxIdleConns(5) // 默认值
|
||||||
|
}
|
||||||
|
|
||||||
|
if cfg.Database.ConnMaxLifetime > 0 {
|
||||||
|
sqlDB.SetConnMaxLifetime(time.Duration(cfg.Database.ConnMaxLifetime) * time.Second)
|
||||||
|
} else {
|
||||||
|
sqlDB.SetConnMaxLifetime(time.Hour) // 默认值
|
||||||
|
}
|
||||||
|
|
||||||
|
return db, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// printMigrationStatus 打印迁移状态
|
||||||
|
func printMigrationStatus(status []MigrationStatus) {
|
||||||
|
if len(status) == 0 {
|
||||||
|
fmt.Println("没有找到迁移")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
fmt.Println("\n迁移状态:")
|
||||||
|
fmt.Println("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━")
|
||||||
|
fmt.Printf("%-20s %-40s %-10s\n", "版本", "描述", "状态")
|
||||||
|
fmt.Println("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━")
|
||||||
|
|
||||||
|
for _, s := range status {
|
||||||
|
statusText := "待执行"
|
||||||
|
if s.Applied {
|
||||||
|
statusText = "✓ 已应用"
|
||||||
|
}
|
||||||
|
fmt.Printf("%-20s %-40s %-10s\n", s.Version, s.Description, statusText)
|
||||||
|
}
|
||||||
|
fmt.Println("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━")
|
||||||
|
fmt.Println()
|
||||||
|
}
|
||||||
@@ -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,33 +76,152 @@ 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
|
||||||
|
|
||||||
|
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 EXISTS (
|
||||||
SELECT FROM information_schema.tables
|
SELECT 1 FROM information_schema.tables
|
||||||
WHERE table_schema = CURRENT_SCHEMA()
|
WHERE table_schema = CURRENT_SCHEMA()
|
||||||
AND table_name = '%s'
|
AND table_name = '%s'
|
||||||
)
|
)
|
||||||
`, m.tableName)).Scan(&exists).Error
|
`, 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
|
||||||
}
|
}
|
||||||
|
|
||||||
if !exists {
|
if !exists {
|
||||||
// 创建迁移记录表
|
// 创建迁移记录表(包含执行时间字段)
|
||||||
err = m.db.Exec(fmt.Sprintf(`
|
err = m.db.Exec(fmt.Sprintf(`
|
||||||
CREATE TABLE IF NOT EXISTS %s (
|
CREATE TABLE IF NOT EXISTS %s (
|
||||||
version VARCHAR(255) PRIMARY KEY,
|
version VARCHAR(255) PRIMARY KEY,
|
||||||
description VARCHAR(255),
|
description VARCHAR(255),
|
||||||
applied_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
applied_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
execution_time INT COMMENT '执行耗时(ms)'
|
||||||
)
|
)
|
||||||
`, m.tableName)).Error
|
`, m.tableName)).Error
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("failed to create migration table: %w", err)
|
return fmt.Errorf("failed to create migration table: %w", err)
|
||||||
}
|
}
|
||||||
|
} else {
|
||||||
|
// 表已存在,检查是否有 execution_time 字段(向后兼容)
|
||||||
|
// 注意:这个检查可能在某些数据库中失败,但不影响功能
|
||||||
|
// 如果字段不存在,记录执行时间时会失败,但不影响迁移执行
|
||||||
|
var hasExecutionTime bool
|
||||||
|
var columnCount int64
|
||||||
|
var checkErr error
|
||||||
|
|
||||||
|
switch m.dbType {
|
||||||
|
case "mysql":
|
||||||
|
// MySQL/MariaDB语法
|
||||||
|
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
|
||||||
|
}
|
||||||
|
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(`
|
||||||
|
ALTER TABLE %s
|
||||||
|
ADD COLUMN execution_time INT
|
||||||
|
`, m.tableName))
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return nil
|
return nil
|
||||||
@@ -109,17 +248,34 @@ func (m *Migrator) getAppliedMigrations() (map[string]bool, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// recordMigration 记录迁移
|
// recordMigration 记录迁移
|
||||||
func (m *Migrator) recordMigration(version, description string, isUp bool) error {
|
func (m *Migrator) recordMigration(version, description string, isUp bool, executionTime ...int) error {
|
||||||
if err := m.initTable(); err != nil {
|
if err := m.initTable(); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
if isUp {
|
if isUp {
|
||||||
// 记录迁移
|
// 记录迁移(包含执行时间,如果提供了)
|
||||||
err := m.db.Exec(fmt.Sprintf(`
|
var err error
|
||||||
|
if len(executionTime) > 0 && executionTime[0] > 0 {
|
||||||
|
// 尝试插入执行时间(如果字段存在)
|
||||||
|
err = m.db.Exec(fmt.Sprintf(`
|
||||||
|
INSERT INTO %s (version, description, applied_at, execution_time)
|
||||||
|
VALUES (?, ?, ?, ?)
|
||||||
|
`, m.tableName), version, description, time.Now(), executionTime[0]).Error
|
||||||
|
if err != nil {
|
||||||
|
// 如果失败(可能是字段不存在),尝试不包含执行时间
|
||||||
|
err = m.db.Exec(fmt.Sprintf(`
|
||||||
INSERT INTO %s (version, description, applied_at)
|
INSERT INTO %s (version, description, applied_at)
|
||||||
VALUES (?, ?, ?)
|
VALUES (?, ?, ?)
|
||||||
`, m.tableName), version, description, time.Now()).Error
|
`, m.tableName), version, description, time.Now()).Error
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// 不包含执行时间
|
||||||
|
err = m.db.Exec(fmt.Sprintf(`
|
||||||
|
INSERT INTO %s (version, description, applied_at)
|
||||||
|
VALUES (?, ?, ?)
|
||||||
|
`, m.tableName), version, description, time.Now()).Error
|
||||||
|
}
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("failed to record migration: %w", err)
|
return fmt.Errorf("failed to record migration: %w", err)
|
||||||
}
|
}
|
||||||
@@ -160,6 +316,9 @@ func (m *Migrator) Up() error {
|
|||||||
return fmt.Errorf("migration %s has no Up function", migration.Version)
|
return fmt.Errorf("migration %s has no Up function", migration.Version)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 记录开始时间
|
||||||
|
startTime := time.Now()
|
||||||
|
|
||||||
// 开始事务
|
// 开始事务
|
||||||
tx := m.db.Begin()
|
tx := m.db.Begin()
|
||||||
if tx.Error != nil {
|
if tx.Error != nil {
|
||||||
@@ -172,8 +331,11 @@ func (m *Migrator) Up() error {
|
|||||||
return fmt.Errorf("failed to apply migration %s: %w", migration.Version, err)
|
return fmt.Errorf("failed to apply migration %s: %w", migration.Version, err)
|
||||||
}
|
}
|
||||||
|
|
||||||
// 记录迁移
|
// 计算执行时间(毫秒)
|
||||||
if err := m.recordMigrationWithDB(tx, migration.Version, migration.Description, true); err != nil {
|
executionTime := int(time.Since(startTime).Milliseconds())
|
||||||
|
|
||||||
|
// 记录迁移(包含执行时间)
|
||||||
|
if err := m.recordMigrationWithDB(tx, migration.Version, migration.Description, true, executionTime); err != nil {
|
||||||
tx.Rollback()
|
tx.Rollback()
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
@@ -183,7 +345,7 @@ func (m *Migrator) Up() error {
|
|||||||
return fmt.Errorf("failed to commit migration %s: %w", migration.Version, err)
|
return fmt.Errorf("failed to commit migration %s: %w", migration.Version, err)
|
||||||
}
|
}
|
||||||
|
|
||||||
fmt.Printf("Applied migration: %s - %s\n", migration.Version, migration.Description)
|
fmt.Printf("Applied migration: %s - %s (耗时: %dms)\n", migration.Version, migration.Description, executionTime)
|
||||||
}
|
}
|
||||||
|
|
||||||
return nil
|
return nil
|
||||||
@@ -246,12 +408,29 @@ func (m *Migrator) Down() error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// recordMigrationWithDB 使用指定的数据库连接记录迁移
|
// recordMigrationWithDB 使用指定的数据库连接记录迁移
|
||||||
func (m *Migrator) recordMigrationWithDB(db *gorm.DB, version, description string, isUp bool) error {
|
func (m *Migrator) recordMigrationWithDB(db *gorm.DB, version, description string, isUp bool, executionTime ...int) error {
|
||||||
if isUp {
|
if isUp {
|
||||||
err := db.Exec(fmt.Sprintf(`
|
var err error
|
||||||
|
if len(executionTime) > 0 && executionTime[0] > 0 {
|
||||||
|
// 尝试插入执行时间(如果字段存在)
|
||||||
|
err = db.Exec(fmt.Sprintf(`
|
||||||
|
INSERT INTO %s (version, description, applied_at, execution_time)
|
||||||
|
VALUES (?, ?, ?, ?)
|
||||||
|
`, m.tableName), version, description, time.Now(), executionTime[0]).Error
|
||||||
|
if err != nil {
|
||||||
|
// 如果失败(可能是字段不存在),尝试不包含执行时间
|
||||||
|
err = db.Exec(fmt.Sprintf(`
|
||||||
INSERT INTO %s (version, description, applied_at)
|
INSERT INTO %s (version, description, applied_at)
|
||||||
VALUES (?, ?, ?)
|
VALUES (?, ?, ?)
|
||||||
`, m.tableName), version, description, time.Now()).Error
|
`, m.tableName), version, description, time.Now()).Error
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// 不包含执行时间
|
||||||
|
err = db.Exec(fmt.Sprintf(`
|
||||||
|
INSERT INTO %s (version, description, applied_at)
|
||||||
|
VALUES (?, ?, ?)
|
||||||
|
`, m.tableName), version, description, time.Now()).Error
|
||||||
|
}
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("failed to record migration: %w", err)
|
return fmt.Errorf("failed to record migration: %w", err)
|
||||||
}
|
}
|
||||||
@@ -300,10 +479,96 @@ type MigrationStatus struct {
|
|||||||
Applied bool
|
Applied bool
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// splitSQL 分割SQL语句,处理多行SQL、注释等
|
||||||
|
// 支持单行注释(--)、多行注释(/* */)、按分号分割语句
|
||||||
|
func splitSQL(content string) []string {
|
||||||
|
var statements []string
|
||||||
|
var current strings.Builder
|
||||||
|
|
||||||
|
lines := strings.Split(content, "\n")
|
||||||
|
inMultiLineComment := false
|
||||||
|
|
||||||
|
for _, line := range lines {
|
||||||
|
trimmedLine := strings.TrimSpace(line)
|
||||||
|
|
||||||
|
// 跳过空行
|
||||||
|
if trimmedLine == "" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
// 处理多行注释
|
||||||
|
if strings.HasPrefix(trimmedLine, "/*") {
|
||||||
|
inMultiLineComment = true
|
||||||
|
}
|
||||||
|
if strings.HasSuffix(trimmedLine, "*/") {
|
||||||
|
inMultiLineComment = false
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if inMultiLineComment {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
// 跳过单行注释
|
||||||
|
if strings.HasPrefix(trimmedLine, "--") {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
// 添加到当前语句
|
||||||
|
current.WriteString(line)
|
||||||
|
current.WriteString("\n")
|
||||||
|
|
||||||
|
// 检查是否是完整语句(以分号结尾)
|
||||||
|
if strings.HasSuffix(trimmedLine, ";") {
|
||||||
|
stmt := strings.TrimSpace(current.String())
|
||||||
|
if stmt != "" && !strings.HasPrefix(stmt, "--") {
|
||||||
|
statements = append(statements, stmt)
|
||||||
|
}
|
||||||
|
current.Reset()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 添加最后一个语句(如果没有分号结尾)
|
||||||
|
if current.Len() > 0 {
|
||||||
|
stmt := strings.TrimSpace(current.String())
|
||||||
|
if stmt != "" && !strings.HasPrefix(stmt, "--") {
|
||||||
|
statements = append(statements, stmt)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return statements
|
||||||
|
}
|
||||||
|
|
||||||
|
// parseMigrationFileName 解析迁移文件名,支持多种格式
|
||||||
|
// 格式1: 数字前缀 - 01_init_schema.sql
|
||||||
|
// 格式2: 时间戳 - 20240101000001_create_users.sql
|
||||||
|
// 格式3: 带.up后缀 - 20240101000001_create_users.up.sql
|
||||||
|
// 返回: (version, description, error)
|
||||||
|
func parseMigrationFileName(baseName string) (string, string, error) {
|
||||||
|
// 移除扩展名
|
||||||
|
nameWithoutExt := strings.TrimSuffix(baseName, filepath.Ext(baseName))
|
||||||
|
// 移除 .up 后缀(如果存在)
|
||||||
|
nameWithoutExt = strings.TrimSuffix(nameWithoutExt, ".up")
|
||||||
|
|
||||||
|
// 解析版本号和描述
|
||||||
|
parts := strings.SplitN(nameWithoutExt, "_", 2)
|
||||||
|
if len(parts) < 2 {
|
||||||
|
// 如果只有一个部分,尝试作为版本号(向后兼容)
|
||||||
|
return nameWithoutExt, baseName, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
version := parts[0]
|
||||||
|
description := strings.Join(parts[1:], "_")
|
||||||
|
|
||||||
|
return version, description, nil
|
||||||
|
}
|
||||||
|
|
||||||
// LoadMigrationsFromFiles 从文件系统加载迁移文件
|
// LoadMigrationsFromFiles 从文件系统加载迁移文件
|
||||||
// dir: 迁移文件目录
|
// dir: 迁移文件目录
|
||||||
// pattern: 文件命名模式,例如 "*.sql" 或 "*.up.sql"
|
// pattern: 文件命名模式,例如 "*.sql" 或 "*.up.sql"
|
||||||
// 文件命名格式: {version}_{description}.sql 或 {version}_{description}.up.sql
|
// 文件命名格式支持:
|
||||||
|
// - 数字前缀: 01_init_schema.sql
|
||||||
|
// - 时间戳: 20240101000001_create_users.sql
|
||||||
|
// - 带.up后缀: 20240101000001_create_users.up.sql
|
||||||
func LoadMigrationsFromFiles(dir string, pattern string) ([]Migration, error) {
|
func LoadMigrationsFromFiles(dir string, pattern string) ([]Migration, error) {
|
||||||
files, err := filepath.Glob(filepath.Join(dir, pattern))
|
files, err := filepath.Glob(filepath.Join(dir, pattern))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -313,19 +578,17 @@ func LoadMigrationsFromFiles(dir string, pattern string) ([]Migration, error) {
|
|||||||
migrations := make([]Migration, 0)
|
migrations := make([]Migration, 0)
|
||||||
for _, file := range files {
|
for _, file := range files {
|
||||||
baseName := filepath.Base(file)
|
baseName := filepath.Base(file)
|
||||||
// 移除扩展名
|
|
||||||
nameWithoutExt := strings.TrimSuffix(baseName, filepath.Ext(baseName))
|
|
||||||
// 移除 .up 后缀(如果存在)
|
|
||||||
nameWithoutExt = strings.TrimSuffix(nameWithoutExt, ".up")
|
|
||||||
|
|
||||||
// 解析版本号和描述
|
// 跳过 .down.sql 文件(会在处理 .up.sql 或 .sql 时自动加载)
|
||||||
parts := strings.SplitN(nameWithoutExt, "_", 2)
|
if strings.HasSuffix(baseName, ".down.sql") {
|
||||||
if len(parts) < 2 {
|
continue
|
||||||
return nil, fmt.Errorf("invalid migration file name format: %s (expected: {version}_{description})", baseName)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
version := parts[0]
|
// 解析版本号和描述
|
||||||
description := strings.Join(parts[1:], "_")
|
version, description, err := parseMigrationFileName(baseName)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("invalid migration file name format: %s: %w", baseName, err)
|
||||||
|
}
|
||||||
|
|
||||||
// 读取文件内容
|
// 读取文件内容
|
||||||
content, err := os.ReadFile(file)
|
content, err := os.ReadFile(file)
|
||||||
@@ -343,26 +606,81 @@ func LoadMigrationsFromFiles(dir string, pattern string) ([]Migration, error) {
|
|||||||
downSQL = string(downContent)
|
downSQL = string(downContent)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 创建迁移,使用 SQL 分割功能
|
||||||
migration := Migration{
|
migration := Migration{
|
||||||
Version: version,
|
Version: version,
|
||||||
Description: description,
|
Description: description,
|
||||||
Up: func(db *gorm.DB) error {
|
Up: func(db *gorm.DB) error {
|
||||||
return db.Exec(sqlContent).Error
|
// 分割 SQL 语句
|
||||||
|
statements := splitSQL(sqlContent)
|
||||||
|
if len(statements) == 0 {
|
||||||
|
return nil // 空文件,跳过
|
||||||
|
}
|
||||||
|
|
||||||
|
// 执行每个 SQL 语句
|
||||||
|
// 注意:某些 DDL 语句(如 CREATE TABLE)在某些数据库中会隐式提交事务
|
||||||
|
// 因此这里不使用事务,而是逐个执行
|
||||||
|
for i, stmt := range statements {
|
||||||
|
stmt = strings.TrimSpace(stmt)
|
||||||
|
if stmt == "" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := db.Exec(stmt).Error; err != nil {
|
||||||
|
// 如果是表已存在的错误,记录警告但继续执行(向后兼容)
|
||||||
|
errStr := err.Error()
|
||||||
|
if strings.Contains(errStr, "already exists") ||
|
||||||
|
strings.Contains(errStr, "Duplicate") ||
|
||||||
|
strings.Contains(errStr, "duplicate") {
|
||||||
|
fmt.Printf("Warning: SQL statement %d in migration %s: %v\n", i+1, version, err)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
return fmt.Errorf("failed to execute SQL statement %d in migration %s: %w\nSQL: %s", i+1, version, err, stmt)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
if downSQL != "" {
|
if downSQL != "" {
|
||||||
migration.Down = func(db *gorm.DB) error {
|
migration.Down = func(db *gorm.DB) error {
|
||||||
return db.Exec(downSQL).Error
|
// 分割 SQL 语句
|
||||||
|
statements := splitSQL(downSQL)
|
||||||
|
if len(statements) == 0 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// 执行每个 SQL 语句
|
||||||
|
for i, stmt := range statements {
|
||||||
|
stmt = strings.TrimSpace(stmt)
|
||||||
|
if stmt == "" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := db.Exec(stmt).Error; err != nil {
|
||||||
|
return fmt.Errorf("failed to execute SQL statement %d in rollback %s: %w\nSQL: %s", i+1, version, err, stmt)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
migrations = append(migrations, migration)
|
migrations = append(migrations, migration)
|
||||||
}
|
}
|
||||||
|
|
||||||
// 按版本号排序
|
// 按版本号排序(支持数字和时间戳混合排序)
|
||||||
sort.Slice(migrations, func(i, j int) bool {
|
sort.Slice(migrations, func(i, j int) bool {
|
||||||
return migrations[i].Version < migrations[j].Version
|
vi, vj := migrations[i].Version, migrations[j].Version
|
||||||
|
// 尝试按数字排序(如果是数字前缀)
|
||||||
|
if viNum, err1 := strconv.Atoi(vi); err1 == nil {
|
||||||
|
if vjNum, err2 := strconv.Atoi(vj); err2 == nil {
|
||||||
|
return viNum < vjNum
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// 否则按字符串排序
|
||||||
|
return vi < vj
|
||||||
})
|
})
|
||||||
|
|
||||||
return migrations, nil
|
return migrations, nil
|
||||||
|
|||||||
273
sms/sms.go
273
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 创建短信发送器
|
||||||
if params["Action"] == "" {
|
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 == "" {
|
||||||
|
return nil, fmt.Errorf("AccessKeyID is required")
|
||||||
|
}
|
||||||
|
|
||||||
|
if s.config.AccessKeySecret == "" {
|
||||||
|
return nil, fmt.Errorf("AccessKeySecret is required")
|
||||||
|
}
|
||||||
|
|
||||||
|
if s.config.SignName == "" {
|
||||||
|
return nil, fmt.Errorf("SignName is required")
|
||||||
|
}
|
||||||
|
|
||||||
|
// 设置默认值
|
||||||
|
if s.config.Region == "" {
|
||||||
|
s.config.Region = "cn-hangzhou"
|
||||||
|
}
|
||||||
|
if s.config.Timeout == 0 {
|
||||||
|
s.config.Timeout = 10
|
||||||
|
}
|
||||||
|
|
||||||
|
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 len(phoneNumbers) == 0 {
|
||||||
|
return nil, fmt.Errorf("phone numbers are required")
|
||||||
|
}
|
||||||
|
|
||||||
|
// 使用配置中的模板代码(如果请求中未指定)
|
||||||
|
templateCodeValue := ""
|
||||||
|
if len(templateCode) > 0 && templateCode[0] != "" {
|
||||||
|
templateCodeValue = templateCode[0]
|
||||||
|
} else {
|
||||||
|
templateCodeValue = cfg.TemplateCode
|
||||||
|
}
|
||||||
|
if templateCodeValue == "" {
|
||||||
|
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["Action"] = "SendSms"
|
||||||
}
|
|
||||||
if params["Version"] == "" {
|
|
||||||
params["Version"] = "2017-05-25"
|
params["Version"] = "2017-05-25"
|
||||||
}
|
params["RegionId"] = cfg.Region
|
||||||
if params["RegionId"] == "" {
|
params["AccessKeyId"] = cfg.AccessKeyID
|
||||||
params["RegionId"] = s.config.Region
|
|
||||||
}
|
|
||||||
if params["AccessKeyId"] == "" {
|
|
||||||
params["AccessKeyId"] = s.config.AccessKeyID
|
|
||||||
}
|
|
||||||
if params["Format"] == "" {
|
|
||||||
params["Format"] = "JSON"
|
params["Format"] = "JSON"
|
||||||
}
|
|
||||||
if params["SignatureMethod"] == "" {
|
|
||||||
params["SignatureMethod"] = "HMAC-SHA1"
|
params["SignatureMethod"] = "HMAC-SHA1"
|
||||||
}
|
|
||||||
if params["SignatureVersion"] == "" {
|
|
||||||
params["SignatureVersion"] = "1.0"
|
params["SignatureVersion"] = "1.0"
|
||||||
}
|
|
||||||
if params["SignatureNonce"] == "" {
|
|
||||||
params["SignatureNonce"] = fmt.Sprint(time.Now().UnixNano())
|
params["SignatureNonce"] = fmt.Sprint(time.Now().UnixNano())
|
||||||
}
|
|
||||||
if params["Timestamp"] == "" {
|
|
||||||
params["Timestamp"] = time.Now().UTC().Format("2006-01-02T15:04:05Z")
|
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 生成唯一文件名
|
||||||
|
|||||||
39
templates/Dockerfile.example
Normal file
39
templates/Dockerfile.example
Normal file
@@ -0,0 +1,39 @@
|
|||||||
|
# Dockerfile 示例
|
||||||
|
# 展示如何构建包含迁移工具的 Go 应用
|
||||||
|
|
||||||
|
# ===== 构建阶段 =====
|
||||||
|
FROM golang:1.21 as builder
|
||||||
|
|
||||||
|
WORKDIR /app
|
||||||
|
COPY go.mod go.sum ./
|
||||||
|
RUN go mod download
|
||||||
|
|
||||||
|
COPY . .
|
||||||
|
|
||||||
|
# 编译应用和迁移工具
|
||||||
|
RUN go build -o bin/server cmd/server/main.go
|
||||||
|
RUN go build -o bin/migrate cmd/migrate/main.go
|
||||||
|
|
||||||
|
# ===== 运行阶段 =====
|
||||||
|
FROM debian:bookworm-slim
|
||||||
|
|
||||||
|
WORKDIR /app
|
||||||
|
|
||||||
|
# 安装运行时依赖
|
||||||
|
RUN apt-get update && apt-get install -y ca-certificates && rm -rf /var/lib/apt/lists/*
|
||||||
|
|
||||||
|
# 复制二进制文件和迁移文件
|
||||||
|
COPY --from=builder /app/bin/server .
|
||||||
|
COPY --from=builder /app/bin/migrate .
|
||||||
|
COPY --from=builder /app/migrations ./migrations
|
||||||
|
|
||||||
|
EXPOSE 8080
|
||||||
|
|
||||||
|
# 启动:先执行迁移,再启动应用
|
||||||
|
CMD ["sh", "-c", "./migrate up && ./server"]
|
||||||
|
|
||||||
|
# 注意:
|
||||||
|
# 1. 配置文件通过 docker-compose volumes 挂载,不打包进镜像
|
||||||
|
# 2. 镜像只包含二进制文件和迁移SQL文件
|
||||||
|
# 3. 配置文件在运行时提供,更安全、更灵活
|
||||||
|
|
||||||
78
templates/Makefile.example
Normal file
78
templates/Makefile.example
Normal file
@@ -0,0 +1,78 @@
|
|||||||
|
# 示例 Makefile
|
||||||
|
# 提供常用的开发和部署命令
|
||||||
|
|
||||||
|
.PHONY: help build run migrate-up migrate-down migrate-status docker-build docker-up clean
|
||||||
|
|
||||||
|
# 默认目标:显示帮助
|
||||||
|
help:
|
||||||
|
@echo "可用命令:"
|
||||||
|
@echo " make build - 编译应用和迁移工具"
|
||||||
|
@echo " make run - 运行应用(先执行迁移)"
|
||||||
|
@echo " make migrate-up - 执行数据库迁移"
|
||||||
|
@echo " make migrate-down - 回滚数据库迁移"
|
||||||
|
@echo " make migrate-status - 查看迁移状态"
|
||||||
|
@echo " make docker-build - 构建 Docker 镜像"
|
||||||
|
@echo " make docker-up - 启动 Docker 服务"
|
||||||
|
@echo " make clean - 清理编译文件"
|
||||||
|
|
||||||
|
# 编译
|
||||||
|
build:
|
||||||
|
@echo "编译应用..."
|
||||||
|
@mkdir -p bin
|
||||||
|
@go build -o bin/server cmd/server/main.go
|
||||||
|
@go build -o bin/migrate cmd/migrate/main.go
|
||||||
|
@echo "✓ 编译完成"
|
||||||
|
|
||||||
|
# 运行应用
|
||||||
|
run: migrate-up
|
||||||
|
@echo "启动应用..."
|
||||||
|
@./bin/server
|
||||||
|
|
||||||
|
# 执行迁移
|
||||||
|
migrate-up: build
|
||||||
|
@echo "执行数据库迁移..."
|
||||||
|
@./bin/migrate up
|
||||||
|
|
||||||
|
# 回滚迁移
|
||||||
|
migrate-down: build
|
||||||
|
@echo "回滚数据库迁移..."
|
||||||
|
@./bin/migrate down
|
||||||
|
|
||||||
|
# 查看迁移状态
|
||||||
|
migrate-status: build
|
||||||
|
@./bin/migrate status
|
||||||
|
|
||||||
|
# 构建 Docker 镜像
|
||||||
|
docker-build:
|
||||||
|
@echo "构建 Docker 镜像..."
|
||||||
|
@docker build -t myapp:latest .
|
||||||
|
|
||||||
|
# 启动 Docker 服务
|
||||||
|
docker-up:
|
||||||
|
@echo "启动 Docker 服务..."
|
||||||
|
@docker-compose up --build
|
||||||
|
|
||||||
|
# 清理
|
||||||
|
clean:
|
||||||
|
@echo "清理编译文件..."
|
||||||
|
@rm -rf bin
|
||||||
|
@echo "✓ 清理完成"
|
||||||
|
|
||||||
|
# 开发环境:直接运行(不编译)
|
||||||
|
dev-migrate-up:
|
||||||
|
@go run cmd/migrate/main.go up
|
||||||
|
|
||||||
|
dev-migrate-down:
|
||||||
|
@go run cmd/migrate/main.go down
|
||||||
|
|
||||||
|
dev-migrate-status:
|
||||||
|
@go run cmd/migrate/main.go status
|
||||||
|
|
||||||
|
# 交叉编译(Linux)
|
||||||
|
build-linux:
|
||||||
|
@echo "交叉编译 Linux 版本..."
|
||||||
|
@mkdir -p bin
|
||||||
|
@GOOS=linux GOARCH=amd64 go build -o bin/server-linux cmd/server/main.go
|
||||||
|
@GOOS=linux GOARCH=amd64 go build -o bin/migrate-linux cmd/migrate/main.go
|
||||||
|
@echo "✓ Linux 版本编译完成"
|
||||||
|
|
||||||
40
templates/README.md
Normal file
40
templates/README.md
Normal file
@@ -0,0 +1,40 @@
|
|||||||
|
# 模板文件
|
||||||
|
|
||||||
|
这个目录包含了可以直接复制到你项目中使用的模板文件。
|
||||||
|
|
||||||
|
## 包含的模板
|
||||||
|
|
||||||
|
- `migrate/main.go` - 数据库迁移工具模板 ⭐
|
||||||
|
- `Dockerfile.example` - Docker 构建示例
|
||||||
|
- `docker-compose.example.yml` - Docker Compose 示例
|
||||||
|
- `Makefile.example` - Makefile 常用命令示例
|
||||||
|
|
||||||
|
## 快速使用
|
||||||
|
|
||||||
|
### 迁移工具模板
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 1. 复制到你的项目
|
||||||
|
mkdir -p cmd/migrate
|
||||||
|
cp templates/migrate/main.go cmd/migrate/
|
||||||
|
|
||||||
|
# 2. 编译
|
||||||
|
go build -o bin/migrate cmd/migrate/main.go
|
||||||
|
|
||||||
|
# 3. 使用
|
||||||
|
./bin/migrate up
|
||||||
|
./bin/migrate -help
|
||||||
|
```
|
||||||
|
|
||||||
|
### Docker 模板
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 复制到你的项目根目录
|
||||||
|
cp templates/Dockerfile.example Dockerfile
|
||||||
|
cp templates/docker-compose.example.yml docker-compose.yml
|
||||||
|
cp templates/Makefile.example Makefile
|
||||||
|
```
|
||||||
|
|
||||||
|
## 完整文档
|
||||||
|
|
||||||
|
详细使用说明请查看:[MIGRATION.md](../MIGRATION.md)
|
||||||
22
templates/docker-compose.example.yml
Normal file
22
templates/docker-compose.example.yml
Normal file
@@ -0,0 +1,22 @@
|
|||||||
|
# docker-compose.yml 示例
|
||||||
|
# 展示如何在 docker-compose 中使用迁移工具
|
||||||
|
|
||||||
|
version: '3.8'
|
||||||
|
|
||||||
|
services:
|
||||||
|
app:
|
||||||
|
build: .
|
||||||
|
ports:
|
||||||
|
- "8080:8080"
|
||||||
|
volumes:
|
||||||
|
# 挂载配置文件(推荐:修改配置无需重启容器)
|
||||||
|
- ./config.json:/app/config.json:ro
|
||||||
|
# 启动时先执行迁移,再启动应用
|
||||||
|
command: sh -c "./migrate up && ./server"
|
||||||
|
|
||||||
|
# 使用说明:
|
||||||
|
# 1. 将此配置添加到你的 docker-compose.yml 中
|
||||||
|
# 2. 确保你的配置文件(config.json)包含数据库连接信息
|
||||||
|
# 3. 修改配置后,手动执行迁移:docker-compose exec app ./migrate up
|
||||||
|
# 4. 无需重启容器!
|
||||||
|
|
||||||
149
templates/migrate/main.go
Normal file
149
templates/migrate/main.go
Normal file
@@ -0,0 +1,149 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"flag"
|
||||||
|
"fmt"
|
||||||
|
"os"
|
||||||
|
|
||||||
|
"git.toowon.com/jimmy/go-common/migration"
|
||||||
|
)
|
||||||
|
|
||||||
|
// 数据库迁移工具(黑盒模式)
|
||||||
|
//
|
||||||
|
// 工作原理:
|
||||||
|
// 此工具调用 migration.RunMigrationsFromConfigWithCommand() 方法,
|
||||||
|
// 内部自动处理配置加载、数据库连接、迁移执行等所有细节。
|
||||||
|
// 你只需要提供配置文件和SQL迁移文件即可。
|
||||||
|
//
|
||||||
|
// 使用方式:
|
||||||
|
// 基本用法:
|
||||||
|
// ./migrate up # 使用默认配置
|
||||||
|
// ./migrate up -config /path/to/config.json # 指定配置文件
|
||||||
|
// ./migrate up -config config.json -dir db/migrations # 指定配置和迁移目录
|
||||||
|
// ./migrate status # 查看迁移状态
|
||||||
|
// ./migrate down # 回滚最后一个迁移
|
||||||
|
//
|
||||||
|
// Docker 中使用:
|
||||||
|
// # 方式1:挂载配置文件(推荐)
|
||||||
|
// docker run -v /host/config.json:/app/config.json myapp ./migrate up
|
||||||
|
//
|
||||||
|
// # 方式2:使用环境变量指定配置文件路径
|
||||||
|
// docker run -e CONFIG_FILE=/etc/app/config.json myapp ./migrate up
|
||||||
|
//
|
||||||
|
// # 方式3:指定容器内的配置文件路径
|
||||||
|
// docker run myapp ./migrate up -config /etc/app/config.json
|
||||||
|
//
|
||||||
|
// 支持的命令:
|
||||||
|
// up - 执行所有待执行的迁移
|
||||||
|
// down - 回滚最后一个迁移
|
||||||
|
// status - 查看迁移状态
|
||||||
|
//
|
||||||
|
// 配置优先级(从高到低):
|
||||||
|
// 1. 命令行参数 -config 和 -dir
|
||||||
|
// 2. 环境变量 CONFIG_FILE 和 MIGRATIONS_DIR
|
||||||
|
// 3. 默认值(config.json 和 migrations)
|
||||||
|
|
||||||
|
var (
|
||||||
|
configFile string
|
||||||
|
migrationsDir string
|
||||||
|
showHelp bool
|
||||||
|
)
|
||||||
|
|
||||||
|
func init() {
|
||||||
|
flag.StringVar(&configFile, "config", "", "配置文件路径(默认:config.json 或环境变量 CONFIG_FILE)")
|
||||||
|
flag.StringVar(&configFile, "c", "", "配置文件路径(简写)")
|
||||||
|
flag.StringVar(&migrationsDir, "dir", "", "迁移文件目录(默认:migrations 或环境变量 MIGRATIONS_DIR)")
|
||||||
|
flag.StringVar(&migrationsDir, "d", "", "迁移文件目录(简写)")
|
||||||
|
flag.BoolVar(&showHelp, "help", false, "显示帮助信息")
|
||||||
|
flag.BoolVar(&showHelp, "h", false, "显示帮助信息(简写)")
|
||||||
|
}
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
flag.Parse()
|
||||||
|
|
||||||
|
// 显示帮助
|
||||||
|
if showHelp {
|
||||||
|
printHelp()
|
||||||
|
os.Exit(0)
|
||||||
|
}
|
||||||
|
|
||||||
|
// 获取命令(默认up)
|
||||||
|
// 支持两种方式:
|
||||||
|
// 1. 位置参数:./migrate up
|
||||||
|
// 2. 标志参数:./migrate -cmd=up(向后兼容)
|
||||||
|
command := "up"
|
||||||
|
args := flag.Args()
|
||||||
|
if len(args) > 0 {
|
||||||
|
command = args[0]
|
||||||
|
}
|
||||||
|
|
||||||
|
// 验证命令
|
||||||
|
if command != "up" && command != "down" && command != "status" {
|
||||||
|
fmt.Fprintf(os.Stderr, "错误:未知命令 '%s'\n\n", command)
|
||||||
|
printHelp()
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
|
||||||
|
// 获取配置文件路径(优先级:命令行 > 环境变量 > 默认值)
|
||||||
|
// 如果未指定,RunMigrationsFromConfigWithCommand 会自动查找
|
||||||
|
if configFile == "" {
|
||||||
|
configFile = getEnv("CONFIG_FILE", "")
|
||||||
|
}
|
||||||
|
|
||||||
|
// 获取迁移目录(优先级:命令行 > 环境变量 > 默认值)
|
||||||
|
// 如果未指定,RunMigrationsFromConfigWithCommand 会使用默认值 "migrations"
|
||||||
|
if migrationsDir == "" {
|
||||||
|
migrationsDir = getEnv("MIGRATIONS_DIR", "")
|
||||||
|
}
|
||||||
|
|
||||||
|
// 执行迁移(黑盒模式:内部自动处理所有细节)
|
||||||
|
if err := migration.RunMigrationsFromConfigWithCommand(configFile, migrationsDir, command); err != nil {
|
||||||
|
fmt.Fprintf(os.Stderr, "错误: %v\n", err)
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func getEnv(key, defaultValue string) string {
|
||||||
|
if value := os.Getenv(key); value != "" {
|
||||||
|
return value
|
||||||
|
}
|
||||||
|
return defaultValue
|
||||||
|
}
|
||||||
|
|
||||||
|
func printHelp() {
|
||||||
|
fmt.Println("数据库迁移工具")
|
||||||
|
fmt.Println()
|
||||||
|
fmt.Println("用法:")
|
||||||
|
fmt.Println(" migrate [命令] [选项]")
|
||||||
|
fmt.Println()
|
||||||
|
fmt.Println("命令:")
|
||||||
|
fmt.Println(" up 执行所有待执行的迁移(默认)")
|
||||||
|
fmt.Println(" down 回滚最后一个迁移")
|
||||||
|
fmt.Println(" status 查看迁移状态")
|
||||||
|
fmt.Println()
|
||||||
|
fmt.Println("选项:")
|
||||||
|
fmt.Println(" -config, -c 配置文件路径(默认: config.json)")
|
||||||
|
fmt.Println(" -dir, -d 迁移文件目录(默认: migrations)")
|
||||||
|
fmt.Println(" -help, -h 显示帮助信息")
|
||||||
|
fmt.Println()
|
||||||
|
fmt.Println("示例:")
|
||||||
|
fmt.Println(" # 使用默认配置")
|
||||||
|
fmt.Println(" migrate up")
|
||||||
|
fmt.Println()
|
||||||
|
fmt.Println(" # 指定配置文件")
|
||||||
|
fmt.Println(" migrate up -config /etc/app/config.json")
|
||||||
|
fmt.Println()
|
||||||
|
fmt.Println(" # 指定配置和迁移目录")
|
||||||
|
fmt.Println(" migrate up -c config.json -d db/migrations")
|
||||||
|
fmt.Println()
|
||||||
|
fmt.Println(" # 使用环境变量指定配置文件路径")
|
||||||
|
fmt.Println(" CONFIG_FILE=/etc/app/config.json migrate up")
|
||||||
|
fmt.Println()
|
||||||
|
fmt.Println(" # Docker 中使用(挂载配置文件)")
|
||||||
|
fmt.Println(" docker run -v /host/config.json:/app/config.json myapp migrate up")
|
||||||
|
fmt.Println()
|
||||||
|
fmt.Println("配置优先级(从高到低):")
|
||||||
|
fmt.Println(" 1. 命令行参数 -config 和 -dir")
|
||||||
|
fmt.Println(" 2. 环境变量 CONFIG_FILE 和 MIGRATIONS_DIR")
|
||||||
|
fmt.Println(" 3. 默认值(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