9 Commits

60 changed files with 3210 additions and 11024 deletions

1
.gitignore vendored
View File

@@ -1 +1,2 @@
.cursor .cursor
.DS_Store

429
INTEGRATION.md Normal file
View File

@@ -0,0 +1,429 @@
# GoCommon 业务项目对接操作手册
本文档供**引用 GoCommon 的业务项目**使用。按本手册对接即可,无需重复沟通基础设施实现方式。
模块路径:`git.toowon.com/jimmy/go-common`
> 本文档只描述**目标架构**,重构时一步到位,**不提供过渡期用法,不考虑向后兼容**。
---
## 1. 对接原则
| 原则 | 说明 |
|------|------|
| Factory 只是入口 | 启动时初始化一次,通过 getter 获取各模块**对象** |
| 能力在模块自身 | 使用 `log.Info()``db.Find()``store.Upload()`,不在 Factory 上堆透传方法 |
| 按需引用 | 用什么模块取什么对象;无状态工具直接 `import tools` |
| 不重写基础设施 | 数据库连接、Redis 客户端、统一 HTTP 出参、中间件链由 GoCommon 提供 |
| 业务只管业务 | Service 返回数据Handler 交给 `http.Handler` 出参Migration 只写 SQL 文件 |
---
## 2. 环境准备
### 2.1 配置私有模块
```bash
go env -w GOPRIVATE=git.toowon.com
go env -w GONOPROXY=git.toowon.com
go env -w GONOSUMDB=git.toowon.com
```
### 2.2 Git 认证SSH 推荐)
```bash
git config --global url."git@git.toowon.com:".insteadOf "https://git.toowon.com/"
```
### 2.3 安装依赖
```bash
go get git.toowon.com/jimmy/go-common@v2.0.0
```
`go.mod` 中:
```go
require git.toowon.com/jimmy/go-common v2.0.0
```
配置示例见 [`config/example.json`](./config/example.json)。
---
## 3. 推荐项目结构
```text
your-project/
├── config.json
├── cmd/
│ ├── server/main.go
│ └── migrate/main.go # 从 templates/migrate/main.go 复制
├── migrations/
│ └── 20240101000001_create_users.sql
├── locales/ # i18n可选
│ ├── zh-CN.json
│ └── en-US.json
├── internal/
│ ├── handler/
│ └── service/
└── go.mod
```
---
## 4. 启动初始化(只做一次)
```go
package main
import (
"log"
"net/http"
"git.toowon.com/jimmy/go-common/factory"
)
func main() {
if err := factory.Init("config.json"); err != nil {
log.Fatal(err)
}
app := factory.Default()
chain := app.MiddlewareChain()
chain.Append(yourAuthMiddleware)
userSvc, err := NewUserService(app)
if err != nil {
log.Fatal(err)
}
http.Handle("/api/users", chain.ThenFunc(func(w http.ResponseWriter, r *http.Request) {
listUsers(w, r, userSvc, app)
}))
log.Fatal(http.ListenAndServe(":8080", nil))
}
```
**禁止**在每个 Handler 里 `NewFromFile` / `Init`。全局只初始化一次,通过 `factory.Default()` 或注入 `*factory.Factory`
---
## 5. 获取模块对象Factory getter
连接与客户端由 Factory **lazy 初始化并缓存**。业务侧**不要**自行 `gorm.Open` / `redis.NewClient`
| 模块 | API | 用法 |
|------|-----|------|
| 配置 | `app.Config()` | 读原始配置 |
| 数据库 | `app.Database()` | `db.Find(&users)``db.Transaction(...)` |
| Redis | `app.Redis()` | `rds.Set(ctx, key, val, ttl)` |
| 日志 | `app.Logger()` | `log.Info(...)`,退出前 `log.Close()` |
| 存储 | `app.Storage()` | `store.Upload(ctx, key, reader)` |
| 邮件 | `app.Email()` | `mail.SendEmail(...)` |
| 短信 | `app.SMS()` | `sms.SendSMS(...)` |
| Excel | `app.Excel()` | `ex.ExportToFile(...)` |
| 国际化 | `app.I18n()` | 供 `http.Handler` 注入;或 `i18n.GetMessage(...)` |
| 中间件链 | `app.MiddlewareChain()` | `chain.Append(...).ThenFunc(...)` |
| 迁移 | `app.Migrator("migrations")` | `m.Up()` / `m.Status()` / `m.Down()` |
### 注入 Service 示例
```go
type UserService struct {
db *gorm.DB
rds *redis.Client
}
func NewUserService(app *factory.Factory) (*UserService, error) {
db, err := app.Database()
if err != nil {
return nil, err
}
rds, err := app.Redis()
if err != nil {
return nil, err
}
return &UserService{db: db, rds: rds}, nil
}
func (s *UserService) List(page, size int) (users []User, total int64, err error) {
s.db.Model(&User{}).Count(&total)
err = s.db.Offset((page-1)*size).Limit(size).Find(&users).Error
return
}
```
`config.json` 未配置的模块,调用 getter 会返回错误——**只配置使用的模块即可**。
---
## 6. HTTP 统一出参
### 6.1 职责划分
| 层级 | 做什么 |
|------|--------|
| Service | 返回 `[]User``total`、业务 error |
| Handler | 解析请求、调 Service、通过 `http.Handler` 出参 |
| `http.Handler` | PageData → Response → JSON结构 / 编码 / 语种 / 时间统一) |
**禁止**在 Service 拼 JSON**禁止**在业务项目自定义 `Response` 结构,**禁止**经 Factory 出参(无 `app.Success` / `app.Error`)。
### 6.2 标准响应格式
```json
{
"code": 0,
"message": "success",
"timestamp": 1704067200,
"data": {}
}
```
分页时 `data`
```json
{
"list": [],
"total": 100,
"page": 1,
"pageSize": 20
}
```
类型定义在 `http` 包:`http.Response``http.PageData`
### 6.3 Handler 用法(唯一方式)
中间件链须包含 `Language``Timezone``MiddlewareChain()` 已默认组装)。
```go
import commonhttp "git.toowon.com/jimmy/go-common/http"
func listUsers(w http.ResponseWriter, r *http.Request, svc *UserService, app *factory.Factory) {
i18n, _ := app.I18n()
h := commonhttp.NewHandler(w, r, commonhttp.WithI18n(i18n))
var req ListUserRequest
if err := h.ParseJSON(&req); err != nil {
h.Error("common.invalid_request")
return
}
p := h.Pagination()
users, total, err := svc.List(p.GetPage(), p.GetPageSize())
if err != nil {
h.Error("user.list_failed")
return
}
h.SuccessPage(users, total)
}
```
`http.Handler` 统一负责:
- `Content-Type: application/json; charset=utf-8`
- 从 context 读取语种、时区
- 消息码(如 `user.not_found`)经 i18n 转为文案与业务 code
- `timestamp` 按统一时区策略写入
### 6.4 请求头约定
| Header | 用途 |
|--------|------|
| `Accept-Language` | 响应消息语种 |
| `X-Timezone` | 时区(默认 `Asia/Shanghai` |
---
## 7. 数据库迁移
执行框架已封装,业务**只写 SQL 文件**。
### 7.1 推荐:独立 migrate 命令(与 Web 解耦)
```bash
cp templates/migrate/main.go cmd/migrate/main.go
go build -o bin/migrate cmd/migrate/main.go
./bin/migrate up
./bin/migrate status
./bin/migrate down
./bin/migrate up -config config.json -dir migrations
```
```sql
-- migrations/20240101000001_create_users.sql
CREATE TABLE users (
id BIGINT PRIMARY KEY AUTO_INCREMENT,
username VARCHAR(255) NOT NULL
);
```
```sql
-- migrations/20240101000001_create_users.down.sql
DROP TABLE IF EXISTS users;
```
独立 CLI 内部调用 `migration.RunMigrationsFromConfigWithCommand`,无需业务实现连接逻辑。
### 7.2 可选:经 Factory开发 / 小项目)
```go
m, err := app.Migrator("migrations")
if err != nil {
log.Fatal(err)
}
if err := m.Up(); err != nil {
log.Fatal(err)
}
```
### 7.3 Docker
```yaml
command: sh -c "./bin/migrate up && ./bin/server"
volumes:
- ./config.json:/app/config.json:ro
- ./migrations:/app/migrations:ro
```
---
## 8. 各模块按需对接
### 8.1 日志
```go
log, _ := app.Logger()
defer log.Close()
log.Info("服务启动")
```
### 8.2 存储
```go
store, _ := app.Storage()
store.Upload(ctx, "images/a.jpg", fileReader, "image/jpeg")
url, _ := store.GetURL("images/a.jpg", 3600)
```
不经 Factory 时:`storage.NewStorage(storage.StorageTypeLocal, cfg)`
### 8.3 邮件 / 短信
```go
mail, _ := app.Email()
defer mail.Close()
// HTTP 通知类:异步,不阻塞请求
mail.SendEmailAsync(r.Context(), []string{"a@b.com"}, "主题", "正文")
// 验证码等需等待结果:同步
mail.SendEmail([]string{"a@b.com"}, "主题", "正文")
sms, _ := app.SMS()
defer sms.Close()
sms.SendSMSAsync(r.Context(), []string{"13800138000"}, map[string]string{"code": "123456"})
sms.SendSMS([]string{"13800138000"}, map[string]string{"code": "123456"})
```
### 8.4 Excel
```go
ex := app.Excel()
ex.ExportToFile("users.xlsx", "用户列表", columns, users)
```
### 8.5 国际化
```go
i18n, _ := app.I18n()
i18n.LoadFromDir("locales")
msg := i18n.GetMessage("zh-CN", "user.not_found")
```
HTTP 出参的 i18n 通过 `NewHandler(..., WithI18n(i18n))` 注入Handler 内用消息码调用 `h.Error("user.not_found")`
### 8.6 无状态工具(不经 Factory
```go
import "git.toowon.com/jimmy/go-common/tools"
tools.Now()
tools.MD5("text")
tools.YuanToCents(100.5)
```
---
## 9. config.json 最小示例
```json
{
"database": {
"type": "mysql",
"host": "localhost",
"port": 3306,
"user": "root",
"password": "password",
"database": "mydb"
},
"logger": {
"level": "info",
"output": "both",
"filePath": "./logs/app.log",
"async": true
},
"i18n": {
"defaultLang": "zh-CN",
"localesDir": "locales"
}
}
```
完整字段见 [`config/example.json`](./config/example.json)。
---
## 10. 反模式(禁止)
- 每个 Handler 内 `factory.Init` / `NewFromFile`
- 业务 Service 内写 HTTP JSON 响应
- 自行 `gorm.Open` / `redis.NewClient`
- 使用 Factory 透传:`LogInfo``RedisSet``Success``Error``Now``MD5`
- 直接调用 `http.Success(w, ...)` 包级函数(应使用 `http.Handler`
- 在业务项目复制 GoCommon 的 Response / 中间件实现
---
## 11. 故障排除
**无法下载模块:**
```bash
go env -w GOPRIVATE=git.toowon.com
git config --global url."git@git.toowon.com:".insteadOf "https://git.toowon.com/"
go get git.toowon.com/jimmy/go-common@latest
```
**依赖错误:** `go clean -modcache && go mod tidy`
**getter 报 config is nil** 补充 `config.json` 对应段,或不调用该 getter
**迁移找不到文件:** 检查 `-dir` 与 SQL 文件命名
---
## 12. 文档与版本
| 文档 | 用途 |
|------|------|
| 本文档 | 业务项目对接 |
| [README.md](./README.md) | 库概述 |
| [VERSION.md](./VERSION.md) | 版本发布 |
版本升级见 [VERSION.md](./VERSION.md)。

View File

@@ -1,580 +0,0 @@
# 数据库迁移工具 - 完整指南
## 📌 核心特点
-**独立工具,零耦合** - 与应用代码完全分离
-**生产就绪** - 编译成二进制无需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友好修改配置无需重启
**开箱即用,灵活强大!** 🎉

View File

@@ -1,346 +0,0 @@
# 快速开始指南
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/) - 查看更多实际示例

428
README.md
View File

@@ -1,404 +1,56 @@
# GoCommon - Go通用工具类库 # GoCommon - Go 通用工具类库
这是一个Go语言开发的通用工具类库其他Go项目提供常用的工具方法集合。 其他 Go 项目引用的通用工具集合。业务项目对接请直接阅读:
**📖 快速链接** **[业务项目对接操作手册INTEGRATION.md](./INTEGRATION.md)**
- [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)
提供数据库迁移功能支持MySQL、PostgreSQL、SQLite等数据库。
**🎯 独立工具,零耦合**
- ✅ 编译成独立二进制:`go build -o bin/migrate cmd/migrate/main.go`
- ✅ 生产环境无需Go环境只需二进制文件
- ✅ 与应用代码完全解耦,可独立部署和执行
- ✅ 支持宿主机和Docker零额外配置
### 2. 日期转换工具 (datetime)
提供日期时间转换功能,支持时区设定和多种格式转换。
### 3. HTTP Restful工具 (http)
提供HTTP请求/响应处理工具包含标准化的响应结构、分页支持和HTTP状态码与业务状态码的分离。
### 4. 中间件工具 (middleware)
提供生产级HTTP中间件包括
- **CORS** - 跨域资源共享
- **Timezone** - 时区处理
- **Logging** - 请求日志记录(支持异步)
- **Recovery** - Panic恢复防止服务崩溃
- **RateLimit** - 请求限流(令牌桶算法)
- **Chain** - 中间件链式组合
### 5. 配置工具 (config)
提供从外部文件加载配置的功能支持数据库、OSS、Redis、CORS、MinIO等配置。
### 6. 存储工具 (storage)
提供文件上传和查看功能支持OSS和MinIO两种存储方式并提供HTTP处理器。
### 7. 邮件工具 (email)
提供SMTP邮件发送功能支持纯文本和HTML邮件使用Go标准库实现。
### 8. 短信工具 (sms)
提供阿里云短信发送功能支持模板短信和批量发送使用Go标准库实现。
### 9. 工厂工具 (factory)
提供从配置文件直接创建已初始化客户端对象的功能包括数据库、Redis、邮件、短信、日志等避免调用方重复实现创建逻辑。
### 10. 日志工具 (logger)
提供统一的日志记录功能支持多种日志级别和输出方式使用Go标准库实现。
---
## 🎯 Factory 黑盒模式(核心设计)
**理念**:外部项目只需传递一个配置文件路径,直接使用黑盒方法,无需获取内部对象。
### 方法分类
| 类型 | 方法 | 使用方式 | 推荐度 |
|------|------|----------|--------|
| **黑盒方法(推荐)** | | | |
| 中间件 | `GetMiddlewareChain()` | 直接使用可Append自定义中间件 | ⭐⭐⭐ |
| 日志 | `LogInfo()`, `LogError()` 等 | 直接调用无需获取logger对象 | ⭐⭐⭐ |
| Redis | `RedisSet()`, `RedisGet()` 等 | 直接调用,覆盖常用操作 | ⭐⭐⭐ |
| 邮件 | `SendEmail()` | 直接调用 | ⭐⭐⭐ |
| 短信 | `SendSMS()` | 直接调用 | ⭐⭐⭐ |
| 存储 | `UploadFile()`, `GetFileURL()` | 直接调用 | ⭐⭐⭐ |
| **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")
``` ```
git.toowon.com/jimmy/go-common
--- ```
## 安装 ## 安装
### 1. 配置私有仓库(重要)
由于本项目使用私有 Git 仓库,需要先配置 `GOPRIVATE` 环境变量:
```bash ```bash
# 使用 go env 命令配置(推荐,永久生效)
go env -w GOPRIVATE=git.toowon.com go env -w GOPRIVATE=git.toowon.com
go get git.toowon.com/jimmy/go-common@v2.0.0
# 验证配置
go env GOPRIVATE
``` ```
**详细配置说明请参考 [SETUP.md](./SETUP.md)** ## 设计概要
**遇到问题?请查看 [故障排除指南](./TROUBLESHOOTING.md)** - **Factory**:入口,启动时初始化一次,按需 getter 获取模块对象DB、Redis、Logger 等)
- **各模块包**:能力在对象方法上(`log.Info()``store.Upload()`
### 2. 安装模块 - **http 包**:统一 HTTP 出参Response / PageData / Handler
- **migration**:独立 CLI 或 Factory 执行 SQL 迁移
```bash - **tools**:无状态工具函数,直接 import
# 安装最新版本(推荐用于开发)
go get git.toowon.com/jimmy/go-common@latest ## 功能模块
# 安装特定版本(推荐用于生产) | 模块 | 包路径 | 说明 |
go get git.toowon.com/jimmy/go-common@v1.0.0 |------|--------|------|
``` | 配置 | `config` | JSON 配置加载 |
| 工厂 | `factory` | 统一入口与 lazy getter |
**版本管理说明请参考 [VERSION.md](./VERSION.md)** | HTTP | `http` | 请求解析、统一响应 |
| 中间件 | `middleware` | CORS、日志、Recovery、限流、语种、时区 |
--- | 工具 | `tools` | 时间、加密、金额、类型转换 |
| 日志 | `logger` | 异步日志 |
## 📚 文档导航 | 存储 | `storage` | Local / OSS / MinIO |
| 邮件 / 短信 | `email` / `sms` | SMTP、阿里云短信 |
- **[快速开始指南](./QUICKSTART.md)** ⭐ - 5分钟快速上手 | Excel | `excel` | 数据导出 |
- [完整文档](./docs/README.md) - 所有模块详细文档 | 国际化 | `i18n` | 多语言消息 |
- [故障排除](./TROUBLESHOOTING.md) - 常见问题解决 | 迁移 | `migration` | SQL 版本管理 |
- [版本管理](./VERSION.md) - 版本发布说明
## 文档
---
| 文档 | 说明 |
## 快速开始 |------|------|
| [INTEGRATION.md](./INTEGRATION.md) | 业务项目对接操作手册 |
### 1. 创建配置文件 `config.json` | [VERSION.md](./VERSION.md) | 版本管理与发布 |
| [templates/](./templates/) | migrate 等脚手架模板 |
```json | [config/example.json](./config/example.json) | 配置文件示例 |
{ | [examples/](./examples/) | 代码示例 |
"database": {
"type": "mysql",
"host": "localhost",
"port": 3306,
"user": "root",
"password": "password",
"database": "mydb"
},
"redis": {
"host": "localhost",
"port": 6379
},
"logger": {
"level": "info",
"output": "both",
"filePath": "./logs/app.log",
"async": true
}
}
```
### 2. 使用工厂黑盒模式(最简单,推荐)⭐
```go
package main
import (
"context"
"net/http"
"time"
"git.toowon.com/jimmy/go-common/factory"
commonhttp "git.toowon.com/jimmy/go-common/http"
)
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")
// 数据库(高级功能)
db, _ := fac.GetDatabase()
db.Find(&users)
```
### HTTP处理器
```go
import commonhttp "git.toowon.com/jimmy/go-common/http"
func GetUser(h *commonhttp.Handler) {
id := h.GetQueryInt64("id", 0)
h.Success(data)
}
http.HandleFunc("/user", commonhttp.HandleFunc(GetUser))
```
### 日期时间
**推荐方式:通过 factory 使用(黑盒模式)**
```go
import "git.toowon.com/jimmy/go-common/factory"
fac, _ := factory.NewFactoryFromFile("config.json")
now := fac.Now("Asia/Shanghai")
str := fac.FormatDateTime(now)
```
**或者直接使用 tools 包:**
```go
import "git.toowon.com/jimmy/go-common/tools"
tools.SetDefaultTimeZone(tools.AsiaShanghai)
now := tools.Now()
str := tools.FormatDateTime(now)
```
更多示例:[examples目录](./examples/)
## 版本管理
当前版本:**v1.0.0**
### 如何指定版本
`go.mod` 文件中指定版本:
```go
require (
git.toowon.com/jimmy/go-common v1.0.0
)
```
或者使用命令行:
```bash
# 使用最新版本
go get git.toowon.com/jimmy/go-common@latest
# 使用特定版本
go get git.toowon.com/jimmy/go-common@v1.0.0
```
**详细版本管理说明请参考 [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 MIT License
## 联系方式
- 作者Jimmy
- 邮箱jimmy@toowon.com
- 项目地址git.toowon.com/jimmy/go-common
---
⭐ 如果这个项目对你有帮助,请给个 Star

174
SETUP.md
View File

@@ -1,174 +0,0 @@
# 项目配置说明
## GOPRIVATE 环境变量配置
由于本项目使用私有 Git 仓库 (`git.toowon.com`),需要配置 `GOPRIVATE` 环境变量,让 Go 工具链知道这些模块是私有的,不要通过公共代理下载。
### 配置方法
#### 方法一:临时配置(当前终端会话有效)
```bash
# macOS/Linux
export GOPRIVATE=git.toowon.com
# Windows (PowerShell)
$env:GOPRIVATE="git.toowon.com"
# Windows (CMD)
set GOPRIVATE=git.toowon.com
```
#### 方法二:永久配置(推荐)
**macOS/Linux:**
1. 编辑 shell 配置文件(根据你使用的 shell 选择):
```bash
# 如果是 zshmacOS 默认)
nano ~/.zshrc
# 如果是 bash
nano ~/.bashrc
# 或
nano ~/.bash_profile
```
2. 添加以下内容:
```bash
export GOPRIVATE=git.toowon.com
```
3. 保存文件并重新加载配置:
```bash
# zsh
source ~/.zshrc
# bash
source ~/.bashrc
```
**Windows:**
1. 打开"系统属性" -> "高级" -> "环境变量"
2. 在"用户变量"或"系统变量"中点击"新建"
3. 变量名:`GOPRIVATE`
4. 变量值:`git.toowon.com`
5. 点击"确定"保存
#### 方法三:使用 go env 命令推荐Go 1.13+
```bash
# 设置 GOPRIVATE
go env -w GOPRIVATE=git.toowon.com
# 查看当前配置
go env GOPRIVATE
# 如果需要设置多个私有仓库,用逗号分隔
go env -w GOPRIVATE=git.toowon.com,github.com/your-org
```
### 验证配置
```bash
# 查看 GOPRIVATE 配置
go env GOPRIVATE
# 应该输出: git.toowon.com
```
### 其他相关环境变量(可选)
如果需要更细粒度的控制,还可以配置:
```bash
# GOPRIVATE: 私有模块,不通过代理下载,不校验 checksum
go env -w GOPRIVATE=git.toowon.com
# GONOPROXY: 不通过代理下载的模块(默认与 GOPRIVATE 相同)
go env -w GONOPROXY=git.toowon.com
# GONOSUMDB: 不校验 checksum 的模块(默认与 GOPRIVATE 相同)
go env -w GONOSUMDB=git.toowon.com
```
### Git 认证配置
由于是私有仓库,还需要配置 Git 认证:
#### 方法一:使用 SSH推荐
1. 确保已配置 SSH 密钥
2. 使用 SSH URL
```bash
git config --global url."git@git.toowon.com:".insteadOf "https://git.toowon.com/"
```
#### 方法二:使用 HTTPS + 个人访问令牌
1. 在 Git 服务器上生成个人访问令牌
2. 配置 Git 凭据:
```bash
git config --global credential.helper store
```
3. 首次访问时会提示输入用户名和令牌
#### 方法三:在 URL 中包含凭据(不推荐,安全性较低)
```bash
# 在 go.mod 中使用(不推荐)
# 或者通过 .netrc 文件配置
```
### 常见问题
#### 问题1go get 失败,提示找不到模块
**解决方案:**
1. 确认 GOPRIVATE 已正确配置
2. 确认 Git 认证已配置
3. 尝试手动克隆仓库验证:
```bash
git clone git@git.toowon.com:jimmy/go-common.git
```
#### 问题2go mod download 失败
**解决方案:**
```bash
# 清除模块缓存
go clean -modcache
# 重新下载
go mod download
```
#### 问题3IDE 无法识别模块
**解决方案:**
1. 重启 IDE
2. 在 IDE 中执行:`go mod tidy`
3. 确认 IDE 的 Go 环境变量配置正确
### 完整配置示例
```bash
# 1. 配置 GOPRIVATE
go env -w GOPRIVATE=git.toowon.com
# 2. 配置 Git SSH如果使用 SSH
git config --global url."git@git.toowon.com:".insteadOf "https://git.toowon.com/"
# 3. 验证配置
go env | grep GOPRIVATE
# 4. 测试模块下载
go get git.toowon.com/jimmy/go-common@latest
```
### 参考文档
- [Go Modules 官方文档](https://go.dev/ref/mod)
- [Go 私有模块配置](https://go.dev/ref/mod#private-modules)

View File

@@ -1,208 +0,0 @@
# 故障排除指南
## 常见问题
### 1. 伪版本错误 (Pseudo-version error)
**错误信息:**
```
go: github.com/pmezard/go-difflib@v1.1.1-0.20181226105442-5d4384ee4fb2: invalid pseudo-version: preceding tag (v1.1.0) not found
```
**原因:**
- Go 模块缓存损坏
- 依赖版本冲突
- 间接依赖使用了无效的伪版本
**解决方案:**
#### 方案1清理模块缓存推荐
```bash
# 清理 Go 模块缓存
go clean -modcache
# 重新下载依赖
go mod download
# 整理依赖
go mod tidy
```
#### 方案2在调用方项目中解决
如果是在调用方项目中遇到此问题:
```bash
# 进入调用方项目目录
cd /path/to/your/project
# 清理模块缓存
go clean -modcache
# 删除 go.sum 文件(可选,会自动重新生成)
rm go.sum
# 重新获取依赖
go get git.toowon.com/jimmy/go-common@v0.0.1
# 整理依赖
go mod tidy
```
#### 方案3使用代理如果网络问题
```bash
# 设置 Go 代理(国内用户推荐)
go env -w GOPROXY=https://goproxy.cn,direct
# 或者使用官方代理
go env -w GOPROXY=https://proxy.golang.org,direct
```
#### 方案4强制更新依赖
```bash
# 强制更新所有依赖
go get -u ./...
# 或者更新特定依赖
go get -u git.toowon.com/jimmy/go-common@latest
```
### 2. 私有仓库访问问题
**错误信息:**
```
go: git.toowon.com/jimmy/go-common@v0.0.1: unrecognized import path
```
**解决方案:**
```bash
# 配置 GOPRIVATE
go env -w GOPRIVATE=git.toowon.com
# 配置 Git 认证(如果需要)
git config --global url."git@git.toowon.com:".insteadOf "https://git.toowon.com/"
```
详细说明请参考 [SETUP.md](./SETUP.md)
### 3. 版本标签不存在
**错误信息:**
```
go: git.toowon.com/jimmy/go-common@v0.0.1: invalid version: unknown revision
```
**解决方案:**
1. 确认版本标签已创建并推送:
```bash
# 在库项目中查看标签
git tag -l
# 如果标签不存在,创建并推送
git tag -a v0.0.1 -m "Release v0.0.1"
git push origin v0.0.1
```
2. 在调用方项目中清理缓存后重试:
```bash
go clean -modcache
go get git.toowon.com/jimmy/go-common@v0.0.1
```
### 4. 依赖版本冲突
**错误信息:**
```
go: conflicting versions for module
```
**解决方案:**
```bash
# 查看依赖树
go mod graph | grep conflicting-module
# 更新冲突的依赖
go get -u conflicting-module@latest
# 整理依赖
go mod tidy
```
### 5. 网络连接问题
**错误信息:**
```
dial tcp: lookup proxy.golang.org: no such host
```
**解决方案:**
```bash
# 使用国内代理
go env -w GOPROXY=https://goproxy.cn,direct
# 或者使用七牛云代理
go env -w GOPROXY=https://goproxy.io,direct
# 禁用代理(直接访问)
go env -w GOPROXY=direct
```
## 通用排查步骤
如果遇到其他问题,按以下步骤排查:
1. **清理缓存**
```bash
go clean -modcache
```
2. **验证模块**
```bash
go mod verify
```
3. **整理依赖**
```bash
go mod tidy
```
4. **查看依赖图**
```bash
go mod graph
```
5. **查看模块信息**
```bash
go list -m all
```
6. **检查 Go 环境**
```bash
go env
```
## 获取帮助
如果以上方法都无法解决问题,请:
1. 检查 Go 版本(建议使用 Go 1.21 或更高版本)
```bash
go version
```
2. 查看详细的错误信息
```bash
go get -v git.toowon.com/jimmy/go-common@v0.0.1
```
3. 检查项目仓库是否有对应的版本标签
4. 联系项目维护者

View File

@@ -121,11 +121,23 @@ go get -u=minor git.toowon.com/jimmy/go-common
## 当前版本 ## 当前版本
当前版本:**v1.0.0** 当前版本:**v2.0.0**
## 版本历史 ## 版本历史
- **v1.0.0** (当前版本) - **v2.0.0** (当前版本Breaking)
- Factory 精简为 `Init` / `Default()` + lazy getter删除全部透传方法
- HTTP 出参统一由 `http.Handler` 负责,删除包级 `Success` / `SystemError`
- Logger API 精简为 `Debug/Info/Error(msg, fields)`,新增 Request ID + `FromContext`
- email / sms 新增异步队列 + `Close()`
- 中间件链默认顺序Recovery → RequestID → Logging → …
- **v1.0.0**
- 初始版本 - 初始版本
- 包含所有基础工具类migration、datetime、http、middleware、config、storage、email、sms、factory、logger - 包含所有基础工具类migration、datetime、http、middleware、config、storage、email、sms、factory、logger
- **v1.1.0** (未发布)
- storage新增本地文件夹存储LocalStorage
- config新增 `localStorage` 配置段
- factory支持 Local/MinIO/OSS 自动选择

View File

@@ -9,15 +9,38 @@ import (
// Config 应用配置 // Config 应用配置
type Config struct { type Config struct {
Database *DatabaseConfig `json:"database"` Database *DatabaseConfig `json:"database"`
OSS *OSSConfig `json:"oss"` OSS *OSSConfig `json:"oss"`
Redis *RedisConfig `json:"redis"` Redis *RedisConfig `json:"redis"`
CORS *CORSConfig `json:"cors"` CORS *CORSConfig `json:"cors"`
MinIO *MinIOConfig `json:"minio"` MinIO *MinIOConfig `json:"minio"`
Email *EmailConfig `json:"email"` Local *LocalStorageConfig `json:"localStorage"`
SMS *SMSConfig `json:"sms"` Email *EmailConfig `json:"email"`
Logger *LoggerConfig `json:"logger"` SMS *SMSConfig `json:"sms"`
RateLimit *RateLimitConfig `json:"rateLimit"` Logger *LoggerConfig `json:"logger"`
I18n *I18nConfig `json:"i18n"`
RateLimit *RateLimitConfig `json:"rateLimit"`
}
// I18nConfig 国际化配置
type I18nConfig struct {
DefaultLang string `json:"defaultLang"`
LocalesDir string `json:"localesDir"`
}
// LocalStorageConfig 本地存储配置
// 用于将文件保存到本地文件夹(适合开发环境、单机部署等场景)
type LocalStorageConfig struct {
// BaseDir 本地文件保存根目录(必填)
// 示例: "./uploads" 或 "/var/app/uploads"
BaseDir string `json:"baseDir"`
// PublicURL 对外访问URL可选
// 1) 若包含 "{objectKey}" 占位符,则会替换为 url.QueryEscape(objectKey)
// 示例: "http://localhost:8080/file?key={objectKey}" (配合 ProxyHandler 使用)
// 2) 若不包含占位符则作为URL前缀自动拼接 objectKey
// 示例: "http://localhost:8080/static/" => "http://localhost:8080/static/<objectKey>"
PublicURL string `json:"publicURL"`
} }
// DatabaseConfig 数据库配置 // DatabaseConfig 数据库配置
@@ -192,6 +215,23 @@ type EmailConfig struct {
// Timeout 连接超时时间(秒) // Timeout 连接超时时间(秒)
Timeout int `json:"timeout"` Timeout int `json:"timeout"`
// Async 是否异步发送(默认 true省略时启用
Async *bool `json:"async"`
// Workers 异步 worker 数量(默认 2
Workers int `json:"workers"`
// QueueSize 异步队列大小(默认 1000
QueueSize int `json:"queueSize"`
}
// IsAsync 是否启用异步(默认 true
func (c *EmailConfig) IsAsync() bool {
if c == nil || c.Async == nil {
return true
}
return *c.Async
} }
// SMSConfig 短信配置(阿里云短信) // SMSConfig 短信配置(阿里云短信)
@@ -216,11 +256,28 @@ type SMSConfig struct {
// Timeout 请求超时时间(秒) // Timeout 请求超时时间(秒)
Timeout int `json:"timeout"` Timeout int `json:"timeout"`
// Async 是否异步发送(默认 true省略时启用
Async *bool `json:"async"`
// Workers 异步 worker 数量(默认 2
Workers int `json:"workers"`
// QueueSize 异步队列大小(默认 1000
QueueSize int `json:"queueSize"`
}
// IsAsync 是否启用异步(默认 true
func (c *SMSConfig) IsAsync() bool {
if c == nil || c.Async == nil {
return true
}
return *c.Async
} }
// LoggerConfig 日志配置 // LoggerConfig 日志配置
type LoggerConfig struct { type LoggerConfig struct {
// Level 日志级别: debug, info, warn, error // Level 日志级别: debug, info, error
Level string `json:"level"` Level string `json:"level"`
// Output 输出方式: stdout, stderr, file, both // Output 输出方式: stdout, stderr, file, both
@@ -235,16 +292,21 @@ type LoggerConfig struct {
// DisableTimestamp 禁用时间戳 // DisableTimestamp 禁用时间戳
DisableTimestamp bool `json:"disableTimestamp"` DisableTimestamp bool `json:"disableTimestamp"`
// Async 是否使用异步模式(默认false即同步模式 // Async 是否使用异步模式(默认 true省略时启用
// 异步模式日志写入通过channel异步处理不阻塞调用方 Async *bool `json:"async"`
// 同步模式:日志直接写入,会阻塞调用方直到写入完成
Async bool `json:"async"`
// BufferSize 异步模式下的缓冲区大小默认1000 // BufferSize 异步模式下的缓冲区大小默认1000
// 当缓冲区满时,新的日志会阻塞直到有空间
BufferSize int `json:"bufferSize"` BufferSize int `json:"bufferSize"`
} }
// IsAsync 是否启用异步(默认 true
func (c *LoggerConfig) IsAsync() bool {
if c == nil || c.Async == nil {
return true
}
return *c.Async
}
// RateLimitConfig 限流配置 // RateLimitConfig 限流配置
type RateLimitConfig struct { type RateLimitConfig struct {
// Enable 是否启用限流 // Enable 是否启用限流
@@ -368,13 +430,19 @@ func (c *Config) setDefaults() {
// 邮件默认值 // 邮件默认值
if c.Email != nil { if c.Email != nil {
if c.Email.Port == 0 { if c.Email.Port == 0 {
c.Email.Port = 587 // 默认使用587端口TLS c.Email.Port = 587
} }
if c.Email.From == "" { if c.Email.From == "" {
c.Email.From = c.Email.Username c.Email.From = c.Email.Username
} }
if c.Email.Timeout == 0 { if c.Email.Timeout == 0 {
c.Email.Timeout = 30 c.Email.Timeout = 5
}
if c.Email.Workers == 0 {
c.Email.Workers = 2
}
if c.Email.QueueSize == 0 {
c.Email.QueueSize = 1000
} }
} }
@@ -384,7 +452,13 @@ func (c *Config) setDefaults() {
c.SMS.Region = "cn-hangzhou" c.SMS.Region = "cn-hangzhou"
} }
if c.SMS.Timeout == 0 { if c.SMS.Timeout == 0 {
c.SMS.Timeout = 10 c.SMS.Timeout = 5
}
if c.SMS.Workers == 0 {
c.SMS.Workers = 2
}
if c.SMS.QueueSize == 0 {
c.SMS.QueueSize = 1000
} }
} }
@@ -396,6 +470,14 @@ func (c *Config) setDefaults() {
if c.Logger.Output == "" { if c.Logger.Output == "" {
c.Logger.Output = "stdout" c.Logger.Output = "stdout"
} }
if c.Logger.BufferSize == 0 {
c.Logger.BufferSize = 1000
}
}
// i18n 默认值
if c.I18n != nil && c.I18n.DefaultLang == "" {
c.I18n.DefaultLang = "zh-CN"
} }
// 限流默认值 // 限流默认值
@@ -439,6 +521,11 @@ func (c *Config) GetMinIO() *MinIOConfig {
return c.MinIO return c.MinIO
} }
// GetLocalStorage 获取本地存储配置
func (c *Config) GetLocalStorage() *LocalStorageConfig {
return c.Local
}
// GetEmail 获取邮件配置 // GetEmail 获取邮件配置
func (c *Config) GetEmail() *EmailConfig { func (c *Config) GetEmail() *EmailConfig {
return c.Email return c.Email
@@ -454,6 +541,11 @@ func (c *Config) GetLogger() *LoggerConfig {
return c.Logger return c.Logger
} }
// GetI18n 获取国际化配置
func (c *Config) GetI18n() *I18nConfig {
return c.I18n
}
// GetDatabaseDSN 获取数据库连接字符串 // GetDatabaseDSN 获取数据库连接字符串
func (c *Config) GetDatabaseDSN() (string, error) { func (c *Config) GetDatabaseDSN() (string, error) {
if c.Database == nil { if c.Database == nil {
@@ -528,3 +620,8 @@ func (c *Config) GetRedisAddr() string {
// 构建地址 // 构建地址
return fmt.Sprintf("%s:%d", c.Redis.Host, c.Redis.Port) return fmt.Sprintf("%s:%d", c.Redis.Host, c.Redis.Port)
} }
// BoolPtr 返回 bool 指针(用于配置默认值)
func BoolPtr(v bool) *bool {
return &v
}

View File

@@ -50,6 +50,10 @@
"region": "us-east-1", "region": "us-east-1",
"domain": "http://localhost:9000" "domain": "http://localhost:9000"
}, },
"localStorage": {
"baseDir": "./uploads",
"publicURL": "http://localhost:8080/file?key={objectKey}"
},
"email": { "email": {
"host": "smtp.example.com", "host": "smtp.example.com",
"port": 587, "port": 587,

View File

@@ -1,142 +0,0 @@
# GoCommon 工具类库文档
## 目录
- [数据库迁移工具](./migration.md) - 数据库版本管理和迁移
- [完整使用指南](../MIGRATION.md) ⭐ - 独立工具零耦合Docker友好
- [日期转换工具](./datetime.md) - 日期时间处理和时区转换
- [HTTP Restful工具](./http.md) - HTTP请求响应处理和分页
- [中间件工具](./middleware.md) - 生产级HTTP中间件CORS、时区、日志、Recovery、限流
- [配置工具](./config.md) - 外部配置文件加载和管理
- [存储工具](./storage.md) - 文件上传和查看OSS、MinIO
- [邮件工具](./email.md) - SMTP邮件发送
- [短信工具](./sms.md) - 阿里云短信发送
- [工厂工具](./factory.md) - 从配置直接创建已初始化客户端对象
- [日志工具](./logger.md) - 统一的日志记录功能
## 快速开始
### 安装
```bash
go get git.toowon.com/jimmy/go-common
```
### 使用示例
#### 数据库迁移(独立工具,零耦合)
```bash
# 1. 复制模板templates/migrate/main.go -> cmd/migrate/main.go
# 2. 创建迁移文件migrations/20240101000001_create_users.sql
# 3. 开发环境
go run cmd/migrate/main.go up
# 4. 生产环境(编译后使用,推荐)
go build -o bin/migrate cmd/migrate/main.go
./bin/migrate up # 使用默认配置
./bin/migrate up -config /path/to/config.json # 指定配置
./bin/migrate status # 查看状态
# 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)
#### 日期转换
**推荐方式:通过 factory 使用(黑盒模式)**
```go
import "git.toowon.com/jimmy/go-common/factory"
fac, _ := factory.NewFactoryFromFile("config.json")
now := fac.Now("Asia/Shanghai")
str := fac.FormatDateTime(now)
```
**或者直接使用 tools 包:**
```go
import "git.toowon.com/jimmy/go-common/tools"
tools.SetDefaultTimeZone(tools.AsiaShanghai)
now := tools.Now()
str := tools.FormatDateTime(now)
```
#### HTTP响应Handler黑盒模式
```go
import (
"net/http"
commonhttp "git.toowon.com/jimmy/go-common/http"
)
func GetUser(h *commonhttp.Handler) {
id := h.GetQueryInt64("id", 0)
h.Success(data)
}
http.HandleFunc("/user", commonhttp.HandleFunc(GetUser))
```
#### 中间件(生产级配置)
```go
import (
"time"
"git.toowon.com/jimmy/go-common/middleware"
commonhttp "git.toowon.com/jimmy/go-common/http"
)
// 完整的中间件链
chain := middleware.NewChain(
middleware.Recovery(nil), // Panic恢复
middleware.Logging(nil), // 请求日志
middleware.RateLimitByIP(100, time.Minute), // 限流
middleware.CORS(nil), // CORS
middleware.Timezone, // 时区
)
handler := chain.ThenFunc(func(w http.ResponseWriter, r *http.Request) {
h := commonhttp.NewHandler(w, r)
timezone := h.GetTimezone()
h.Success(data)
})
```
#### 配置管理
```go
import "git.toowon.com/jimmy/go-common/config"
// 从文件加载配置
cfg, err := config.LoadFromFile("./config.json")
// 获取各种配置
dsn, _ := cfg.GetDatabaseDSN()
redisAddr := cfg.GetRedisAddr()
corsConfig := cfg.GetCORS()
```
## 版本
v1.0.0
## 许可证
MIT

View File

@@ -1,540 +0,0 @@
# 配置工具文档
## 概述
配置工具提供了从外部文件加载和管理应用配置的功能支持数据库、OSS、Redis、CORS、MinIO、邮件、短信等常用服务的配置。
## 功能特性
- 支持从外部JSON文件加载配置
- 支持数据库配置MySQL、PostgreSQL、SQLite
- 支持OSS对象存储配置阿里云、腾讯云、AWS、七牛云等
- 支持Redis配置
- 支持CORS配置与middleware包集成
- 支持MinIO配置
- 支持邮件配置SMTP
- 支持短信配置(阿里云短信)
- 自动设置默认值
- 自动生成数据库连接字符串DSN
- 自动生成Redis地址
## 配置文件格式
配置文件采用JSON格式支持以下配置项
```json
{
"database": {
"type": "mysql",
"host": "localhost",
"port": 3306,
"user": "root",
"password": "password",
"database": "testdb",
"charset": "utf8mb4",
"maxOpenConns": 100,
"maxIdleConns": 10,
"connMaxLifetime": 3600
},
"oss": {
"provider": "aliyun",
"endpoint": "oss-cn-hangzhou.aliyuncs.com",
"accessKeyId": "your-access-key-id",
"accessKeySecret": "your-access-key-secret",
"bucket": "your-bucket-name",
"region": "cn-hangzhou",
"useSSL": true,
"domain": "https://cdn.example.com"
},
"redis": {
"host": "localhost",
"port": 6379,
"password": "",
"database": 0,
"maxRetries": 3,
"poolSize": 10,
"minIdleConns": 5,
"dialTimeout": 5,
"readTimeout": 3,
"writeTimeout": 3
},
"cors": {
"allowedOrigins": ["*"],
"allowedMethods": ["GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS"],
"allowedHeaders": ["Content-Type", "Authorization", "X-Requested-With", "X-Timezone"],
"exposedHeaders": [],
"allowCredentials": false,
"maxAge": 86400
},
"minio": {
"endpoint": "localhost:9000",
"accessKeyId": "minioadmin",
"secretAccessKey": "minioadmin",
"useSSL": false,
"bucket": "test-bucket",
"region": "us-east-1",
"domain": "http://localhost:9000"
},
"email": {
"host": "smtp.example.com",
"port": 587,
"username": "your-email@example.com",
"password": "your-email-password",
"from": "your-email@example.com",
"fromName": "Your App Name",
"useTLS": true,
"useSSL": false,
"timeout": 30
},
"sms": {
"accessKeyId": "your-aliyun-access-key-id",
"accessKeySecret": "your-aliyun-access-key-secret",
"region": "cn-hangzhou",
"signName": "Your Sign Name",
"templateCode": "SMS_123456789",
"endpoint": "",
"timeout": 10
}
}
```
## 使用方法
### 1. 加载配置文件
```go
import "git.toowon.com/jimmy/go-common/config"
// 从文件加载配置(支持绝对路径和相对路径)
config, err := config.LoadFromFile("/path/to/config.json")
if err != nil {
log.Fatal(err)
}
// 或者从字节数组加载
data := []byte(`{"database": {...}}`)
config, err := config.LoadFromBytes(data)
```
### 2. 获取数据库配置
```go
// 获取数据库配置对象
dbConfig := config.GetDatabase()
if dbConfig != nil {
fmt.Printf("Database: %s@%s:%d/%s\n",
dbConfig.User, dbConfig.Host, dbConfig.Port, dbConfig.Database)
}
// 获取数据库连接字符串DSN
dsn, err := config.GetDatabaseDSN()
if err != nil {
log.Fatal(err)
}
// MySQL: "root:password@tcp(localhost:3306)/testdb?charset=utf8mb4&parseTime=True&loc=UTC"
// PostgreSQL: "host=localhost port=5432 user=root password=password dbname=testdb timezone=UTC sslmode=disable"
// 注意数据库时间统一使用UTC时间
```
### 3. 获取OSS配置
```go
ossConfig := config.GetOSS()
if ossConfig != nil {
fmt.Printf("OSS Provider: %s\n", ossConfig.Provider)
fmt.Printf("Endpoint: %s\n", ossConfig.Endpoint)
fmt.Printf("Bucket: %s\n", ossConfig.Bucket)
}
```
### 4. 获取Redis配置
```go
redisConfig := config.GetRedis()
if redisConfig != nil {
fmt.Printf("Redis: %s:%d\n", redisConfig.Host, redisConfig.Port)
}
// 获取Redis地址格式: host:port
addr := config.GetRedisAddr()
// 输出: "localhost:6379"
```
### 5. 获取CORS配置
```go
// 获取CORS配置返回config.CORSConfig类型
configCORS := config.GetCORS()
// 转换为middleware.CORSConfig并使用CORS中间件
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(
middleware.CORS(middlewareCORS),
)
```
### 6. 获取MinIO配置
```go
minioConfig := config.GetMinIO()
if minioConfig != nil {
fmt.Printf("MinIO Endpoint: %s\n", minioConfig.Endpoint)
fmt.Printf("Bucket: %s\n", minioConfig.Bucket)
}
```
## 配置项说明
### DatabaseConfig 数据库配置
| 字段 | 类型 | 说明 | 默认值 |
|------|------|------|--------|
| Type | string | 数据库类型: mysql, postgres, sqlite | - |
| Host | string | 数据库主机 | - |
| Port | int | 数据库端口 | - |
| User | string | 数据库用户名 | - |
| Password | string | 数据库密码 | - |
| Database | string | 数据库名称 | - |
| Charset | string | 字符集MySQL使用 | utf8mb4 |
| MaxOpenConns | int | 最大打开连接数 | 100 |
| MaxIdleConns | int | 最大空闲连接数 | 10 |
| ConnMaxLifetime | int | 连接最大生存时间(秒) | 3600 |
| DSN | string | 数据库连接字符串(如果设置,优先使用) | - |
### OSSConfig OSS配置
| 字段 | 类型 | 说明 |
|------|------|------|
| Provider | string | 提供商: aliyun, tencent, aws, qiniu |
| Endpoint | string | 端点地址 |
| AccessKeyID | string | 访问密钥ID |
| AccessKeySecret | string | 访问密钥 |
| Bucket | string | 存储桶名称 |
| Region | string | 区域 |
| UseSSL | bool | 是否使用SSL |
| Domain | string | 自定义域名CDN域名 |
### RedisConfig Redis配置
| 字段 | 类型 | 说明 | 默认值 |
|------|------|------|--------|
| Host | string | Redis主机 | - |
| Port | int | Redis端口 | 6379 |
| Password | string | Redis密码 | - |
| Database | int | Redis数据库编号 | 0 |
| MaxRetries | int | 最大重试次数 | 3 |
| PoolSize | int | 连接池大小 | 10 |
| MinIdleConns | int | 最小空闲连接数 | 5 |
| DialTimeout | int | 连接超时时间(秒) | 5 |
| ReadTimeout | int | 读取超时时间(秒) | 3 |
| WriteTimeout | int | 写入超时时间(秒) | 3 |
| Addr | string | Redis地址如果设置优先使用 | - |
### CORSConfig CORS配置
| 字段 | 类型 | 说明 | 默认值 |
|------|------|------|--------|
| AllowedOrigins | []string | 允许的源 | ["*"] |
| AllowedMethods | []string | 允许的HTTP方法 | ["GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS"] |
| AllowedHeaders | []string | 允许的请求头 | ["Content-Type", "Authorization", "X-Requested-With", "X-Timezone"] |
| ExposedHeaders | []string | 暴露给客户端的响应头 | [] |
| AllowCredentials | bool | 是否允许发送凭证 | false |
| MaxAge | int | 预检请求的缓存时间(秒) | 86400 |
### MinIOConfig MinIO配置
| 字段 | 类型 | 说明 |
|------|------|------|
| Endpoint | string | MinIO端点地址 |
| AccessKeyID | string | 访问密钥ID |
| SecretAccessKey | string | 密钥 |
| UseSSL | bool | 是否使用SSL |
| Bucket | string | 存储桶名称 |
| Region | string | 区域 |
| Domain | string | 自定义域名 |
### EmailConfig 邮件配置
| 字段 | 类型 | 说明 | 默认值 |
|------|------|------|--------|
| Host | string | SMTP服务器地址 | - |
| Port | int | SMTP服务器端口 | 587 |
| Username | string | 发件人邮箱 | - |
| Password | string | 邮箱密码或授权码 | - |
| From | string | 发件人邮箱地址如果为空使用Username | Username |
| FromName | string | 发件人名称 | - |
| UseTLS | bool | 是否使用TLS | false |
| UseSSL | bool | 是否使用SSL | false |
| Timeout | int | 连接超时时间(秒) | 30 |
### SMSConfig 短信配置(阿里云短信)
| 字段 | 类型 | 说明 | 默认值 |
|------|------|------|--------|
| AccessKeyID | string | 阿里云AccessKey ID | - |
| AccessKeySecret | string | 阿里云AccessKey Secret | - |
| Region | string | 区域cn-hangzhou | cn-hangzhou |
| SignName | string | 短信签名 | - |
| TemplateCode | string | 短信模板代码 | - |
| Endpoint | string | 服务端点(可选,默认使用区域端点) | - |
| Timeout | int | 请求超时时间(秒) | 10 |
### LoggerConfig 日志配置
| 字段 | 类型 | 说明 | 默认值 |
|------|------|------|--------|
| Level | string | 日志级别: debug, info, warn, error | info |
| Output | string | 输出方式: stdout, stderr, file, both | stdout |
| FilePath | string | 日志文件路径当output为file或both时必需 | - |
| Prefix | string | 日志前缀 | - |
| DisableTimestamp | bool | 禁用时间戳 | false |
## 完整示例
### 示例1加载配置并使用
```go
package main
import (
"log"
"git.toowon.com/jimmy/go-common/config"
"git.toowon.com/jimmy/go-common/middleware"
"gorm.io/driver/mysql"
"gorm.io/gorm"
)
func main() {
// 加载配置
cfg, err := config.LoadFromFile("./config.json")
if err != nil {
log.Fatal(err)
}
// 使用数据库配置
dsn, err := cfg.GetDatabaseDSN()
if err != nil {
log.Fatal(err)
}
db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
if err != nil {
log.Fatal(err)
}
// 使用Redis配置
redisAddr := cfg.GetRedisAddr()
fmt.Printf("Redis Address: %s\n", redisAddr)
// 使用CORS配置
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(
middleware.CORS(middlewareCORS),
)
// 使用OSS配置
ossConfig := cfg.GetOSS()
if ossConfig != nil {
fmt.Printf("OSS Provider: %s\n", ossConfig.Provider)
}
// 使用MinIO配置
minioConfig := cfg.GetMinIO()
if minioConfig != nil {
fmt.Printf("MinIO Endpoint: %s\n", minioConfig.Endpoint)
}
}
```
### 示例2部分配置
配置文件可以只包含需要的配置项:
```json
{
"database": {
"type": "mysql",
"host": "localhost",
"port": 3306,
"user": "root",
"password": "password",
"database": "testdb"
},
"redis": {
"host": "localhost",
"port": 6379
}
}
```
未配置的部分会返回nil需要在使用前检查
```go
cfg, _ := config.LoadFromFile("./config.json")
dbConfig := cfg.GetDatabase()
if dbConfig != nil {
// 使用数据库配置
}
ossConfig := cfg.GetOSS()
if ossConfig == nil {
// OSS未配置
}
```
### 示例3使用DSN字段
如果配置文件中直接提供了DSN会优先使用
```json
{
"database": {
"type": "mysql",
"dsn": "root:password@tcp(localhost:3306)/testdb?charset=utf8mb4&parseTime=True"
}
}
```
```go
dsn, err := cfg.GetDatabaseDSN()
// 直接返回配置中的DSN不会重新构建
```
## API 参考
### LoadFromFile(filePath string) (*Config, error)
从文件加载配置。
**参数:**
- `filePath`: 配置文件路径(支持绝对路径和相对路径)
**返回:** 配置对象和错误信息
### LoadFromBytes(data []byte) (*Config, error)
从字节数组加载配置。
**参数:**
- `data`: JSON格式的配置数据
**返回:** 配置对象和错误信息
### (c *Config) GetDatabase() *DatabaseConfig
获取数据库配置。
**返回:** 数据库配置对象可能为nil
### (c *Config) GetDatabaseDSN() (string, error)
获取数据库连接字符串。
**返回:** DSN字符串和错误信息
### (c *Config) GetOSS() *OSSConfig
获取OSS配置。
**返回:** OSS配置对象可能为nil
### (c *Config) GetRedis() *RedisConfig
获取Redis配置。
**返回:** Redis配置对象可能为nil
### (c *Config) GetRedisAddr() string
获取Redis地址格式: host:port
**返回:** Redis地址字符串
### (c *Config) GetCORS() *middleware.CORSConfig
获取CORS配置并转换为middleware.CORSConfig类型。
**返回:** CORS配置对象如果配置为nil返回默认配置
### (c *Config) GetMinIO() *MinIOConfig
获取MinIO配置。
**返回:** MinIO配置对象可能为nil
### (c *Config) GetEmail() *EmailConfig
获取邮件配置。
**返回:** 邮件配置对象可能为nil
### (c *Config) GetSMS() *SMSConfig
获取短信配置。
**返回:** 短信配置对象可能为nil
### (c *Config) GetLogger() *LoggerConfig
获取日志配置。
**返回:** 日志配置对象可能为nil
## 注意事项
1. **配置文件路径**
- 支持绝对路径和相对路径
- 相对路径基于当前工作目录
2. **默认值**
- 配置加载时会自动设置默认值
- 如果配置项为nil对应的Get方法会返回nil
3. **DSN优先级**
- 如果配置中设置了DSN字段会优先使用
- 否则会根据配置项自动构建DSN
4. **配置验证**
- 当前版本不进行配置验证,请确保配置正确
- 建议在生产环境中添加配置验证逻辑
5. **安全性**
- 配置文件可能包含敏感信息(密码、密钥等)
- 建议将配置文件放在安全的位置,不要提交到版本控制系统
- 可以使用环境变量或配置管理服务
6. **数据库时区**
- 数据库时间统一使用UTC时间存储
- DSN中会自动设置UTC时区MySQL: loc=UTC, PostgreSQL: timezone=UTC
- 时区转换应在应用层处理使用datetime工具包进行时区转换
## 配置文件示例
完整配置文件示例请参考 `config/example.json`

View File

@@ -1,596 +0,0 @@
# 日期转换工具文档
## 概述
日期转换工具提供了丰富的日期时间处理功能,支持时区设定、格式转换、时间计算等常用操作。
**重要说明**:日期时间功能位于 `tools` 包中,推荐通过 `factory` 包使用(黑盒模式),也可以直接使用 `tools` 包。
## 功能特性
- 支持时区设定和转换
- 支持多种时间格式的解析和格式化
- 提供常用时间格式常量
- 支持Unix时间戳转换
- 提供时间计算功能(添加天数、月数、年数等)
- 提供时间范围获取功能(开始/结束时间)
- 支持将任意时区时间转换为UTC时间用于数据库存储
## 使用方法
### 方式1通过 factory 使用(推荐,黑盒模式)
```go
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 := tools.SetDefaultTimeZone(tools.AsiaShanghai)
if err != nil {
log.Fatal(err)
}
```
### 2. 获取当前时间
**通过 factory**
```go
// 使用默认时区
now := fac.Now()
// 使用指定时区
now := fac.Now("Asia/Shanghai")
now := fac.Now("America/New_York")
```
**直接使用 tools**
```go
// 使用默认时区
now := tools.Now()
// 使用指定时区
now := tools.Now(tools.AsiaShanghai)
now := tools.Now("America/New_York")
```
### 3. 解析时间字符串
**通过 factory**
```go
// 使用默认时区解析
t, err := fac.ParseDateTime("2024-01-01 12:00:00")
// 使用指定时区解析
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 := tools.ParseDateTime("2024-01-01 12:00:00")
t, err := tools.ParseDate("2024-01-01")
```
### 4. 格式化时间
**通过 factory**
```go
t := time.Now()
// 使用默认时区格式化
str := fac.FormatDateTime(t)
str := fac.FormatDate(t)
str := fac.FormatTime(t)
// 使用指定时区格式化
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 := tools.FormatDateTime(t) // "2006-01-02 15:04:05"
str := tools.FormatDate(t) // "2006-01-02"
str := tools.FormatTime(t) // "15:04:05"
```
### 5. 时区转换
**通过 factory**
```go
t := time.Now()
t2, err := tools.ToTimezone(t, "Asia/Shanghai")
```
**直接使用 tools**
```go
t := time.Now()
t2, err := tools.ToTimezone(t, tools.AsiaShanghai)
```
### 6. Unix时间戳转换
**通过 factory**
```go
t := time.Now()
// 转换为Unix时间戳
unix := fac.ToUnix(t)
// 从Unix时间戳创建时间
t2 := fac.FromUnix(unix)
// 转换为Unix毫秒时间戳
unixMilli := fac.ToUnixMilli(t)
// 从Unix毫秒时间戳创建时间
t3 := fac.FromUnixMilli(unixMilli)
```
**直接使用 tools**
```go
t := time.Now()
// 转换为Unix时间戳
unix := tools.ToUnix(t)
// 从Unix时间戳创建时间
t2 := tools.FromUnix(unix)
// 转换为Unix毫秒时间戳
unixMilli := tools.ToUnixMilli(t)
// 从Unix毫秒时间戳创建时间
t3 := tools.FromUnixMilli(unixMilli)
```
### 7. 时间计算
**通过 factory**
```go
t := time.Now()
// 添加天数
t1 := fac.AddDays(t, 7)
// 添加月数
t2 := fac.AddMonths(t, 1)
// 添加年数
t3 := fac.AddYears(t, 1)
```
**直接使用 tools**
```go
t := time.Now()
// 添加天数
t1 := tools.AddDays(t, 7)
// 添加月数
t2 := tools.AddMonths(t, 1)
// 添加年数
t3 := tools.AddYears(t, 1)
```
### 8. 时间范围获取
**通过 factory**
```go
t := time.Now()
// 获取一天的开始时间00:00:00
start := fac.StartOfDay(t)
// 获取一天的结束时间23:59:59.999999999
end := fac.EndOfDay(t)
// 获取月份的开始时间
monthStart := fac.StartOfMonth(t)
// 获取月份的结束时间
monthEnd := fac.EndOfMonth(t)
// 获取年份的开始时间
yearStart := fac.StartOfYear(t)
// 获取年份的结束时间
yearEnd := fac.EndOfYear(t)
```
**直接使用 tools**
```go
t := time.Now()
// 获取一天的开始时间00:00:00
start := tools.StartOfDay(t)
// 获取一天的结束时间23:59:59.999999999
end := tools.EndOfDay(t)
// 获取月份的开始时间
monthStart := tools.StartOfMonth(t)
// 获取月份的结束时间
monthEnd := tools.EndOfMonth(t)
// 获取年份的开始时间
yearStart := tools.StartOfYear(t)
// 获取年份的结束时间
yearEnd := tools.EndOfYear(t)
```
### 9. 时间差计算
**通过 factory**
```go
t1 := time.Now()
t2 := time.Now().Add(24 * time.Hour)
// 计算天数差
days := fac.DiffDays(t1, t2)
// 计算小时差
hours := fac.DiffHours(t1, t2)
// 计算分钟差
minutes := fac.DiffMinutes(t1, t2)
// 计算秒数差
seconds := fac.DiffSeconds(t1, t2)
```
**直接使用 tools**
```go
t1 := time.Now()
t2 := time.Now().Add(24 * time.Hour)
// 计算天数差
days := tools.DiffDays(t1, t2)
// 计算小时差
hours := tools.DiffHours(t1, t2)
// 计算分钟差
minutes := tools.DiffMinutes(t1, t2)
// 计算秒数差
seconds := tools.DiffSeconds(t1, t2)
```
### 10. 转换为UTC时间用于数据库存储
**直接使用 toolsfactory 暂未提供):**
```go
// 将任意时区的时间转换为UTC
t := time.Now() // 当前时区的时间
utcTime := tools.ToUTC(t)
// 从指定时区转换为UTC
t, _ := tools.ParseDateTime("2024-01-01 12:00:00", tools.AsiaShanghai)
utcTime, err := tools.ToUTCFromTimezone(t, tools.AsiaShanghai)
// 解析时间字符串并直接转换为UTC
utcTime, err := tools.ParseDateTimeToUTC("2024-01-01 12:00:00", tools.AsiaShanghai)
// 解析日期并转换为UTC当天的00:00:00 UTC
utcTime, err := tools.ParseDateToUTC("2024-01-01", tools.AsiaShanghai)
```
## API 参考
### 时区常量
**通过 tools 包使用:**
```go
import "git.toowon.com/jimmy/go-common/tools"
const (
tools.UTC = "UTC"
tools.AsiaShanghai = "Asia/Shanghai"
tools.AmericaNewYork = "America/New_York"
tools.EuropeLondon = "Europe/London"
tools.AsiaTokyo = "Asia/Tokyo"
)
```
### 常用时间格式
```go
CommonLayouts.DateTime = "2006-01-02 15:04"
CommonLayouts.DateTimeSec = "2006-01-02 15:04:05"
CommonLayouts.Date = "2006-01-02"
CommonLayouts.Time = "15:04"
CommonLayouts.TimeSec = "15:04:05"
CommonLayouts.ISO8601 = "2006-01-02T15:04:05Z07:00"
CommonLayouts.RFC3339 = time.RFC3339
CommonLayouts.RFC3339Nano = time.RFC3339Nano
```
### 主要函数
**注意**:以下函数可以通过 `factory``tools` 包调用。推荐使用 `factory` 的黑盒模式。
#### SetDefaultTimeZone(timezone string) error
设置默认时区(仅 tools 包提供)。
**参数:**
- `timezone`: 时区字符串,如 "Asia/Shanghai"
**返回:** 错误信息
**使用方式:**
```go
tools.SetDefaultTimeZone(tools.AsiaShanghai)
```
#### Now(timezone ...string) time.Time
获取当前时间。
**参数:**
- `timezone`: 可选,时区字符串,不指定则使用默认时区
**返回:** 时间对象
**使用方式:**
```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
**参数:**
- `value`: 时间字符串
- `timezone`: 可选,时区字符串
**返回:** 时间对象和错误信息
**使用方式:**
```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`: 时间对象
- `timezone`: 可选,时区字符串
**返回:** 格式化后的时间字符串
**使用方式:**
```go
// 通过 factory
str := fac.FormatDateTime(t, "Asia/Shanghai")
// 直接使用 tools
str := tools.FormatDateTime(t, tools.AsiaShanghai)
```
更多函数请参考 `factory` 包或 `tools` 包的 API 文档。
### UTC转换函数
#### ToUTC(t time.Time) time.Time
将时间转换为UTC时间。
**参数:**
- `t`: 时间对象(可以是任意时区)
**返回:** UTC时间
#### ToUTCFromTimezone(t time.Time, timezone string) (time.Time, error)
从指定时区转换为UTC时间。
**参数:**
- `t`: 时间对象(会被视为指定时区的时间)
- `timezone`: 源时区
**返回:** UTC时间和错误信息
#### ParseToUTC(layout, value string, timezone ...string) (time.Time, error)
解析时间字符串并转换为UTC时间。
**参数:**
- `layout`: 时间格式,如 "2006-01-02 15:04:05"
- `value`: 时间字符串
- `timezone`: 源时区,如果为空则使用默认时区
**返回:** UTC时间和错误信息
#### ParseDateTimeToUTC(value string, timezone ...string) (time.Time, error)
解析日期时间字符串并转换为UTC时间便捷方法
**参数:**
- `value`: 时间字符串(格式: 2006-01-02 15:04:05
- `timezone`: 源时区,如果为空则使用默认时区
**返回:** UTC时间和错误信息
#### ParseDateToUTC(value string, timezone ...string) (time.Time, error)
解析日期字符串并转换为UTC时间便捷方法
**参数:**
- `value`: 日期字符串(格式: 2006-01-02
- `timezone`: 源时区,如果为空则使用默认时区
**返回:** UTC时间当天的00:00:00 UTC时间和错误信息
## 注意事项
1. **时区字符串**必须符合IANA时区数据库格式
2. **默认时区**默认时区为UTC建议在应用启动时设置合适的默认时区
3. **时间格式**时间格式字符串必须使用Go的特定时间2006-01-02 15:04:05
4. **时间范围函数**所有时间范围函数StartOfDay、EndOfDay等都会考虑时区
5. **数据库存储**
- 数据库时间统一使用UTC时间存储
- 使用`ToUTC``ParseToUTC`等方法将时间转换为UTC后存储到数据库
- 从数据库读取UTC时间后使用`ToTimezone`转换为用户时区显示
## 完整示例
### 示例1通过 factory 使用(推荐)
```go
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)
}
// 获取当前时间
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() {
// 设置默认时区
err := tools.SetDefaultTimeZone(tools.AsiaShanghai)
if err != nil {
log.Fatal(err)
}
// 获取当前时间
now := tools.Now()
fmt.Printf("Current time: %s\n", tools.FormatDateTime(now))
// 时区转换
t, _ := tools.ParseDateTime("2024-01-01 12:00:00")
t2, _ := tools.ToTimezone(t, tools.AmericaNewYork)
fmt.Printf("Time in New York: %s\n", tools.FormatDateTime(t2))
}
```
### 示例3UTC转换数据库存储场景
```go
package main
import (
"fmt"
"log"
"git.toowon.com/jimmy/go-common/tools"
)
func main() {
// 从请求中获取时间(假设是上海时区)
requestTimeStr := "2024-01-01 12:00:00"
requestTimezone := tools.AsiaShanghai
// 转换为UTC时间用于数据库存储
dbTime, err := tools.ParseDateTimeToUTC(requestTimeStr, requestTimezone)
if err != nil {
log.Fatal(err)
}
fmt.Printf("Request time (Shanghai): %s\n", requestTimeStr)
fmt.Printf("Database time (UTC): %s\n", tools.FormatDateTime(dbTime, tools.UTC))
// 从数据库读取UTC时间转换为用户时区显示
userTimezone := tools.AsiaShanghai
displayTime, err := tools.ToTimezone(dbTime, userTimezone)
if err != nil {
log.Fatal(err)
}
fmt.Printf("Display time (Shanghai): %s\n", tools.FormatDateTime(displayTime, userTimezone))
}
```
完整示例请参考 `factory` 包中的 datetime 相关方法,通过 `factory` 调用 `tools` 包中的 datetime 功能。

View File

@@ -1,332 +0,0 @@
# 邮件工具文档
## 概述
邮件工具提供了SMTP邮件发送功能使用Go标准库实现无需第三方依赖。
## 功能特性
- 支持SMTP邮件发送
- 支持TLS/SSL加密
- 支持发送原始邮件内容(完全由外部控制)
- 支持便捷方法发送简单邮件
- 使用配置工具统一管理配置
## 使用方法
### 1. 创建邮件发送器
```go
import (
"git.toowon.com/jimmy/go-common/config"
"git.toowon.com/jimmy/go-common/email"
)
// 从配置加载
cfg, err := config.LoadFromFile("./config.json")
if err != nil {
log.Fatal(err)
}
emailConfig := cfg.GetEmail()
if emailConfig == nil {
log.Fatal("email config is nil")
}
// 创建邮件发送器
mailer, err := email.NewEmail(emailConfig)
if err != nil {
log.Fatal(err)
}
```
### 2. 发送原始邮件内容(推荐,最灵活)
```go
// 外部构建完整的邮件内容MIME格式
emailBody := []byte(`From: sender@example.com
To: recipient@example.com
Subject: 邮件主题
Content-Type: text/html; charset=UTF-8
<html>
<body>
<h1>邮件内容</h1>
<p>这是由外部构建的完整邮件内容</p>
</body>
</html>
`)
// 发送邮件工具只负责SMTP发送不构建内容
err := mailer.SendRaw(
[]string{"recipient@example.com"}, // 收件人列表
emailBody, // 完整的邮件内容
)
if err != nil {
log.Fatal(err)
}
```
### 3. 发送简单邮件(便捷方法)
```go
// 发送纯文本邮件(内部会构建邮件内容)
err := mailer.SendSimple(
[]string{"recipient@example.com"},
"邮件主题",
"邮件正文内容",
)
if err != nil {
log.Fatal(err)
}
```
### 4. 发送HTML邮件便捷方法
```go
// 发送HTML邮件内部会构建邮件内容
htmlBody := `
<html>
<body>
<h1>欢迎</h1>
<p>这是一封HTML邮件</p>
</body>
</html>
`
err := mailer.SendHTML(
[]string{"recipient@example.com"},
"邮件主题",
htmlBody,
)
if err != nil {
log.Fatal(err)
}
```
### 5. 使用Message结构发送便捷方法
```go
import "git.toowon.com/jimmy/go-common/email"
msg := &email.Message{
To: []string{"to@example.com"},
Cc: []string{"cc@example.com"},
Bcc: []string{"bcc@example.com"},
Subject: "邮件主题",
Body: "纯文本正文",
HTMLBody: "<html><body><h1>HTML正文</h1></body></html>",
}
err := mailer.Send(msg)
if err != nil {
log.Fatal(err)
}
```
## API 参考
### NewEmail(cfg *config.EmailConfig) (*Email, error)
创建邮件发送器。
**参数:**
- `cfg`: 邮件配置对象
**返回:** 邮件发送器实例和错误信息
### (e *Email) SendRaw(recipients []string, body []byte) error
发送原始邮件内容(推荐使用,最灵活)。
**参数:**
- `recipients`: 收件人列表To、Cc、Bcc的合并列表
- `body`: 完整的邮件内容MIME格式由外部构建
**返回:** 错误信息
**说明:** 此方法允许外部完全控制邮件内容工具只负责SMTP发送。
### (e *Email) Send(msg *Message) error
发送邮件使用Message结构内部会构建邮件内容
**参数:**
- `msg`: 邮件消息对象
**返回:** 错误信息
**说明:** 如果需要完全控制邮件内容请使用SendRaw方法。
### (e *Email) SendSimple(to []string, subject, body string) error
发送简单邮件(便捷方法)。
**参数:**
- `to`: 收件人列表
- `subject`: 主题
- `body`: 正文
### (e *Email) SendHTML(to []string, subject, htmlBody string) error
发送HTML邮件便捷方法
**参数:**
- `to`: 收件人列表
- `subject`: 主题
- `htmlBody`: HTML正文
### Message 结构体
```go
type Message struct {
To []string // 收件人列表
Cc []string // 抄送列表(可选)
Bcc []string // 密送列表(可选)
Subject string // 主题
Body string // 正文(纯文本)
HTMLBody string // HTML正文可选
Attachments []Attachment // 附件列表(可选)
}
```
### Attachment 结构体
```go
type Attachment struct {
Filename string // 文件名
Content []byte // 文件内容
ContentType string // 文件类型
}
```
## 配置说明
邮件配置通过 `config.EmailConfig` 提供:
| 字段 | 类型 | 说明 | 默认值 |
|------|------|------|--------|
| Host | string | SMTP服务器地址 | - |
| Port | int | SMTP服务器端口 | 587 |
| Username | string | 发件人邮箱 | - |
| Password | string | 邮箱密码或授权码 | - |
| From | string | 发件人邮箱地址 | Username |
| FromName | string | 发件人名称 | - |
| UseTLS | bool | 是否使用TLS | false |
| UseSSL | bool | 是否使用SSL | false |
| Timeout | int | 连接超时时间(秒) | 30 |
## 常见SMTP服务器配置
### Gmail
```json
{
"host": "smtp.gmail.com",
"port": 587,
"useTLS": true,
"useSSL": false
}
```
### QQ邮箱
```json
{
"host": "smtp.qq.com",
"port": 587,
"useTLS": true,
"useSSL": false
}
```
### 163邮箱
```json
{
"host": "smtp.163.com",
"port": 25,
"useTLS": false,
"useSSL": false
}
```
### 企业邮箱SSL
```json
{
"host": "smtp.exmail.qq.com",
"port": 465,
"useTLS": false,
"useSSL": true
}
```
## 注意事项
1. **推荐使用SendRaw方法**
- `SendRaw`方法允许外部完全控制邮件内容
- 可以构建任意格式的MIME邮件包括复杂附件、多部分内容等
- 工具只负责SMTP发送不构建内容
2. **邮件内容构建**
- 使用`SendRaw`需要外部构建完整的MIME格式邮件内容
- 可以参考RFC 5322标准构建邮件内容
- 便捷方法(`Send``SendSimple``SendHTML`)内部会构建简单格式的邮件内容
3. **密码/授权码**
- 很多邮箱服务商需要使用授权码而不是登录密码
- Gmail、QQ邮箱等需要开启SMTP服务并获取授权码
4. **端口选择**
- 587端口通常使用TLSSTARTTLS
- 465端口通常使用SSL
- 25端口通常不使用加密不推荐
5. **TLS vs SSL**
- UseTLS=true使用STARTTLS推荐端口587
- UseSSL=true使用SSL端口465
6. **错误处理**
- 所有操作都应该进行错误处理
- 建议记录详细的错误日志
## 完整示例
```go
package main
import (
"log"
"git.toowon.com/jimmy/go-common/config"
"git.toowon.com/jimmy/go-common/email"
)
func main() {
// 加载配置
cfg, err := config.LoadFromFile("./config.json")
if err != nil {
log.Fatal(err)
}
// 创建邮件发送器
mailer, err := email.NewEmail(cfg.GetEmail())
if err != nil {
log.Fatal(err)
}
// 发送邮件
err = mailer.SendSimple(
[]string{"recipient@example.com"},
"测试邮件",
"这是一封测试邮件",
)
if err != nil {
log.Fatal(err)
}
log.Println("邮件发送成功")
}
```
## 示例
完整示例请参考 `examples/email_example.go`

File diff suppressed because it is too large Load Diff

View File

@@ -1,752 +0,0 @@
# HTTP Restful工具文档
## 概述
HTTP Restful工具提供了标准化的HTTP请求和响应处理功能提供公共方法供外部调用保持低耦合。
## 功能特性
- **低耦合设计**提供公共方法不封装Handler结构
- **标准化的响应结构**`{code, message, timestamp, data}`
- **分离HTTP状态码和业务状态码**
- **支持分页响应**
- **提供便捷的请求参数解析方法**
- **支持JSON请求体解析**
- **Factory黑盒模式**:推荐使用 `factory.Success()` 等方法
## 响应结构
### 标准响应结构
```json
{
"code": 0,
"message": "success",
"timestamp": 1704067200,
"data": {}
}
```
**结构体类型(暴露在 factory 中):**
```go
// 在 factory 包中可以直接使用
type Response struct {
Code int `json:"code"` // 业务状态码0表示成功
Message string `json:"message"` // 响应消息
Timestamp int64 `json:"timestamp"` // 时间戳
Data interface{} `json:"data"` // 响应数据
}
```
### 分页响应结构
```json
{
"code": 0,
"message": "success",
"timestamp": 1704067200,
"data": {
"list": [],
"total": 100,
"page": 1,
"pageSize": 10
}
}
```
**结构体类型(暴露在 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)
```
## 使用方法
### 方式一使用Factory黑盒方法推荐
这是最简单的方式,直接使用 `factory.Success()` 等方法:
```go
import (
"net/http"
"git.toowon.com/jimmy/go-common/factory"
commonhttp "git.toowon.com/jimmy/go-common/http"
)
func GetUser(w http.ResponseWriter, r *http.Request) {
fac, _ := factory.NewFactoryFromFile("config.json")
// 获取查询参数(使用公共方法)
id := commonhttp.GetQueryInt64(r, "id", 0)
// 返回成功响应使用factory方法
fac.Success(w, data)
}
func CreateUser(w http.ResponseWriter, r *http.Request) {
fac, _ := factory.NewFactoryFromFile("config.json")
// 解析JSON使用公共方法
var req struct {
Name string `json:"name"`
}
if err := commonhttp.ParseJSON(r, &req); err != nil {
commonhttp.WriteJSON(w, http.StatusBadRequest, 400, "请求参数解析失败", nil)
return
}
// 返回成功响应使用factory方法
fac.Success(w, data, "创建成功")
}
func GetUserList(w http.ResponseWriter, r *http.Request) {
fac, _ := factory.NewFactoryFromFile("config.json")
// 获取分页参数使用factory方法推荐
pagination := fac.ParsePaginationRequest(r)
page := pagination.GetPage()
pageSize := pagination.GetSize()
// 获取查询参数使用factory方法推荐
keyword := fac.GetQuery(r, "keyword", "")
// 查询数据
list, total := getDataList(keyword, page, pageSize)
// 返回分页响应使用factory方法
fac.SuccessPage(w, list, total, page, pageSize)
}
// 注册路由
http.HandleFunc("/user", GetUser)
http.HandleFunc("/users", GetUserList)
```
### 方式二:直接使用公共方法
如果不想使用Factory可以直接使用 `http` 包的公共方法:
```go
import (
"net/http"
commonhttp "git.toowon.com/jimmy/go-common/http"
)
func GetUser(w http.ResponseWriter, r *http.Request) {
// 获取查询参数
id := commonhttp.GetQueryInt64(r, "id", 0)
// 返回成功响应
commonhttp.Success(w, data)
}
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
}
// 返回成功响应
commonhttp.Success(w, data, "创建成功")
}
```
### 成功响应
```go
// 使用Factory推荐
fac.Success(w, data) // 只有数据,使用默认消息 "success"
fac.Success(w, data, "操作成功") // 数据+消息
// 或直接使用公共方法
commonhttp.Success(w, data) // 只有数据
commonhttp.Success(w, data, "操作成功") // 数据+消息
```
### 错误响应
```go
// 使用Factory推荐
fac.Error(w, 1001, "用户不存在") // 业务错误HTTP 200业务code非0
fac.SystemError(w, "服务器内部错误") // 系统错误HTTP 500
// 或直接使用公共方法
commonhttp.Error(w, 1001, "用户不存在")
commonhttp.SystemError(w, "服务器内部错误")
commonhttp.WriteJSON(w, http.StatusBadRequest, 400, "请求参数错误", nil) // 自定义HTTP状态码仅公共方法
```
### 分页响应
```go
// 使用Factory推荐
fac.SuccessPage(w, list, total, page, pageSize)
fac.SuccessPage(w, list, total, page, pageSize, "查询成功")
// 或直接使用公共方法
commonhttp.SuccessPage(w, list, total, page, pageSize)
commonhttp.SuccessPage(w, list, total, page, pageSize, "查询成功")
```
### 解析请求
#### 解析JSON请求体
```go
// 使用公共方法
var req struct {
Name string `json:"name"`
Email string `json:"email"`
}
if err := commonhttp.ParseJSON(r, &req); err != nil {
commonhttp.WriteJSON(w, http.StatusBadRequest, 400, "请求参数解析失败", nil)
return
}
```
#### 获取查询参数
```go
// 使用公共方法
name := commonhttp.GetQuery(r, "name", "")
id := commonhttp.GetQueryInt(r, "id", 0)
userId := commonhttp.GetQueryInt64(r, "userId", 0)
isActive := commonhttp.GetQueryBool(r, "isActive", false)
price := commonhttp.GetQueryFloat64(r, "price", 0.0)
```
#### 获取表单参数
```go
// 使用公共方法
name := commonhttp.GetFormValue(r, "name", "")
age := commonhttp.GetFormInt(r, "age", 0)
userId := commonhttp.GetFormInt64(r, "userId", 0)
isActive := commonhttp.GetFormBool(r, "isActive", false)
```
#### 获取请求头
```go
// 使用公共方法
token := commonhttp.GetHeader(r, "Authorization", "")
contentType := commonhttp.GetHeader(r, "Content-Type", "application/json")
```
#### 获取分页参数
**方式1使用 PaginationRequest 结构(推荐)**
```go
// 定义请求结构(包含分页字段)
type ListUserRequest struct {
Keyword string `json:"keyword"`
commonhttp.PaginationRequest // 嵌入分页请求结构
}
// 从JSON请求体解析分页字段会自动解析
var req ListUserRequest
if err := commonhttp.ParseJSON(r, &req); err != nil {
commonhttp.WriteJSON(w, http.StatusBadRequest, 400, "请求参数解析失败", nil)
return
}
// 使用分页方法
page := req.GetPage() // 获取页码默认1
size := req.GetSize() // 获取每页数量默认20最大100优先使用page_size
offset := req.GetOffset() // 计算偏移量
```
**方式2从查询参数/form解析分页**
```go
// 使用公共方法
pagination := commonhttp.ParsePaginationRequest(r)
page := pagination.GetPage()
size := pagination.GetSize()
offset := pagination.GetOffset()
```
#### 获取时区
```go
// 使用公共方法
// 如果使用了middleware.Timezone中间件可以从context中获取时区信息
// 如果未设置,返回默认时区 AsiaShanghai
timezone := commonhttp.GetTimezone(r)
```
## 完整示例
### 使用Factory推荐
```go
package main
import (
"log"
"net/http"
"git.toowon.com/jimmy/go-common/factory"
commonhttp "git.toowon.com/jimmy/go-common/http"
)
// 用户结构
type User struct {
ID int64 `json:"id"`
Name string `json:"name"`
Email string `json:"email"`
}
// 用户列表接口
func GetUserList(w http.ResponseWriter, r *http.Request) {
fac, _ := factory.NewFactoryFromFile("config.json")
// 获取分页参数(使用公共方法)
pagination := commonhttp.ParsePaginationRequest(r)
page := pagination.GetPage()
pageSize := pagination.GetSize()
// 获取查询参数(使用公共方法)
keyword := commonhttp.GetQuery(r, "keyword", "")
// 查询数据
users, total := queryUsers(keyword, page, pageSize)
// 返回分页响应使用factory方法
fac.SuccessPage(w, users, total, page, pageSize)
}
// 创建用户接口
func CreateUser(w http.ResponseWriter, r *http.Request) {
fac, _ := factory.NewFactoryFromFile("config.json")
// 解析请求体(使用公共方法)
var req struct {
Name string `json:"name"`
Email string `json:"email"`
}
if err := commonhttp.ParseJSON(r, &req); err != nil {
fac.WriteJSON(w, http.StatusBadRequest, 400, "请求参数解析失败", nil)
return
}
// 参数验证
if req.Name == "" {
fac.Error(w, 1001, "用户名不能为空")
return
}
// 创建用户
user, err := createUser(req.Name, req.Email)
if err != nil {
fac.SystemError(w, "创建用户失败")
return
}
// 返回成功响应使用factory方法
fac.Success(w, user, "创建成功")
}
// 获取用户详情接口
func GetUser(w http.ResponseWriter, r *http.Request) {
fac, _ := factory.NewFactoryFromFile("config.json")
// 获取查询参数使用factory方法推荐
id := fac.GetQueryInt64(r, "id", 0)
if id == 0 {
commonhttp.WriteJSON(w, http.StatusBadRequest, 400, "用户ID不能为空", nil)
return
}
// 查询用户
user, err := getUserByID(id)
if err != nil {
fac.SystemError(w, "查询用户失败")
return
}
if user == nil {
fac.Error(w, 1002, "用户不存在")
return
}
// 返回成功响应使用factory方法
fac.Success(w, user)
}
func main() {
http.HandleFunc("/users", func(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case http.MethodGet:
GetUserList(w, r)
case http.MethodPost:
CreateUser(w, r)
default:
commonhttp.WriteJSON(w, http.StatusMethodNotAllowed, 405, "方法不支持", nil)
}
})
http.HandleFunc("/user", GetUser)
log.Println("Server started on :8080")
log.Fatal(http.ListenAndServe(":8080", nil))
}
```
## API 参考
### Factory HTTP响应结构体暴露给外部项目使用
#### Response
标准响应结构体,外部项目可以直接使用 `factory.Response`
**字段:**
- `Code`: 业务状态码0表示成功
- `Message`: 响应消息
- `Timestamp`: 时间戳Unix时间戳
- `Data`: 响应数据
**示例:**
```go
response := factory.Response{
Code: 0,
Message: "success",
Data: userData,
}
```
#### PageData
分页数据结构体,外部项目可以直接使用 `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。
**参数:**
- `data`: 响应数据可以为nil
- `message`: 响应消息(可选),如果为空则使用默认消息 "success"
**示例:**
```go
fac.Success(w, data) // 只有数据,使用默认消息 "success"
fac.Success(w, data, "操作成功") // 数据+消息
```
#### (f *Factory) Error(w http.ResponseWriter, code int, message string)
业务错误响应HTTP 200业务code非0。
**示例:**
```go
fac.Error(w, 1001, "用户不存在")
```
#### (f *Factory) SystemError(w http.ResponseWriter, message string)
系统错误响应HTTP 500业务code 500。
**示例:**
```go
fac.SystemError(w, "服务器内部错误")
```
#### (f *Factory) WriteJSON(w http.ResponseWriter, httpCode, code int, message string, data interface{})
写入JSON响应自定义
**参数:**
- `httpCode`: HTTP状态码
- `code`: 业务状态码
- `message`: 响应消息
- `data`: 响应数据
**说明:**
- 此方法不在 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)
分页成功响应。
**参数:**
- `list`: 数据列表
- `total`: 总记录数
- `page`: 当前页码
- `pageSize`: 每页大小
- `message`: 响应消息(可选,如果为空则使用默认消息 "success"
**示例:**
```go
fac.SuccessPage(w, users, total, page, pageSize)
fac.SuccessPage(w, users, total, page, pageSize, "查询成功")
```
### 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请求体。
**示例:**
```go
var req CreateUserRequest
if err := commonhttp.ParseJSON(r, &req); err != nil {
// 处理错误
}
```
#### GetQuery(r *http.Request, key, defaultValue string) string
获取查询参数(字符串)。
#### GetQueryInt(r *http.Request, key string, defaultValue int) int
获取查询参数(整数)。
#### GetQueryInt64(r *http.Request, key string, defaultValue int64) int64
获取查询参数int64
#### GetQueryBool(r *http.Request, key string, defaultValue bool) bool
获取查询参数(布尔值)。
#### GetQueryFloat64(r *http.Request, key string, defaultValue float64) float64
获取查询参数(浮点数)。
#### GetFormValue(r *http.Request, key, defaultValue string) string
获取表单值(字符串)。
#### GetFormInt(r *http.Request, key string, defaultValue int) int
获取表单值(整数)。
#### GetFormInt64(r *http.Request, key string, defaultValue int64) int64
获取表单值int64
#### GetFormBool(r *http.Request, key string, defaultValue bool) bool
获取表单值(布尔值)。
#### GetHeader(r *http.Request, key, defaultValue string) string
获取请求头。
#### ParsePaginationRequest(r *http.Request) *PaginationRequest
从请求中解析分页参数。
**说明:**
- 支持从查询参数和form表单中解析
- 优先级:查询参数 > form表单
- 如果请求体是JSON格式且包含分页字段建议先使用`ParseJSON`解析完整请求体到包含`PaginationRequest`的结构体中
#### GetTimezone(r *http.Request) string
从请求的context中获取时区。
**说明:**
- 如果使用了middleware.Timezone中间件可以从context中获取时区信息
- 如果未设置,返回默认时区 AsiaShanghai
#### Success(w http.ResponseWriter, data interface{}, message ...string)
成功响应(公共方法)。
**参数:**
- `data`: 响应数据可以为nil
- `message`: 响应消息(可选),如果为空则使用默认消息 "success"
**示例:**
```go
commonhttp.Success(w, data) // 只有数据
commonhttp.Success(w, data, "操作成功") // 数据+消息
```
#### Error(w http.ResponseWriter, code int, message string)
错误响应(公共方法)。
#### 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)
分页成功响应(公共方法)。
### 分页请求结构
#### PaginationRequest
分页请求结构支持从JSON和form中解析分页参数。
**字段:**
- `Page`: 页码默认1
- `Size`: 每页数量(兼容旧版本)
- `PageSize`: 每页数量推荐使用优先于Size
**方法:**
- `GetPage() int`: 获取页码如果未设置则返回默认值1
- `GetSize() int`: 获取每页数量优先使用PageSize如果未设置则使用Size默认20最大100
- `GetOffset() int`: 计算数据库查询的偏移量
#### ParsePaginationRequest(r *http.Request) *PaginationRequest
从请求中解析分页参数内部函数Handler内部使用
## 状态码说明
### HTTP状态码
- `200`: 正常响应(包括业务错误)
- `400`: 请求参数错误
- `401`: 未授权
- `403`: 禁止访问
- `404`: 资源不存在
- `500`: 系统内部错误
### 业务状态码
- `0`: 成功
- `非0`: 业务错误(具体错误码由业务定义)
## 注意事项
1. **HTTP状态码与业务状态码分离**
- 业务错误如用户不存在、参数验证失败等返回HTTP 200业务code非0
- 只有系统异常如数据库连接失败、程序panic等才返回HTTP 500
2. **分页参数限制**
- page最小值为1
- pageSize最小值为1最大值为100
3. **响应格式统一**
- 所有响应都遵循标准结构
- timestamp为Unix时间戳
4. **错误处理**
- 使用`Error`方法返回业务错误HTTP 200业务code非0
- 使用`SystemError`返回系统错误HTTP 500
- 其他HTTP错误状态码400, 401, 403, 404等使用`WriteJSON`方法直接指定
5. **推荐使用Factory**
- 使用 `factory.Success()` 等方法,代码更简洁
- 直接使用 `http` 包的公共方法,保持低耦合
- 不需要Handler结构减少不必要的封装
## 示例
完整示例请参考:
- `examples/http_handler_example.go` - 使用Factory和公共方法
- `examples/http_pagination_example.go` - 分页示例
- `examples/factory_blackbox_example.go` - Factory黑盒模式示例

View File

@@ -1,341 +0,0 @@
# 日志工具文档
## 概述
日志工具提供了统一的日志记录功能使用Go标准库实现无需第三方依赖。
## 功能特性
- 支持多种日志级别debug, info, warn, error
- 支持多种输出方式stdout, stderr, file, both
- 支持日志文件自动创建
- 支持日志前缀
- 支持禁用时间戳
- 支持带字段的日志记录
- **支持异步/同步日志模式(默认同步)**
- 使用配置工具统一管理配置
## 使用方法
### 1. 从配置创建日志记录器(推荐)
```go
import (
"git.toowon.com/jimmy/go-common/config"
"git.toowon.com/jimmy/go-common/factory"
)
// 加载配置
cfg, err := config.LoadFromFile("./config.json")
if err != nil {
log.Fatal(err)
}
// 使用工厂创建日志记录器(已初始化,可直接使用)
fac := factory.NewFactory(cfg)
logger, err := fac.GetLogger()
if err != nil {
log.Fatal(err)
}
// 直接使用
logger.Info("Application started")
logger.Error("Failed to connect: %v", err)
```
### 2. 直接创建日志记录器
```go
import (
"git.toowon.com/jimmy/go-common/config"
"git.toowon.com/jimmy/go-common/logger"
)
// 从配置获取日志配置
cfg, _ := config.LoadFromFile("./config.json")
loggerConfig := cfg.GetLogger()
// 创建日志记录器
logger, err := logger.NewLogger(loggerConfig)
if err != nil {
log.Fatal(err)
}
// 使用默认配置如果loggerConfig为nil
logger, err := logger.NewLogger(nil)
```
### 3. 基本日志记录
```go
// 记录不同级别的日志
logger.Debug("Debug message: %s", "debug info")
logger.Info("Info message: %s", "info")
logger.Warn("Warning message: %s", "warning")
logger.Error("Error message: %s", "error")
// 致命错误(会退出程序)
logger.Fatal("Fatal error: %s", "fatal")
// 恐慌错误会触发panic
logger.Panic("Panic error: %s", "panic")
```
### 4. 带字段的日志记录
```go
// 记录带字段的日志
fields := map[string]interface{}{
"user_id": 123,
"action": "login",
}
logger.Infof(fields, "User logged in")
logger.Errorf(fields, "Failed to process request")
```
### 5. 异步/同步模式
#### 同步模式(默认)
```go
// 配置中不设置async或设置为false使用同步模式
// 同步模式:日志直接写入,会阻塞调用方直到写入完成
logger.Info("This is a synchronous log")
```
#### 异步模式
```go
// 配置中设置async为true使用异步模式
// 异步模式日志写入通过channel异步处理不阻塞调用方
// 配置文件示例:
// {
// "logger": {
// "async": true,
// "bufferSize": 1000
// }
// }
// 使用异步模式时程序退出前需要调用Close()确保所有日志写入完成
defer logger.Close()
logger.Info("This is an asynchronous log")
```
**注意:**
- `Fatal``Panic` 方法始终使用同步模式,确保日志写入后再退出/panic
- 异步模式下,程序退出前应调用 `Close()` 方法,确保所有日志写入完成
- 如果channel已满会自动降级为同步写入避免丢失日志
## API 参考
### NewLogger(cfg *config.LoggerConfig) (*Logger, error)
创建日志记录器。
**参数:**
- `cfg`: 日志配置对象如果为nil使用默认配置
**返回:** 日志记录器实例和错误信息
### (l *Logger) Debug(format string, v ...interface{})
记录调试日志。
### (l *Logger) Info(format string, v ...interface{})
记录信息日志。
### (l *Logger) Warn(format string, v ...interface{})
记录警告日志。
### (l *Logger) Error(format string, v ...interface{})
记录错误日志。
### (l *Logger) Fatal(format string, v ...interface{})
记录致命错误日志并退出程序。
### (l *Logger) Panic(format string, v ...interface{})
记录恐慌日志并触发panic。
### (l *Logger) Debugf(fields map[string]interface{}, format string, v ...interface{})
记录调试日志(带字段)。
### (l *Logger) Infof(fields map[string]interface{}, format string, v ...interface{})
记录信息日志(带字段)。
### (l *Logger) Warnf(fields map[string]interface{}, format string, v ...interface{})
记录警告日志(带字段)。
### (l *Logger) Errorf(fields map[string]interface{}, format string, v ...interface{})
记录错误日志(带字段)。
### (l *Logger) Close() error
优雅关闭logger仅异步模式需要
**说明:**
- 等待所有日志写入完成后再返回
- 同步模式下调用此方法会立即返回,无需等待
- 程序退出前应调用此方法,确保所有日志写入完成
## 配置说明
日志配置通过 `config.LoggerConfig` 提供:
| 字段 | 类型 | 说明 | 默认值 |
|------|------|------|--------|
| Level | string | 日志级别: debug, info, warn, error | info |
| Output | string | 输出方式: stdout, stderr, file, both | stdout |
| FilePath | string | 日志文件路径当output为file或both时必需 | - |
| Prefix | string | 日志前缀 | - |
| DisableTimestamp | bool | 禁用时间戳 | false |
| Async | bool | 是否使用异步模式 | false同步 |
| BufferSize | int | 异步模式下的缓冲区大小 | 1000 |
## 配置示例
### 输出到标准输出
```json
{
"logger": {
"level": "info",
"output": "stdout",
"prefix": "app"
}
}
```
### 输出到文件
```json
{
"logger": {
"level": "debug",
"output": "file",
"filePath": "./logs/app.log",
"prefix": "app"
}
}
```
### 同时输出到标准输出和文件
```json
{
"logger": {
"level": "info",
"output": "both",
"filePath": "./logs/app.log",
"prefix": "app",
"disableTimestamp": false
}
}
```
### 异步模式配置
```json
{
"logger": {
"level": "info",
"output": "file",
"filePath": "./logs/app.log",
"prefix": "app",
"async": true,
"bufferSize": 1000
}
}
```
**说明:**
- `async`: 设置为 `true` 启用异步模式,`false` 或不设置则使用同步模式(默认)
- `bufferSize`: 异步模式下的channel缓冲区大小默认1000。当缓冲区满时新的日志会阻塞直到有空间或降级为同步写入
## 日志级别说明
- **debug**: 调试信息,最详细的日志级别
- **info**: 一般信息,正常的程序运行信息
- **warn**: 警告信息,可能的问题但不影响程序运行
- **error**: 错误信息,程序运行中的错误
## 注意事项
1. **文件路径**
- 当output为`file``both`时,必须提供`filePath`
- 日志文件目录会自动创建(如果不存在)
2. **日志级别**
- 设置为`debug`时,会记录所有级别的日志
- 设置为`info`会记录info、warn、error级别的日志
- 设置为`warn`只记录warn和error级别的日志
- 设置为`error`只记录error级别的日志
3. **文件权限**
- 日志文件创建时使用0666权限
- 目录创建时使用0755权限
4. **性能考虑**
- 使用标准库log包性能较好
- 文件输出使用追加模式,不会覆盖已有日志
- 异步模式适合高并发场景,减少日志写入对业务代码的阻塞
- 同步模式适合需要确保日志立即写入的场景(如调试)
5. **异步模式注意事项**
- 异步模式下,程序退出前必须调用 `Close()` 方法,确保所有日志写入完成
- 如果channel缓冲区已满会自动降级为同步写入避免丢失日志
- `Fatal``Panic` 方法始终使用同步模式,确保日志写入后再退出/panic
## 完整示例
```go
package main
import (
"git.toowon.com/jimmy/go-common/config"
"git.toowon.com/jimmy/go-common/factory"
)
func main() {
// 加载配置
cfg, err := config.LoadFromFile("./config.json")
if err != nil {
log.Fatal(err)
}
// 使用工厂创建日志记录器
fac := factory.NewFactory(cfg)
logger, err := fac.GetLogger()
if err != nil {
log.Fatal(err)
}
// 使用日志记录器
logger.Info("Application started")
// 记录带字段的日志
logger.Infof(map[string]interface{}{
"user_id": 123,
"action": "login",
}, "User logged in successfully")
logger.Error("An error occurred: %v", err)
// 如果使用异步模式程序退出前需要关闭logger
// defer logger.Close()
}
```
## 示例
完整示例请参考 `examples/logger_example.go`

File diff suppressed because it is too large Load Diff

View File

@@ -1,442 +0,0 @@
# 数据库迁移工具文档
## 概述
数据库迁移工具提供了数据库版本管理和迁移功能支持MySQL、PostgreSQL、SQLite等数据库。使用GORM作为数据库操作库可以方便地进行数据库结构的版本控制。
## 功能特性
- 支持迁移版本管理
- 支持迁移和回滚操作
- 支持从文件系统加载迁移文件
- 支持迁移状态查询
- 自动创建迁移记录表
- 事务支持,确保迁移的原子性
## 🚀 最简单的使用方式(黑盒模式,推荐)
这是最简单的迁移方式,内部自动处理配置加载、数据库连接、迁移执行等所有细节。
### 方式一:使用独立迁移工具(推荐)
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. 创建迁移器
```go
import (
"gorm.io/driver/mysql"
"gorm.io/gorm"
"git.toowon.com/jimmy/go-common/migration"
)
// 初始化数据库连接
dsn := "user:password@tcp(localhost:3306)/dbname?charset=utf8mb4&parseTime=True&loc=Local"
db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
// 创建迁移器
migrator := migration.NewMigrator(db)
// 或者指定自定义的迁移记录表名
migrator := migration.NewMigrator(db, "my_migrations")
```
### 2. 添加迁移
#### 方式一:代码方式添加迁移
```go
migrator.AddMigration(migration.Migration{
Version: "20240101000001",
Description: "create_users_table",
Up: func(db *gorm.DB) error {
return db.Exec(`
CREATE TABLE 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
},
})
```
#### 方式二:批量添加迁移
```go
migrations := []migration.Migration{
{
Version: "20240101000001",
Description: "create_users_table",
Up: func(db *gorm.DB) error {
return db.Exec("CREATE TABLE users ...").Error
},
Down: func(db *gorm.DB) error {
return db.Exec("DROP TABLE users").Error
},
},
{
Version: "20240101000002",
Description: "add_index_to_users",
Up: func(db *gorm.DB) error {
return db.Exec("CREATE INDEX idx_email ON users(email)").Error
},
Down: func(db *gorm.DB) error {
return db.Exec("DROP INDEX idx_email ON users").Error
},
},
}
migrator.AddMigrations(migrations...)
```
#### 方式三:从文件加载迁移(推荐)
```go
// 支持的文件命名格式:
// 1. 数字前缀: 01_init_schema.sql
// 2. 时间戳: 20240101000001_create_users.sql
// 3. 带.up后缀: 20240101000001_create_users.up.sql
// 对应的回滚文件: 20240101000001_create_users.down.sql
migrations, err := migration.LoadMigrationsFromFiles("./migrations", "*.sql")
if err != nil {
log.Fatal(err)
}
migrator.AddMigrations(migrations...)
```
**新特性:**
- ✅ 支持数字前缀命名(如 `01_init_schema.sql`
- ✅ 自动分割多行 SQL 语句
- ✅ 自动处理注释(单行 `--` 和多行 `/* */`
- ✅ 记录执行时间(毫秒)
### 3. 执行迁移
```go
// 执行所有未应用的迁移
err := migrator.Up()
if err != nil {
log.Fatal(err)
}
```
### 4. 回滚迁移
```go
// 回滚最后一个迁移
err := migrator.Down()
if err != nil {
log.Fatal(err)
}
```
### 5. 查看迁移状态
```go
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)
}
```
### 6. 重置迁移
#### 方式一:仅清空迁移记录(不回滚数据库变更)
```go
// 直接调用(需要传入确认标志)
err := migrator.Reset(true)
if err != nil {
log.Fatal(err)
}
// 交互式确认(推荐,会提示警告信息)
err := migrator.ResetWithConfirm()
if err != nil {
log.Fatal(err)
}
```
#### 方式二:回滚所有迁移并清空记录
```go
// 直接调用(需要传入确认标志)
err := migrator.ResetAll(true)
if err != nil {
log.Fatal(err)
}
// 交互式确认(推荐,会提示警告信息)
err := migrator.ResetAllWithConfirm()
if err != nil {
log.Fatal(err)
}
```
**注意:**
- `Reset()` 仅清空迁移记录表,不会回滚已执行的数据库变更
- `ResetAll()` 会回滚所有已应用的迁移执行Down函数然后清空记录
- 交互式方法会显示详细的警告信息,需要输入确认文本才能执行
### 7. 生成迁移版本号
```go
// 生成基于时间戳的版本号
version := migration.GenerateVersion()
// 输出: 1704067200 (Unix时间戳)
```
## API 参考
### Migration 结构体
```go
type Migration struct {
Version string // 迁移版本号(必须唯一)
Description string // 迁移描述
Up func(*gorm.DB) error // 升级函数
Down func(*gorm.DB) error // 回滚函数(可选)
}
```
### Migrator 方法
#### NewMigrator(db *gorm.DB, tableName ...string) *Migrator
创建新的迁移器。
**参数:**
- `db`: GORM数据库连接
- `tableName`: 可选,迁移记录表名,默认为 "schema_migrations"
**返回:** 迁移器实例
#### AddMigration(migration Migration)
添加单个迁移。
#### AddMigrations(migrations ...Migration)
批量添加迁移。
#### Up() error
执行所有未应用的迁移。按版本号升序执行。
**返回:** 错误信息
#### Down() error
回滚最后一个已应用的迁移。
**返回:** 错误信息
#### Status() ([]MigrationStatus, error)
查看所有迁移的状态。
**返回:** 迁移状态列表和错误信息
#### Reset(confirm bool) error
重置所有迁移记录(仅清空记录表,不回滚数据库变更)。
**参数:**
- `confirm`: 确认标志必须为true才能执行
**返回:** 错误信息
**注意:** 此操作只清空迁移记录不会回滚已执行的迁移操作。如果需要回滚迁移请先使用Down方法逐个回滚。
#### ResetWithConfirm() error
交互式重置所有迁移记录(带确认提示)。
**返回:** 错误信息
**说明:** 会显示警告信息,需要输入"RESET"(全大写)才能执行。
#### ResetAll(confirm bool) error
重置所有迁移并回滚所有已应用的迁移。
**参数:**
- `confirm`: 确认标志必须为true才能执行
**返回:** 错误信息
**注意:** 此操作会回滚所有已应用的迁移执行Down函数然后清空迁移记录。操作不可逆请谨慎使用。
#### ResetAllWithConfirm() error
交互式重置所有迁移并回滚(带确认提示)。
**返回:** 错误信息
**说明:** 会显示警告信息,需要输入"RESET ALL"(全大写)才能执行。
### MigrationStatus 结构体
```go
type MigrationStatus struct {
Version string // 版本号
Description string // 描述
Applied bool // 是否已应用
}
```
### 辅助函数
#### LoadMigrationsFromFiles(dir string, pattern string) ([]Migration, error)
从文件系统加载迁移文件。
**参数:**
- `dir`: 迁移文件目录
- `pattern`: 文件匹配模式,如 "*.sql" 或 "*.up.sql"
**返回:** 迁移列表和错误信息
**支持的文件命名格式:**
1. **数字前缀格式**(新支持):
- `01_init_schema.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
生成基于时间戳的迁移版本号。
**返回:** Unix时间戳字符串
## 注意事项
1. **迁移版本号**:必须唯一,建议使用时间戳格式
2. **事务支持**:迁移操作在事务中执行,失败会自动回滚
3. **自动创建表**:迁移记录表会自动创建,无需手动创建
4. **回滚文件**如果迁移文件没有对应的down文件回滚操作会失败
5. **执行顺序**:迁移按版本号升序执行,确保顺序正确
6. **重置操作**
- `Reset()` 只清空迁移记录,不会回滚数据库变更
- `ResetAll()` 会回滚所有迁移,操作不可逆
- 建议使用交互式方法(`ResetWithConfirm``ResetAllWithConfirm`)以确保安全
- 在生产环境使用重置功能前,请确保已备份数据库
## 示例
完整示例请参考 `examples/migration_example.go`

View File

@@ -1,370 +0,0 @@
# 短信工具文档
## 概述
短信工具提供了阿里云短信发送功能使用Go标准库实现无需第三方依赖。
## 功能特性
- 支持阿里云短信服务
- 支持发送原始请求(完全由外部控制请求参数)
- 支持模板短信发送
- 支持批量发送
- 自动签名计算
- 使用配置工具统一管理配置
## 使用方法
### 1. 创建短信发送器
```go
import (
"git.toowon.com/jimmy/go-common/config"
"git.toowon.com/jimmy/go-common/sms"
)
// 从配置加载
cfg, err := config.LoadFromFile("./config.json")
if err != nil {
log.Fatal(err)
}
smsConfig := cfg.GetSMS()
if smsConfig == nil {
log.Fatal("SMS config is nil")
}
// 创建短信发送器
smsClient, err := sms.NewSMS(smsConfig)
if err != nil {
log.Fatal(err)
}
```
### 2. 发送原始请求(推荐,最灵活)
```go
// 外部构建完整的请求参数
params := map[string]string{
"PhoneNumbers": "13800138000,13900139000",
"SignName": "我的签名",
"TemplateCode": "SMS_123456789",
"TemplateParam": `{"code":"123456","expire":"5"}`,
}
// 发送短信(工具只负责添加系统参数、计算签名并发送)
resp, err := smsClient.SendRaw(params)
if err != nil {
log.Fatal(err)
}
fmt.Printf("发送成功RequestID: %s\n", resp.RequestID)
```
### 3. 发送简单短信(便捷方法)
```go
// 使用配置中的模板代码发送短信
templateParam := map[string]string{
"code": "123456",
}
resp, err := smsClient.SendSimple(
[]string{"13800138000"},
templateParam,
)
if err != nil {
log.Fatal(err)
}
fmt.Printf("发送成功RequestID: %s\n", resp.RequestID)
```
### 4. 使用指定模板发送短信(便捷方法)
```go
// 使用指定的模板代码发送短信
templateParam := map[string]string{
"code": "123456",
"expire": "5",
}
resp, err := smsClient.SendWithTemplate(
[]string{"13800138000"},
"SMS_123456789", // 模板代码
templateParam,
)
if err != nil {
log.Fatal(err)
}
```
### 5. 使用SendRequest结构发送便捷方法
```go
import "git.toowon.com/jimmy/go-common/sms"
req := &sms.SendRequest{
PhoneNumbers: []string{"13800138000", "13900139000"},
TemplateCode: "SMS_123456789",
TemplateParam: map[string]string{
"code": "123456",
},
SignName: "我的签名", // 可选,如果为空使用配置中的签名
}
resp, err := smsClient.Send(req)
if err != nil {
log.Fatal(err)
}
```
### 6. 使用JSON字符串作为模板参数
```go
// TemplateParam可以是JSON字符串
req := &sms.SendRequest{
PhoneNumbers: []string{"13800138000"},
TemplateCode: "SMS_123456789",
TemplateParam: `{"code":"123456","expire":"5"}`, // 直接使用JSON字符串
}
resp, err := smsClient.Send(req)
```
## API 参考
### NewSMS(cfg *config.SMSConfig) (*SMS, error)
创建短信发送器。
**参数:**
- `cfg`: 短信配置对象
**返回:** 短信发送器实例和错误信息
### (s *SMS) SendRaw(params map[string]string) (*SendResponse, error)
发送原始请求(推荐使用,最灵活)。
**参数:**
- `params`: 请求参数map工具只负责添加必要的系统参数如签名、时间戳等并发送
**返回:** 发送响应和错误信息
**说明:** 此方法允许外部完全控制请求参数,工具只负责添加系统参数、计算签名并发送。
### (s *SMS) Send(req *SendRequest) (*SendResponse, error)
发送短信使用SendRequest结构
**参数:**
- `req`: 发送请求对象
**返回:** 发送响应和错误信息
**说明:** 如果需要完全控制请求参数请使用SendRaw方法。
### (s *SMS) SendSimple(phoneNumbers []string, templateParam map[string]string) (*SendResponse, error)
发送简单短信(便捷方法,使用配置中的模板代码)。
**参数:**
- `phoneNumbers`: 手机号列表
- `templateParam`: 模板参数
### (s *SMS) SendWithTemplate(phoneNumbers []string, templateCode string, templateParam map[string]string) (*SendResponse, error)
使用指定模板发送短信(便捷方法)。
**参数:**
- `phoneNumbers`: 手机号列表
- `templateCode`: 模板代码
- `templateParam`: 模板参数
### SendRequest 结构体
```go
type SendRequest struct {
PhoneNumbers []string // 手机号列表
TemplateCode string // 模板代码(可选,如果为空使用配置中的)
TemplateParam interface{} // 模板参数可以是map[string]string或JSON字符串
SignName string // 签名(可选,如果为空使用配置中的)
}
```
### SendResponse 结构体
```go
type SendResponse struct {
RequestID string // 请求ID
Code string // 响应码OK表示成功
Message string // 响应消息
BizID string // 业务ID
}
```
## 配置说明
短信配置通过 `config.SMSConfig` 提供:
| 字段 | 类型 | 说明 | 默认值 |
|------|------|------|--------|
| AccessKeyID | string | 阿里云AccessKey ID | - |
| AccessKeySecret | string | 阿里云AccessKey Secret | - |
| Region | string | 区域cn-hangzhou | cn-hangzhou |
| SignName | string | 短信签名 | - |
| TemplateCode | string | 短信模板代码 | - |
| Endpoint | string | 服务端点(可选) | - |
| Timeout | int | 请求超时时间(秒) | 10 |
## 阿里云短信配置步骤
1. **开通阿里云短信服务**
- 登录阿里云控制台
- 开通短信服务
2. **创建AccessKey**
- 在AccessKey管理页面创建AccessKey
- 保存AccessKey ID和Secret
3. **申请短信签名**
- 在短信服务控制台申请签名
- 等待审核通过
4. **创建短信模板**
- 在短信服务控制台创建模板
- 模板格式示例:`您的验证码是${code},有效期${expire}分钟`
- 等待审核通过获取模板代码SMS_123456789
5. **配置参数**
```json
{
"sms": {
"accessKeyId": "your-access-key-id",
"accessKeySecret": "your-access-key-secret",
"region": "cn-hangzhou",
"signName": "您的签名",
"templateCode": "SMS_123456789"
}
}
```
## 模板参数示例
### 验证码模板
模板内容:`您的验证码是${code},有效期${expire}分钟`
```go
templateParam := map[string]string{
"code": "123456",
"expire": "5",
}
```
### 通知模板
模板内容:`您的订单${orderNo}已发货,物流单号:${trackingNo}`
```go
templateParam := map[string]string{
"orderNo": "ORD123456",
"trackingNo": "SF1234567890",
}
```
## 响应码说明
| Code | 说明 |
|------|------|
| OK | 发送成功 |
| InvalidSignName | 签名不存在 |
| InvalidTemplateCode | 模板不存在 |
| InvalidPhoneNumbers | 手机号格式错误 |
| Throttling | 请求被限流 |
| 其他 | 参考阿里云短信服务错误码文档 |
## 注意事项
1. **推荐使用SendRaw方法**
- `SendRaw`方法允许外部完全控制请求参数
- 可以发送任意阿里云短信API支持的请求
- 工具只负责添加系统参数、计算签名并发送
2. **模板参数格式**
- `TemplateParam`可以是`map[string]string`或JSON字符串
- 如果使用JSON字符串必须是有效的JSON格式
- 模板参数必须与模板中定义的变量匹配
3. **AccessKey安全**
- AccessKey具有账户权限请妥善保管
- 建议使用子账户AccessKey并限制权限
4. **签名和模板**
- 签名和模板需要先申请并审核通过
- 模板参数必须与模板中定义的变量匹配
5. **手机号格式**
- 支持国内手机号11位数字
- 支持国际手机号(需要加国家代码)
6. **发送频率**
- 注意阿里云的发送频率限制
- 建议实现发送频率控制
7. **错误处理**
- 所有操作都应该进行错误处理
- 建议记录详细的错误日志
- 注意区分业务错误和系统错误
8. **批量发送**
- 支持一次发送给多个手机号
- 注意批量发送的数量限制
## 完整示例
```go
package main
import (
"fmt"
"log"
"git.toowon.com/jimmy/go-common/config"
"git.toowon.com/jimmy/go-common/sms"
)
func main() {
// 加载配置
cfg, err := config.LoadFromFile("./config.json")
if err != nil {
log.Fatal(err)
}
// 创建短信发送器
smsClient, err := sms.NewSMS(cfg.GetSMS())
if err != nil {
log.Fatal(err)
}
// 发送验证码短信
templateParam := map[string]string{
"code": "123456",
"expire": "5",
}
resp, err := smsClient.SendSimple(
[]string{"13800138000"},
templateParam,
)
if err != nil {
log.Fatal(err)
}
fmt.Printf("发送成功RequestID: %s\n", resp.RequestID)
}
```
## 示例
完整示例请参考 `examples/sms_example.go`

View File

@@ -1,515 +0,0 @@
# 存储工具文档
## 概述
存储工具提供了文件上传和查看功能支持OSS和MinIO两种存储方式并提供HTTP处理器用于文件上传和代理查看。
## 功能特性
- 支持OSS对象存储阿里云、腾讯云、AWS、七牛云等
- 支持MinIO对象存储
- 提供统一的存储接口
- 支持文件上传HTTP处理器
- 支持文件代理查看HTTP处理器
- 支持文件大小和扩展名限制
- 自动生成唯一文件名
- 支持自定义对象键前缀
## 使用方法
### 1. 创建存储实例
```go
import (
"git.toowon.com/jimmy/go-common/config"
"git.toowon.com/jimmy/go-common/storage"
)
// 加载配置
cfg, err := config.LoadFromFile("./config.json")
if err != nil {
log.Fatal(err)
}
// 创建OSS存储实例
ossStorage, err := storage.NewStorage(storage.StorageTypeOSS, cfg)
if err != nil {
log.Fatal(err)
}
// 创建MinIO存储实例
minioStorage, err := storage.NewStorage(storage.StorageTypeMinIO, cfg)
if err != nil {
log.Fatal(err)
}
```
### 2. 上传文件
```go
import (
"context"
"os"
"git.toowon.com/jimmy/go-common/storage"
)
// 打开文件
file, err := os.Open("test.jpg")
if err != nil {
log.Fatal(err)
}
defer file.Close()
// 上传文件
ctx := context.Background()
objectKey := "images/test.jpg"
err = ossStorage.Upload(ctx, objectKey, file, "image/jpeg")
if err != nil {
log.Fatal(err)
}
// 获取文件URL
url, err := ossStorage.GetURL(objectKey, 0)
if err != nil {
log.Fatal(err)
}
fmt.Printf("File URL: %s\n", url)
```
### 3. 使用HTTP处理器上传文件
```go
import (
"net/http"
"git.toowon.com/jimmy/go-common/storage"
)
// 创建上传处理器
uploadHandler := storage.NewUploadHandler(storage.UploadHandlerConfig{
Storage: ossStorage,
MaxFileSize: 10 * 1024 * 1024, // 10MB
AllowedExts: []string{".jpg", ".jpeg", ".png", ".gif"},
ObjectPrefix: "images/",
})
// 注册路由
http.Handle("/upload", uploadHandler)
http.ListenAndServe(":8080", nil)
```
**上传请求示例:**
```bash
curl -X POST http://localhost:8080/upload \
-F "file=@test.jpg" \
-F "prefix=images/"
```
**响应示例:**
```json
{
"code": 0,
"message": "Upload successful",
"timestamp": 1704067200,
"data": {
"objectKey": "images/test_1704067200000000000.jpg",
"url": "https://bucket.oss-cn-hangzhou.aliyuncs.com/images/test_1704067200000000000.jpg",
"size": 102400,
"contentType": "image/jpeg",
"uploadTime": "2024-01-01T12:00:00Z"
}
}
```
### 4. 使用HTTP处理器查看文件
```go
import (
"net/http"
"git.toowon.com/jimmy/go-common/storage"
)
// 创建代理查看处理器
proxyHandler := storage.NewProxyHandler(ossStorage)
// 注册路由
http.Handle("/file", proxyHandler)
http.ListenAndServe(":8080", nil)
```
**查看请求示例:**
```
GET /file?key=images/test.jpg
```
### 5. 生成对象键
```go
import "git.toowon.com/jimmy/go-common/storage"
// 生成简单对象键
objectKey := storage.GenerateObjectKey("images/", "test.jpg")
// 输出: "images/test.jpg"
// 生成带日期的对象键
objectKey := storage.GenerateObjectKeyWithDate("images", "test.jpg")
// 输出: "images/2024/01/01/test.jpg"
```
### 6. 删除文件
```go
ctx := context.Background()
err := ossStorage.Delete(ctx, "images/test.jpg")
if err != nil {
log.Fatal(err)
}
```
### 7. 检查文件是否存在
```go
ctx := context.Background()
exists, err := ossStorage.Exists(ctx, "images/test.jpg")
if err != nil {
log.Fatal(err)
}
if exists {
fmt.Println("File exists")
}
```
## API 参考
### Storage 接口
```go
type Storage interface {
// Upload 上传文件
Upload(ctx context.Context, objectKey string, reader io.Reader, contentType ...string) error
// GetURL 获取文件访问URL
GetURL(objectKey string, expires int64) (string, error)
// Delete 删除文件
Delete(ctx context.Context, objectKey string) error
// Exists 检查文件是否存在
Exists(ctx context.Context, objectKey string) (bool, error)
// GetObject 获取文件内容
GetObject(ctx context.Context, objectKey string) (io.ReadCloser, error)
}
```
### NewStorage(storageType StorageType, cfg *config.Config) (Storage, error)
创建存储实例。
**参数:**
- `storageType`: 存储类型(`storage.StorageTypeOSS``storage.StorageTypeMinIO`
- `cfg`: 配置对象
**返回:** 存储实例和错误信息
### UploadHandler
文件上传HTTP处理器。
#### NewUploadHandler(cfg UploadHandlerConfig) *UploadHandler
创建上传处理器。
**配置参数:**
- `Storage`: 存储实例
- `MaxFileSize`: 最大文件大小字节0表示不限制
- `AllowedExts`: 允许的文件扩展名,空表示不限制
- `ObjectPrefix`: 对象键前缀
#### 请求格式
- **方法**: POST
- **表单字段**:
- `file`: 文件(必需)
- `prefix`: 对象键前缀(可选,会覆盖配置中的前缀)
#### 响应格式
```json
{
"code": 0,
"message": "Upload successful",
"timestamp": 1704067200,
"data": {
"objectKey": "images/test.jpg",
"url": "https://...",
"size": 102400,
"contentType": "image/jpeg",
"uploadTime": "2024-01-01T12:00:00Z"
}
}
```
### ProxyHandler
文件代理查看HTTP处理器。
#### NewProxyHandler(storage Storage) *ProxyHandler
创建代理查看处理器。
#### 请求格式
- **方法**: GET
- **URL参数**:
- `key`: 对象键(必需)
#### 响应
- **成功**直接返回文件内容二进制设置适当的Content-Type
- **错误**返回标准HTTP错误状态码和错误消息文本格式
- `400 Bad Request`: 缺少必需参数
- `404 Not Found`: 文件不存在
- `405 Method Not Allowed`: 请求方法不正确
- `500 Internal Server Error`: 系统错误
**注意**`ProxyHandler` 返回的是文件内容二进制而不是JSON响应。错误时使用标准HTTP状态码保持与文件响应的一致性。
### 辅助函数
#### GenerateObjectKey(prefix, filename string) string
生成对象键。
#### GenerateObjectKeyWithDate(prefix, filename string) string
生成带日期的对象键(格式: prefix/YYYY/MM/DD/filename
## 完整示例
### 示例1文件上传和查看
```go
package main
import (
"log"
"net/http"
"git.toowon.com/jimmy/go-common/config"
"git.toowon.com/jimmy/go-common/middleware"
"git.toowon.com/jimmy/go-common/storage"
)
func main() {
// 加载配置
cfg, err := config.LoadFromFile("./config.json")
if err != nil {
log.Fatal(err)
}
// 创建存储实例使用OSS
ossStorage, err := storage.NewStorage(storage.StorageTypeOSS, cfg)
if err != nil {
log.Fatal(err)
}
// 创建上传处理器
uploadHandler := storage.NewUploadHandler(storage.UploadHandlerConfig{
Storage: ossStorage,
MaxFileSize: 10 * 1024 * 1024, // 10MB
AllowedExts: []string{".jpg", ".jpeg", ".png", ".gif", ".pdf"},
ObjectPrefix: "uploads/",
})
// 创建代理查看处理器
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(
middleware.CORS(corsConfig),
middleware.Timezone,
)
// 注册路由
mux := http.NewServeMux()
mux.Handle("/upload", chain.Then(uploadHandler))
mux.Handle("/file", chain.Then(proxyHandler))
log.Println("Server started on :8080")
log.Fatal(http.ListenAndServe(":8080", mux))
}
```
### 示例2直接使用存储接口
```go
package main
import (
"context"
"fmt"
"log"
"os"
"git.toowon.com/jimmy/go-common/config"
"git.toowon.com/jimmy/go-common/storage"
)
func main() {
// 加载配置
cfg, err := config.LoadFromFile("./config.json")
if err != nil {
log.Fatal(err)
}
// 创建存储实例
s, err := storage.NewStorage(storage.StorageTypeMinIO, cfg)
if err != nil {
log.Fatal(err)
}
// 打开文件
file, err := os.Open("test.jpg")
if err != nil {
log.Fatal(err)
}
defer file.Close()
// 生成对象键
objectKey := storage.GenerateObjectKeyWithDate("images", "test.jpg")
// 上传文件
ctx := context.Background()
err = s.Upload(ctx, objectKey, file, "image/jpeg")
if err != nil {
log.Fatal(err)
}
// 获取文件URL
url, err := s.GetURL(objectKey, 0)
if err != nil {
log.Fatal(err)
}
fmt.Printf("File uploaded: %s\n", url)
}
```
## 注意事项
1. **OSS和MinIO SDK实现**
- 当前实现提供了接口和框架但具体的OSS和MinIO SDK集成需要根据实际使用的SDK实现
- 需要在`oss.go``minio.go`中实现具体的SDK调用
2. **文件大小限制**
- 建议设置合理的文件大小限制
- 大文件上传可能需要分片上传
3. **文件扩展名验证**
- 建议限制允许的文件类型,防止上传恶意文件
- 仅验证扩展名不够安全,建议结合文件内容验证
4. **安全性**
- 上传接口应该添加身份验证
- 代理查看接口可以添加访问控制
5. **性能优化**
- 对于大文件,考虑使用分片上传
- 代理查看可以添加缓存机制
6. **错误处理**
- 所有操作都应该进行错误处理
- 建议记录详细的错误日志
## 实现OSS和MinIO SDK集成
由于不同的OSS提供商和MinIO有不同的SDK当前实现提供了框架需要根据实际情况集成
### OSS SDK集成示例阿里云OSS
```go
import (
"github.com/aliyun/aliyun-oss-go-sdk/oss"
)
func NewOSSStorage(cfg *config.OSSConfig) (*OSSStorage, error) {
client, err := oss.New(cfg.Endpoint, cfg.AccessKeyID, cfg.AccessKeySecret)
if err != nil {
return nil, err
}
storage := &OSSStorage{
config: cfg,
client: client,
}
return storage, nil
}
func (s *OSSStorage) Upload(ctx context.Context, objectKey string, reader io.Reader, contentType ...string) error {
bucket, err := s.client.Bucket(s.config.Bucket)
if err != nil {
return err
}
options := []oss.Option{}
if len(contentType) > 0 && contentType[0] != "" {
options = append(options, oss.ContentType(contentType[0]))
}
return bucket.PutObject(objectKey, reader, options...)
}
```
### MinIO SDK集成示例
```go
import (
"github.com/minio/minio-go/v7"
"github.com/minio/minio-go/v7/pkg/credentials"
)
func NewMinIOStorage(cfg *config.MinIOConfig) (*MinIOStorage, error) {
client, err := minio.New(cfg.Endpoint, &minio.Options{
Creds: credentials.NewStaticV4(cfg.AccessKeyID, cfg.SecretAccessKey, ""),
Secure: cfg.UseSSL,
})
if err != nil {
return nil, err
}
storage := &MinIOStorage{
config: cfg,
client: client,
}
return storage, nil
}
func (s *MinIOStorage) Upload(ctx context.Context, objectKey string, reader io.Reader, contentType ...string) error {
ct := "application/octet-stream"
if len(contentType) > 0 && contentType[0] != "" {
ct = contentType[0]
}
_, err := s.client.PutObject(ctx, s.config.Bucket, objectKey, reader, -1, minio.PutObjectOptions{
ContentType: ct,
})
return err
}
```
## 示例
完整示例请参考 `examples/storage_example.go`

View File

@@ -2,18 +2,38 @@ package email
import ( import (
"bytes" "bytes"
"context"
"crypto/tls" "crypto/tls"
"fmt" "fmt"
"net" "net"
"net/smtp" "net/smtp"
"sync"
"sync/atomic"
"time" "time"
"git.toowon.com/jimmy/go-common/config" "git.toowon.com/jimmy/go-common/config"
"git.toowon.com/jimmy/go-common/logger"
) )
// Email 邮件发送器 // Email 邮件发送器
type Email struct { type Email struct {
config *config.EmailConfig config *config.EmailConfig
async bool
queue chan emailTask
workers int
wg sync.WaitGroup
closed bool
mu sync.Mutex
dropped atomic.Uint64
}
type emailTask struct {
to []string
subject string
body string
htmlBody string
requestID string
} }
// NewEmail 创建邮件发送器 // NewEmail 创建邮件发送器
@@ -21,28 +41,55 @@ func NewEmail(cfg *config.Config) *Email {
if cfg == nil || cfg.Email == nil { if cfg == nil || cfg.Email == nil {
return &Email{config: nil} return &Email{config: nil}
} }
return &Email{config: cfg.Email} e := &Email{
config: cfg.Email,
async: cfg.Email.IsAsync(),
workers: cfg.Email.Workers,
}
if e.workers <= 0 {
e.workers = 2
}
queueSize := cfg.Email.QueueSize
if queueSize <= 0 {
queueSize = 1000
}
if e.async {
e.queue = make(chan emailTask, queueSize)
for i := 0; i < e.workers; i++ {
e.wg.Add(1)
go e.worker()
}
}
return e
}
func (e *Email) worker() {
defer e.wg.Done()
for task := range e.queue {
if err := e.SendEmail(task.to, task.subject, task.body, task.htmlBody); err != nil {
fields := map[string]any{
"error": err.Error(),
"request_id": task.requestID,
"to": task.to,
}
logger.FromContext(context.Background()).Error("async email send failed", fields)
}
}
} }
// getEmailConfig 获取邮件配置(内部方法)
func (e *Email) getEmailConfig() (*config.EmailConfig, error) { func (e *Email) getEmailConfig() (*config.EmailConfig, error) {
if e.config == nil { if e.config == nil {
return nil, fmt.Errorf("email config is nil") return nil, fmt.Errorf("email config is nil")
} }
if e.config.Host == "" { if e.config.Host == "" {
return nil, fmt.Errorf("email host is required") return nil, fmt.Errorf("email host is required")
} }
if e.config.Username == "" { if e.config.Username == "" {
return nil, fmt.Errorf("email username is required") return nil, fmt.Errorf("email username is required")
} }
if e.config.Password == "" { if e.config.Password == "" {
return nil, fmt.Errorf("email password is required") return nil, fmt.Errorf("email password is required")
} }
// 设置默认值
if e.config.Port == 0 { if e.config.Port == 0 {
e.config.Port = 587 e.config.Port = 587
} }
@@ -50,224 +97,177 @@ func (e *Email) getEmailConfig() (*config.EmailConfig, error) {
e.config.From = e.config.Username e.config.From = e.config.Username
} }
if e.config.Timeout == 0 { if e.config.Timeout == 0 {
e.config.Timeout = 30 e.config.Timeout = 5
} }
return e.config, nil return e.config, nil
} }
// Message 邮件消息 // Message 邮件消息
type Message struct { type Message struct {
// To 收件人列表 To []string
To []string Cc []string
Bcc []string
// Cc 抄送列表(可选) Subject string
Cc []string Body string
// Bcc 密送列表(可选)
Bcc []string
// Subject 主题
Subject string
// Body 正文(纯文本)
Body string
// HTMLBody HTML正文可选如果设置了会优先使用
HTMLBody string HTMLBody string
} }
// SendEmail 发送邮件 // SendEmail 同步发送邮件(验证码等需等待结果的场景)
// to: 收件人列表
// subject: 邮件主题
// body: 邮件正文(纯文本)
// htmlBody: HTML正文可选如果设置了会优先使用
func (e *Email) SendEmail(to []string, subject, body string, htmlBody ...string) error { func (e *Email) SendEmail(to []string, subject, body string, htmlBody ...string) error {
cfg, err := e.getEmailConfig() cfg, err := e.getEmailConfig()
if err != nil { if err != nil {
return err return err
} }
msg := &Message{To: to, Subject: subject, Body: body}
msg := &Message{
To: to,
Subject: subject,
Body: body,
}
if len(htmlBody) > 0 && htmlBody[0] != "" { if len(htmlBody) > 0 && htmlBody[0] != "" {
msg.HTMLBody = htmlBody[0] msg.HTMLBody = htmlBody[0]
} }
return e.send(msg, cfg) return e.send(msg, cfg)
} }
// send 发送邮件(内部方法 // SendEmailAsync 异步发送邮件HTTP 通知类场景
func (e *Email) SendEmailAsync(ctx context.Context, to []string, subject, body string, htmlBody ...string) {
task := emailTask{
to: append([]string(nil), to...),
subject: subject,
body: body,
requestID: logger.RequestIDFromContext(ctx),
}
if len(htmlBody) > 0 {
task.htmlBody = htmlBody[0]
}
if !e.async {
_ = e.SendEmail(task.to, task.subject, task.body, task.htmlBody)
return
}
select {
case e.queue <- task:
default:
e.dropped.Add(1)
logger.FromContext(ctx).Error("email queue full, task dropped", map[string]any{
"to": to,
})
}
}
// Close 关闭异步 worker
func (e *Email) Close() error {
if !e.async {
return nil
}
e.mu.Lock()
if e.closed {
e.mu.Unlock()
return nil
}
e.closed = true
e.mu.Unlock()
close(e.queue)
e.wg.Wait()
return nil
}
func (e *Email) send(msg *Message, cfg *config.EmailConfig) error { func (e *Email) send(msg *Message, cfg *config.EmailConfig) error {
if msg == nil { if msg == nil {
return fmt.Errorf("message is nil") return fmt.Errorf("message is nil")
} }
if len(msg.To) == 0 { if len(msg.To) == 0 {
return fmt.Errorf("recipients are required") return fmt.Errorf("recipients are required")
} }
if msg.Subject == "" { if msg.Subject == "" {
return fmt.Errorf("subject is required") return fmt.Errorf("subject is required")
} }
if msg.Body == "" && msg.HTMLBody == "" { if msg.Body == "" && msg.HTMLBody == "" {
return fmt.Errorf("body or HTMLBody is required") return fmt.Errorf("body or HTMLBody is required")
} }
// 构建邮件内容
emailBody, err := e.buildEmailBody(msg, cfg) emailBody, err := e.buildEmailBody(msg, cfg)
if err != nil { if err != nil {
return fmt.Errorf("failed to build email body: %w", err) return fmt.Errorf("failed to build email body: %w", err)
} }
// 合并收件人列表
recipients := append(msg.To, msg.Cc...) recipients := append(msg.To, msg.Cc...)
recipients = append(recipients, msg.Bcc...) recipients = append(recipients, msg.Bcc...)
// 连接SMTP服务器
addr := net.JoinHostPort(cfg.Host, fmt.Sprintf("%d", cfg.Port)) addr := net.JoinHostPort(cfg.Host, fmt.Sprintf("%d", cfg.Port))
auth := smtp.PlainAuth("", cfg.Username, cfg.Password, cfg.Host) auth := smtp.PlainAuth("", cfg.Username, cfg.Password, cfg.Host)
// 创建连接
conn, err := net.DialTimeout("tcp", addr, time.Duration(cfg.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客户端
client, err := smtp.NewClient(conn, cfg.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处理 if cfg.UseSSL || cfg.UseTLS {
if cfg.UseSSL { tlsConfig := &tls.Config{ServerName: cfg.Host}
// SSL模式端口通常是465
tlsConfig := &tls.Config{
ServerName: cfg.Host,
}
if err := client.StartTLS(tlsConfig); err != nil {
return fmt.Errorf("failed to start TLS: %w", err)
}
} else if cfg.UseTLS {
// TLS模式STARTTLS端口通常是587
tlsConfig := &tls.Config{
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)
} }
} }
// 认证
if err := client.Auth(auth); err != nil { if err := client.Auth(auth); err != nil {
return fmt.Errorf("failed to authenticate: %w", err) return fmt.Errorf("failed to authenticate: %w", err)
} }
// 设置发件人
if err := client.Mail(cfg.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)
} }
// 设置收件人
for _, to := range recipients { for _, to := range recipients {
if err := client.Rcpt(to); err != nil { if err := client.Rcpt(to); err != nil {
return fmt.Errorf("failed to set recipient %s: %w", to, err) return fmt.Errorf("failed to set recipient %s: %w", to, err)
} }
} }
// 发送邮件内容
writer, err := client.Data() writer, err := client.Data()
if err != nil { if err != nil {
return fmt.Errorf("failed to get data writer: %w", err) return fmt.Errorf("failed to get data writer: %w", err)
} }
if _, err = writer.Write(emailBody); err != nil {
_, err = writer.Write(emailBody) _ = writer.Close()
if err != nil {
writer.Close()
return fmt.Errorf("failed to write email body: %w", err) return fmt.Errorf("failed to write email body: %w", err)
} }
if err = writer.Close(); err != nil {
err = writer.Close()
if err != nil {
return fmt.Errorf("failed to close writer: %w", err) return fmt.Errorf("failed to close writer: %w", err)
} }
// 退出
if err := client.Quit(); err != nil { if err := client.Quit(); err != nil {
return fmt.Errorf("failed to quit: %w", err) return fmt.Errorf("failed to quit: %w", err)
} }
return nil return nil
} }
// buildEmailBody 构建邮件内容
func (e *Email) buildEmailBody(msg *Message, cfg *config.EmailConfig) ([]byte, error) { func (e *Email) buildEmailBody(msg *Message, cfg *config.EmailConfig) ([]byte, error) {
var buf bytes.Buffer var buf bytes.Buffer
// 邮件头
from := cfg.From from := cfg.From
if cfg.FromName != "" { if cfg.FromName != "" {
from = fmt.Sprintf("%s <%s>", cfg.FromName, cfg.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))
// 收件人
buf.WriteString(fmt.Sprintf("To: %s\r\n", joinEmails(msg.To))) buf.WriteString(fmt.Sprintf("To: %s\r\n", joinEmails(msg.To)))
// 抄送
if len(msg.Cc) > 0 { if len(msg.Cc) > 0 {
buf.WriteString(fmt.Sprintf("Cc: %s\r\n", joinEmails(msg.Cc))) buf.WriteString(fmt.Sprintf("Cc: %s\r\n", joinEmails(msg.Cc)))
} }
// 主题
buf.WriteString(fmt.Sprintf("Subject: %s\r\n", msg.Subject)) buf.WriteString(fmt.Sprintf("Subject: %s\r\n", msg.Subject))
// 内容类型
if msg.HTMLBody != "" { if msg.HTMLBody != "" {
// 多部分邮件HTML + 纯文本)
boundary := "----=_Part_" + fmt.Sprint(time.Now().UnixNano()) boundary := "----=_Part_" + fmt.Sprint(time.Now().UnixNano())
buf.WriteString("MIME-Version: 1.0\r\n") buf.WriteString("MIME-Version: 1.0\r\n")
buf.WriteString(fmt.Sprintf("Content-Type: multipart/alternative; boundary=\"%s\"\r\n", boundary)) buf.WriteString(fmt.Sprintf("Content-Type: multipart/alternative; boundary=\"%s\"\r\n\r\n", boundary))
buf.WriteString("\r\n") buf.WriteString("--" + boundary + "\r\nContent-Type: text/plain; charset=UTF-8\r\n\r\n")
buf.WriteString(msg.Body + "\r\n")
// 纯文本部分 buf.WriteString("--" + boundary + "\r\nContent-Type: text/html; charset=UTF-8\r\n\r\n")
buf.WriteString("--" + boundary + "\r\n") buf.WriteString(msg.HTMLBody + "\r\n")
buf.WriteString("Content-Type: text/plain; charset=UTF-8\r\n")
buf.WriteString("Content-Transfer-Encoding: quoted-printable\r\n")
buf.WriteString("\r\n")
buf.WriteString(msg.Body)
buf.WriteString("\r\n")
// HTML部分
buf.WriteString("--" + boundary + "\r\n")
buf.WriteString("Content-Type: text/html; charset=UTF-8\r\n")
buf.WriteString("Content-Transfer-Encoding: quoted-printable\r\n")
buf.WriteString("\r\n")
buf.WriteString(msg.HTMLBody)
buf.WriteString("\r\n")
buf.WriteString("--" + boundary + "--\r\n") buf.WriteString("--" + boundary + "--\r\n")
} else { } else {
// 纯文本邮件 buf.WriteString("Content-Type: text/plain; charset=UTF-8\r\n\r\n")
buf.WriteString("Content-Type: text/plain; charset=UTF-8\r\n") buf.WriteString(msg.Body + "\r\n")
buf.WriteString("Content-Transfer-Encoding: quoted-printable\r\n")
buf.WriteString("\r\n")
buf.WriteString(msg.Body)
buf.WriteString("\r\n")
} }
return buf.Bytes(), nil return buf.Bytes(), nil
} }
// joinEmails 连接邮箱地址
func joinEmails(emails []string) string { func joinEmails(emails []string) string {
if len(emails) == 0 { if len(emails) == 0 {
return "" return ""
@@ -278,4 +278,3 @@ func joinEmails(emails []string) string {
} }
return result return result
} }

View File

@@ -1,3 +1,6 @@
//go:build example
// +build example
package main package main
import ( import (

8
examples/doc.go Normal file
View File

@@ -0,0 +1,8 @@
// Package examples contains build-tagged example programs.
//
// 所有示例程序默认不参与 `go test ./...` 编译,避免多个 main 冲突。
//
// 运行示例:
// go run -tags example ./examples/storage_example.go
package examples

View File

@@ -1,3 +1,6 @@
//go:build example
// +build example
package main package main
import ( import (
@@ -5,117 +8,35 @@ import (
"log" "log"
"git.toowon.com/jimmy/go-common/config" "git.toowon.com/jimmy/go-common/config"
"git.toowon.com/jimmy/go-common/email" "git.toowon.com/jimmy/go-common/factory"
) )
func main() { func main() {
// 加载配置
cfg, err := config.LoadFromFile("./config/example.json") cfg, err := config.LoadFromFile("./config/example.json")
if err != nil { if err != nil {
log.Fatal("Failed to load config:", err) log.Fatal(err)
} }
// 创建邮件发送器 app := factory.New(cfg)
emailConfig := cfg.GetEmail() mail, err := app.Email()
if emailConfig == nil {
log.Fatal("Email config is nil")
}
mailer, err := email.NewEmail(emailConfig)
if err != nil { if err != nil {
log.Fatal("Failed to create email client:", err) log.Fatal(err)
} }
defer mail.Close()
// 示例1发送原始邮件内容推荐最灵活 // 同步发送(验证码等需等待结果
fmt.Println("=== Example 1: Send Raw Email Content ===") err = mail.SendEmail(
// 外部构建完整的邮件内容MIME格式
emailBody := []byte(`From: ` + emailConfig.From + `
To: recipient@example.com
Subject: 原始邮件测试
Content-Type: text/html; charset=UTF-8
<html>
<body>
<h1>这是原始邮件内容</h1>
<p>由外部完全控制邮件格式和内容</p>
</body>
</html>
`)
err = mailer.SendRaw(
[]string{"recipient@example.com"},
emailBody,
)
if err != nil {
log.Printf("Failed to send raw email: %v", err)
} else {
fmt.Println("Raw email sent successfully")
}
// 示例2发送简单邮件便捷方法
fmt.Println("\n=== Example 2: Send Simple Email ===")
err = mailer.SendSimple(
[]string{"recipient@example.com"}, []string{"recipient@example.com"},
"测试邮件", "测试邮件",
"这是一封测试邮件使用Go标准库发送。", "这是一封测试邮件。",
) )
if err != nil { if err != nil {
log.Printf("Failed to send email: %v", err) log.Printf("sync send failed: %v", err)
} else { } else {
fmt.Println("Email sent successfully") fmt.Println("sync email sent")
} }
// 示例3发送HTML邮件 // 异步发送HTTP 通知类)
fmt.Println("\n=== Example 3: Send HTML Email ===") mail.SendEmailAsync(nil, []string{"recipient@example.com"}, "异步通知", "后台发送,不阻塞请求")
htmlBody := ` fmt.Println("async email enqueued")
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<h1>欢迎使用邮件服务</h1>
<p>这是一封HTML格式的邮件。</p>
<p>支持<strong>富文本</strong>格式。</p>
</body>
</html>
`
err = mailer.SendHTML(
[]string{"recipient@example.com"},
"HTML邮件测试",
htmlBody,
)
if err != nil {
log.Printf("Failed to send HTML email: %v", err)
} else {
fmt.Println("HTML email sent successfully")
}
// 示例4发送完整邮件包含抄送、密送
fmt.Println("\n=== Example 4: Send Full Email ===")
msg := &email.Message{
To: []string{"to@example.com"},
Cc: []string{"cc@example.com"},
Bcc: []string{"bcc@example.com"},
Subject: "完整邮件示例",
Body: "这是纯文本正文",
HTMLBody: `
<html>
<body>
<h1>这是HTML正文</h1>
<p>支持同时发送纯文本和HTML版本。</p>
</body>
</html>
`,
}
err = mailer.Send(msg)
if err != nil {
log.Printf("Failed to send full email: %v", err)
} else {
fmt.Println("Full email sent successfully")
}
fmt.Println("\nNote: Make sure your email configuration is correct and SMTP service is enabled.")
} }

69
examples/excel_example.go Normal file
View File

@@ -0,0 +1,69 @@
//go:build example
// +build example
package main
import (
"fmt"
"log"
"os"
"time"
"git.toowon.com/jimmy/go-common/excel"
"git.toowon.com/jimmy/go-common/factory"
"git.toowon.com/jimmy/go-common/tools"
)
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() {
app := factory.New(nil)
ex := app.Excel()
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: 0},
}
columns := []excel.ExportColumn{
{Header: "ID", Field: "ID", Width: 10},
{Header: "姓名", Field: "Name", Width: 20},
{Header: "邮箱", Field: "Email", Width: 30},
{
Header: "创建时间",
Field: "CreatedAt",
Format: excel.AdaptTimeFormatter(tools.FormatDateTime),
},
{
Header: "状态",
Field: "Status",
Format: func(value interface{}) string {
if status, ok := value.(int); ok && status == 1 {
return "启用"
}
return "禁用"
},
},
}
if err := ex.ExportToFile("users.xlsx", "用户列表", columns, users); err != nil {
log.Fatal(err)
}
fmt.Println("exported users.xlsx")
f, err := os.Create("users_http.xlsx")
if err != nil {
log.Fatal(err)
}
defer f.Close()
if err := ex.ExportToWriter(f, "用户列表", columns, users); err != nil {
log.Fatal(err)
}
fmt.Println("exported users_http.xlsx")
}

View File

@@ -1,166 +0,0 @@
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,
}, "请求指标")
})
}

View File

@@ -1,111 +1,52 @@
//go:build example
// +build example
package main package main
import ( import (
"log" "log"
"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/factory"
commonhttp "git.toowon.com/jimmy/go-common/http"
) )
// 用户结构
type User struct { type User struct {
ID int64 `json:"id"` ID int64 `json:"id"`
Name string `json:"name"` Name string `json:"name"`
Email string `json:"email"` Email string `json:"email"`
} }
// 获取用户列表使用公共方法和factory func main() {
func GetUserList(w http.ResponseWriter, r *http.Request) { if err := factory.Init("config.json"); err != nil {
fac, _ := factory.NewFactoryFromFile("config.json") log.Fatal(err)
}
app := factory.Default()
chain := app.MiddlewareChain()
// 获取分页参数(使用公共方法) http.Handle("/users", chain.ThenFunc(listUsers))
pagination := commonhttp.ParsePaginationRequest(r) log.Fatal(http.ListenAndServe(":8080", nil))
page := pagination.GetPage() }
pageSize := pagination.GetSize()
// 获取查询参数(使用公共方法) func listUsers(w http.ResponseWriter, r *http.Request) {
_ = commonhttp.GetQuery(r, "keyword", "") // 示例:获取查询参数 app := factory.Default()
i18n, _ := app.I18n()
h := commonhttp.NewHandler(w, r, commonhttp.WithI18n(i18n))
// 模拟查询数据 var req struct {
Keyword string `json:"keyword"`
commonhttp.PaginationRequest
}
if err := h.ParseJSON(&req); err != nil {
h.Error("common.invalid_request")
return
}
p := h.Pagination()
users := []User{ users := []User{
{ID: 1, Name: "User1", Email: "user1@example.com"}, {ID: 1, Name: "User1", Email: "user1@example.com"},
{ID: 2, Name: "User2", Email: "user2@example.com"}, {ID: 2, Name: "User2", Email: "user2@example.com"},
} }
total := int64(100) h.SuccessPage(users, 100)
_ = p
// 返回分页响应使用factory方法
fac.SuccessPage(w, users, total, page, pageSize)
}
// 创建用户使用公共方法和factory
func CreateUser(w http.ResponseWriter, r *http.Request) {
fac, _ := factory.NewFactoryFromFile("config.json")
// 解析请求体(使用公共方法)
var req struct {
Name string `json:"name"`
Email string `json:"email"`
}
if err := commonhttp.ParseJSON(r, &req); err != nil {
commonhttp.WriteJSON(w, http.StatusBadRequest, 400, "请求参数解析失败", nil)
return
}
// 参数验证
if req.Name == "" {
fac.Error(w, 1001, "用户名不能为空")
return
}
// 模拟创建用户
user := User{
ID: 1,
Name: req.Name,
Email: req.Email,
}
// 返回成功响应使用factory方法统一Success方法
fac.Success(w, user, "创建成功")
}
// 获取用户详情使用公共方法和factory
func GetUser(w http.ResponseWriter, r *http.Request) {
fac, _ := factory.NewFactoryFromFile("config.json")
// 获取查询参数(使用公共方法)
id := commonhttp.GetQueryInt64(r, "id", 0)
if id == 0 {
commonhttp.WriteJSON(w, http.StatusBadRequest, 400, "用户ID不能为空", nil)
return
}
// 模拟查询用户
if id == 1 {
user := User{ID: 1, Name: "User1", Email: "user1@example.com"}
fac.Success(w, user)
} else {
fac.Error(w, 1002, "用户不存在")
}
}
func main() {
// 使用标准http.HandleFunc
http.HandleFunc("/users", func(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case http.MethodGet:
GetUserList(w, r)
case http.MethodPost:
CreateUser(w, r)
default:
commonhttp.WriteJSON(w, http.StatusMethodNotAllowed, 405, "方法不支持", nil)
}
})
http.HandleFunc("/user", GetUser)
log.Println("Server started on :8080")
log.Fatal(http.ListenAndServe(":8080", nil))
} }

View File

@@ -1,63 +1,57 @@
//go:build example
// +build example
package main package main
import ( import (
"log" "log"
"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/factory"
commonhttp "git.toowon.com/jimmy/go-common/http"
) )
// ListUserRequest 用户列表请求(包含分页字段)
type ListUserRequest struct { type ListUserRequest struct {
Keyword string `json:"keyword"` Keyword string `json:"keyword"`
commonhttp.PaginationRequest // 嵌入分页请求结构 commonhttp.PaginationRequest
} }
// User 用户结构
type User struct { type User struct {
ID int64 `json:"id"` ID int64 `json:"id"`
Name string `json:"name"` Name string `json:"name"`
Email string `json:"email"` Email string `json:"email"`
} }
// 获取用户列表使用公共方法和factory func main() {
func GetUserList(w http.ResponseWriter, r *http.Request) { if err := factory.Init("config.json"); err != nil {
fac, _ := factory.NewFactoryFromFile("config.json") log.Fatal(err)
var req ListUserRequest }
app := factory.Default()
chain := app.MiddlewareChain()
http.Handle("/users", chain.ThenFunc(listUsers))
log.Fatal(http.ListenAndServe(":8080", nil))
}
// 方式1从JSON请求体解析分页字段会自动解析 func listUsers(w http.ResponseWriter, r *http.Request) {
app := factory.Default()
i18n, _ := app.I18n()
h := commonhttp.NewHandler(w, r, commonhttp.WithI18n(i18n))
var req ListUserRequest
if r.Method == http.MethodPost { if r.Method == http.MethodPost {
if err := commonhttp.ParseJSON(r, &req); err != nil { if err := h.ParseJSON(&req); err != nil {
commonhttp.WriteJSON(w, http.StatusBadRequest, 400, "请求参数解析失败", nil) h.Error("common.invalid_request")
return return
} }
} else { } else {
// 方式2从查询参数解析分页 p := h.Pagination()
pagination := commonhttp.ParsePaginationRequest(r) req.PaginationRequest = *p
req.PaginationRequest = *pagination req.Keyword = r.URL.Query().Get("keyword")
req.Keyword = commonhttp.GetQuery(r, "keyword", "")
} }
// 使用分页方法
page := req.GetPage() // 获取页码默认1
size := req.GetSize() // 获取每页数量默认20最大100
_ = req.GetOffset() // 计算偏移量
// 模拟查询数据
users := []User{ users := []User{
{ID: 1, Name: "User1", Email: "user1@example.com"}, {ID: 1, Name: "User1", Email: "user1@example.com"},
{ID: 2, Name: "User2", Email: "user2@example.com"}, {ID: 2, Name: "User2", Email: "user2@example.com"},
} }
total := int64(100) h.SuccessPage(users, 100)
// 返回分页响应使用factory方法
fac.SuccessPage(w, users, total, page, size)
}
func main() {
http.HandleFunc("/users", GetUserList)
log.Println("Server started on :8080")
log.Fatal(http.ListenAndServe(":8080", nil))
} }

32
examples/i18n_example.go Normal file
View File

@@ -0,0 +1,32 @@
//go:build example
// +build example
package main
import (
"fmt"
"log"
"git.toowon.com/jimmy/go-common/factory"
)
func main() {
if err := factory.Init("config.json"); err != nil {
log.Fatal(err)
}
app := factory.Default()
i18n, err := app.I18n()
if err != nil {
log.Fatal(err)
}
if err := i18n.LoadFromDir("locales"); err != nil {
log.Fatal(err)
}
fmt.Println("zh-CN:", i18n.GetMessage("zh-CN", "user.not_found"))
fmt.Println("en-US:", i18n.GetMessage("en-US", "user.not_found"))
fmt.Println("welcome:", i18n.GetMessage("zh-CN", "user.welcome", "Alice"))
fmt.Println("langs:", i18n.GetSupportedLangs())
}

View 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"
}
}

View 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 条新消息"
}
}

View File

@@ -1,3 +1,6 @@
//go:build example
// +build example
package main package main
import ( import (
@@ -8,57 +11,24 @@ import (
) )
func main() { func main() {
// 加载配置
cfg, err := config.LoadFromFile("./config/example.json") cfg, err := config.LoadFromFile("./config/example.json")
if err != nil { if err != nil {
log.Fatal("Failed to load config:", err) log.Fatal(err)
} }
// 方式1使用工厂创建日志记录器推荐方式 app := factory.New(cfg)
fac := factory.NewFactory(cfg) logInst, err := app.Logger()
logger, err := fac.GetLogger()
if err != nil { if err != nil {
log.Fatal("Failed to create logger:", err) log.Fatal(err)
} }
defer logInst.Close()
// 如果使用异步模式程序退出前需要关闭logger logInst.Info("Application started", nil)
defer logger.Close() logInst.Info("User logged in", map[string]any{
// 方式2直接使用工厂的日志方法黑盒模式更简单
// fac.LogInfo("Application started")
// fac.LogError("An error occurred")
// 示例1基本日志记录
logger.Info("Application started")
logger.Debug("Debug message: %s", "This is a debug message")
logger.Warn("Warning message: %s", "This is a warning")
logger.Error("Error message: %s", "This is an error")
// 示例2带字段的日志记录
logger.Infof(map[string]interface{}{
"user_id": 123, "user_id": 123,
"action": "login", "action": "login",
"ip": "192.168.1.1", })
}, "User logged in successfully") logInst.Error("Failed to connect to database", map[string]any{
"error": "connection timeout",
logger.Errorf(map[string]interface{}{ })
"error_code": 1001,
"module": "database",
}, "Failed to connect to database: %v", "connection timeout")
// 示例3不同级别的日志
logger.Debug("This is a debug log")
logger.Info("This is an info log")
logger.Warn("This is a warn log")
logger.Error("This is an error log")
// 示例4异步模式使用
// 如果配置中设置了 "async": true日志会异步写入
// 程序退出前需要调用 Close() 确保所有日志写入完成
// logger.Close()
// 注意Fatal和Panic会终止程序示例中不执行
// logger.Fatal("This would exit the program")
// logger.Panic("This would panic")
} }

View File

@@ -1,40 +1,30 @@
//go:build example
// +build example
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/middleware"
) )
// 示例:简单的中间件配置
// 包括Recovery、Logging、CORS、Timezone
func main() { func main() {
// 创建简单的中间件链(使用默认配置) if err := factory.Init("config.json"); err != nil {
chain := middleware.NewChain( log.Fatal(err)
middleware.Recovery(nil), // Panic恢复使用默认logger }
middleware.Logging(nil), // 请求日志使用默认logger app := factory.Default()
middleware.CORS(nil), // CORS允许所有源 chain := app.MiddlewareChain()
middleware.Timezone, // 时区处理默认AsiaShanghai
)
// 定义API处理器
http.Handle("/api/hello", chain.ThenFunc(func(w http.ResponseWriter, r *http.Request) { http.Handle("/api/hello", chain.ThenFunc(func(w http.ResponseWriter, r *http.Request) {
// 获取时区(使用公共方法) h := commonhttp.NewHandler(w, r)
timezone := commonhttp.GetTimezone(r) h.Success(map[string]any{
// 返回响应(使用公共方法)
commonhttp.Success(w, map[string]interface{}{
"message": "Hello, World!", "message": "Hello, World!",
"timezone": timezone, "timezone": h.GetTimezone(),
}) })
})) }))
// 启动服务器 log.Fatal(http.ListenAndServe(":8080", nil))
addr := ":8080"
log.Printf("Server starting on %s", addr)
log.Printf("Try: http://localhost%s/api/hello", addr)
log.Fatal(http.ListenAndServe(addr, nil))
} }

View File

@@ -1,139 +0,0 @@
# 数据库迁移示例
这个目录包含了数据库迁移的示例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)

View File

@@ -1,3 +1,6 @@
//go:build example
// +build example
package main package main
import ( import (
@@ -5,98 +8,30 @@ import (
"log" "log"
"git.toowon.com/jimmy/go-common/config" "git.toowon.com/jimmy/go-common/config"
"git.toowon.com/jimmy/go-common/sms" "git.toowon.com/jimmy/go-common/factory"
) )
func main() { func main() {
// 加载配置
cfg, err := config.LoadFromFile("./config/example.json") cfg, err := config.LoadFromFile("./config/example.json")
if err != nil { if err != nil {
log.Fatal("Failed to load config:", err) log.Fatal(err)
} }
// 创建短信发送器 app := factory.New(cfg)
smsConfig := cfg.GetSMS() smsClient, err := app.SMS()
if smsConfig == nil {
log.Fatal("SMS config is nil")
}
smsClient, err := sms.NewSMS(smsConfig)
if err != nil { if err != nil {
log.Fatal("Failed to create SMS client:", err) log.Fatal(err)
} }
defer smsClient.Close()
// 示例1发送原始请求推荐最灵活 params := map[string]string{"code": "123456"}
fmt.Println("=== Example 1: Send Raw SMS Request ===") resp, err := smsClient.SendSMS([]string{"13800138000"}, params)
// 外部构建完整的请求参数
params := map[string]string{
"PhoneNumbers": "13800138000",
"SignName": smsConfig.SignName,
"TemplateCode": smsConfig.TemplateCode,
"TemplateParam": `{"code":"123456","expire":"5"}`,
}
resp, err := smsClient.SendRaw(params)
if err != nil { if err != nil {
log.Printf("Failed to send raw SMS: %v", err) log.Printf("sync send failed: %v", err)
} else { } else {
fmt.Printf("Raw SMS sent successfully, RequestID: %s\n", resp.RequestID) fmt.Printf("sync sms sent, RequestID: %s\n", resp.RequestID)
} }
// 示例2发送简单短信使用配置中的模板代码 smsClient.SendSMSAsync(nil, []string{"13800138000"}, params)
fmt.Println("\n=== Example 2: Send Simple SMS ===") fmt.Println("async sms enqueued")
templateParam := map[string]string{
"code": "123456",
"expire": "5",
}
resp2, err := smsClient.SendSimple(
[]string{"13800138000"},
templateParam,
)
if err != nil {
log.Printf("Failed to send SMS: %v", err)
} else {
fmt.Printf("SMS sent successfully, RequestID: %s\n", resp2.RequestID)
}
// 示例3使用指定模板发送短信
fmt.Println("\n=== Example 3: Send SMS with Template ===")
templateParam3 := map[string]string{
"code": "654321",
"expire": "10",
}
resp3, err := smsClient.SendWithTemplate(
[]string{"13800138000"},
"SMS_123456789", // 使用指定的模板代码
templateParam3,
)
if err != nil {
log.Printf("Failed to send SMS: %v", err)
} else {
fmt.Printf("SMS sent successfully, RequestID: %s\n", resp3.RequestID)
}
// 示例4使用JSON字符串作为模板参数
fmt.Println("\n=== Example 4: Send SMS with JSON String Template Param ===")
req := &sms.SendRequest{
PhoneNumbers: []string{"13800138000"},
TemplateCode: smsConfig.TemplateCode,
TemplateParam: `{"code":"888888","expire":"15"}`, // 直接使用JSON字符串
}
resp4, err := smsClient.Send(req)
if err != nil {
log.Printf("Failed to send SMS: %v", err)
} else {
fmt.Printf("SMS sent successfully, RequestID: %s\n", resp4.RequestID)
}
fmt.Println("\nNote: Make sure your Aliyun SMS service is configured correctly:")
fmt.Println("1. AccessKey ID and Secret are valid")
fmt.Println("2. Sign name is approved")
fmt.Println("3. Template code is approved")
fmt.Println("4. Template parameters match the template definition")
} }

View File

@@ -1,3 +1,6 @@
//go:build example
// +build example
package main package main
import ( import (
@@ -16,52 +19,51 @@ func main() {
log.Fatal("Failed to load config:", err) log.Fatal("Failed to load config:", err)
} }
// 创建存储实例使用OSS // 优先演示本地存储(可直接运行
// 注意需要先实现OSS SDK集成 localStorage, err := storage.NewStorage(storage.StorageTypeLocal, cfg)
ossStorage, err := storage.NewStorage(storage.StorageTypeOSS, cfg)
if err != nil { if err != nil {
log.Printf("Failed to create OSS storage: %v", err) log.Fatal("Failed to create Local storage:", err)
log.Println("Note: OSS SDK integration is required") }
// 继续演示其他功能
} else {
// 创建上传处理器
uploadHandler := storage.NewUploadHandler(storage.UploadHandlerConfig{
Storage: ossStorage,
MaxFileSize: 10 * 1024 * 1024, // 10MB
AllowedExts: []string{".jpg", ".jpeg", ".png", ".gif", ".pdf"},
ObjectPrefix: "uploads/",
})
// 创建代理查看处理器 uploadHandler := storage.NewUploadHandler(storage.UploadHandlerConfig{
proxyHandler := storage.NewProxyHandler(ossStorage) Storage: localStorage,
MaxFileSize: 10 * 1024 * 1024, // 10MB
AllowedExts: []string{".jpg", ".jpeg", ".png", ".gif", ".pdf"},
ObjectPrefix: "uploads/",
})
// 创建中间件链 proxyHandler := storage.NewProxyHandler(localStorage)
var corsConfig *middleware.CORSConfig
if cfg.GetCORS() != nil { // 创建中间件链
c := cfg.GetCORS() var corsConfig *middleware.CORSConfig
corsConfig = middleware.NewCORSConfig( if cfg.GetCORS() != nil {
c.AllowedOrigins, c := cfg.GetCORS()
c.AllowedMethods, corsConfig = middleware.NewCORSConfig(
c.AllowedHeaders, c.AllowedOrigins,
c.ExposedHeaders, c.AllowedMethods,
c.AllowCredentials, c.AllowedHeaders,
c.MaxAge, c.ExposedHeaders,
) c.AllowCredentials,
} c.MaxAge,
chain := middleware.NewChain(
middleware.CORS(corsConfig),
middleware.Timezone,
) )
}
chain := middleware.NewChain(
middleware.CORS(corsConfig),
middleware.Timezone,
)
// 注册路由 // 注册路由
mux := http.NewServeMux() mux := http.NewServeMux()
mux.Handle("/upload", chain.Then(uploadHandler)) mux.Handle("/upload", chain.Then(uploadHandler))
mux.Handle("/file", chain.Then(proxyHandler)) mux.Handle("/file", chain.Then(proxyHandler))
log.Println("Storage server started on :8080") log.Println("Local storage server started on :8080")
log.Println("Upload: POST /upload") log.Println("Upload: POST /upload")
log.Println("View: GET /file?key=images/test.jpg") log.Println("View: GET /file?key=uploads/xxx.jpg")
log.Fatal(http.ListenAndServe(":8080", mux))
// 提示OSS 需要你自行集成对应 SDK当前 go-common 中仅提供接口框架)
if _, err := storage.NewStorage(storage.StorageTypeOSS, cfg); err != nil {
log.Printf("OSS storage not ready: %v", err)
} }
// 演示MinIO存储 // 演示MinIO存储
@@ -79,5 +81,6 @@ func main() {
objectKey2 := storage.GenerateObjectKeyWithDate("images", "test.jpg") objectKey2 := storage.GenerateObjectKeyWithDate("images", "test.jpg")
log.Printf("Object key 2: %s", objectKey2) log.Printf("Object key 2: %s", objectKey2)
}
log.Fatal(http.ListenAndServe(":8080", mux))
}

443
excel/excel.go Normal file
View File

@@ -0,0 +1,443 @@
package excel
import (
"fmt"
"io"
"os"
"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)
}
// ExportToFile 导出数据到文件
func (e *Excel) ExportToFile(filePath, sheetName string, columns []ExportColumn, data interface{}) error {
f, err := os.Create(filePath)
if err != nil {
return fmt.Errorf("failed to create file: %w", err)
}
defer f.Close()
return e.ExportToWriter(f, sheetName, columns, data)
}
// 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)

File diff suppressed because it is too large Load Diff

20
go.mod
View File

@@ -1,12 +1,15 @@
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/google/uuid v1.6.0
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
@@ -19,7 +22,6 @@ require (
github.com/dustin/go-humanize v1.0.1 // indirect github.com/dustin/go-humanize v1.0.1 // indirect
github.com/go-ini/ini v1.67.0 // indirect github.com/go-ini/ini v1.67.0 // indirect
github.com/go-sql-driver/mysql v1.7.1 // indirect github.com/go-sql-driver/mysql v1.7.1 // indirect
github.com/google/uuid v1.6.0 // indirect
github.com/jackc/pgpassfile v1.0.0 // indirect github.com/jackc/pgpassfile v1.0.0 // indirect
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
github.com/jackc/pgx/v5 v5.6.0 // indirect github.com/jackc/pgx/v5 v5.6.0 // indirect
@@ -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
View File

@@ -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=

95
http/handler.go Normal file
View File

@@ -0,0 +1,95 @@
package http
import (
"net/http"
"git.toowon.com/jimmy/go-common/i18n"
)
// Handler HTTP 出参处理器(唯一对外出参方式)
type Handler struct {
w http.ResponseWriter
r *http.Request
i18n *i18n.I18n
pagination *PaginationRequest
}
// HandlerOption Handler 配置项
type HandlerOption func(*Handler)
// WithI18n 注入 i18n
func WithI18n(i *i18n.I18n) HandlerOption {
return func(h *Handler) {
h.i18n = i
}
}
// NewHandler 创建 HTTP 出参处理器
func NewHandler(w http.ResponseWriter, r *http.Request, opts ...HandlerOption) *Handler {
h := &Handler{w: w, r: r}
for _, opt := range opts {
opt(h)
}
return h
}
// ParseJSON 解析 JSON 请求体
func (h *Handler) ParseJSON(v interface{}) error {
return ParseJSON(h.r, v)
}
// Pagination 解析并缓存分页参数
func (h *Handler) Pagination() *PaginationRequest {
if h.pagination == nil {
h.pagination = ParsePaginationRequest(h.r)
}
return h.pagination
}
// GetLanguage 从 context 获取语言
func (h *Handler) GetLanguage() string {
return GetLanguage(h.r)
}
// GetTimezone 从 context 获取时区
func (h *Handler) GetTimezone() string {
return GetTimezone(h.r)
}
// Success 成功响应
func (h *Handler) Success(data interface{}) {
message := "success"
code := 0
if h.i18n != nil {
info := h.i18n.GetMessageInfo(h.GetLanguage(), "common.success")
if info.Message != "common.success" {
message = info.Message
code = info.Code
}
}
writeResponse(h.w, code, message, data)
}
// SuccessPage 分页成功响应
func (h *Handler) SuccessPage(list interface{}, total int64) {
p := h.Pagination()
pageData := &PageData{
List: list,
Total: total,
Page: p.GetPage(),
PageSize: p.GetPageSize(),
}
h.Success(pageData)
}
// Error 失败响应messageCode 为 i18n 消息码)
func (h *Handler) Error(messageCode string, args ...interface{}) {
code := 0
message := messageCode
if h.i18n != nil {
info := h.i18n.GetMessageInfo(h.GetLanguage(), messageCode, args...)
code = info.Code
message = info.Message
}
writeResponse(h.w, code, message, nil)
}

View File

@@ -4,47 +4,17 @@ import (
"encoding/json" "encoding/json"
"io" "io"
"net/http" "net/http"
"strconv"
"git.toowon.com/jimmy/go-common/middleware" "git.toowon.com/jimmy/go-common/requestctx"
"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
@@ -55,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条
} }
@@ -73,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
} }
@@ -100,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
} }
@@ -119,8 +80,6 @@ func ParsePaginationRequest(r *http.Request) *PaginationRequest {
return req return req
} }
// ========== 请求解析公共方法 ==========
// ParseJSON 解析JSON请求体公共方法 // ParseJSON 解析JSON请求体公共方法
// r: HTTP请求 // r: HTTP请求
// v: 目标结构体指针 // v: 目标结构体指针
@@ -138,172 +97,12 @@ func ParseJSON(r *http.Request, v interface{}) error {
return json.Unmarshal(body, v) return json.Unmarshal(body, v)
} }
// GetQuery 获取查询参数(公共方法) // GetTimezone 从请求的 context 中获取时区
// r: HTTP请求
// key: 参数名
// defaultValue: 默认值
func GetQuery(r *http.Request, key, defaultValue string) string {
value := r.URL.Query().Get(key)
if value == "" {
return defaultValue
}
return value
}
// GetQueryInt 获取整数查询参数(公共方法)
// r: HTTP请求
// key: 参数名
// defaultValue: 默认值
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
}
// GetQueryInt64 获取int64查询参数公共方法
// r: HTTP请求
// key: 参数名
// defaultValue: 默认值
func GetQueryInt64(r *http.Request, key string, defaultValue int64) int64 {
value := r.URL.Query().Get(key)
if value == "" {
return defaultValue
}
intValue, err := strconv.ParseInt(value, 10, 64)
if err != nil {
return defaultValue
}
return intValue
}
// GetQueryBool 获取布尔查询参数(公共方法)
// r: HTTP请求
// key: 参数名
// defaultValue: 默认值
func GetQueryBool(r *http.Request, key string, defaultValue bool) bool {
value := r.URL.Query().Get(key)
if value == "" {
return defaultValue
}
boolValue, err := strconv.ParseBool(value)
if err != nil {
return defaultValue
}
return boolValue
}
// GetQueryFloat64 获取float64查询参数公共方法
// r: HTTP请求
// key: 参数名
// defaultValue: 默认值
func GetQueryFloat64(r *http.Request, key string, defaultValue float64) float64 {
value := r.URL.Query().Get(key)
if value == "" {
return defaultValue
}
floatValue, err := strconv.ParseFloat(value, 64)
if err != nil {
return defaultValue
}
return floatValue
}
// GetFormValue 获取表单值(公共方法)
// r: HTTP请求
// key: 参数名
// defaultValue: 默认值
func GetFormValue(r *http.Request, key, defaultValue string) string {
value := r.FormValue(key)
if value == "" {
return defaultValue
}
return value
}
// GetFormInt 获取表单整数(公共方法)
// r: HTTP请求
// key: 参数名
// defaultValue: 默认值
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
}
// GetFormInt64 获取表单int64公共方法
// r: HTTP请求
// key: 参数名
// defaultValue: 默认值
func GetFormInt64(r *http.Request, key string, defaultValue int64) int64 {
value := r.FormValue(key)
if value == "" {
return defaultValue
}
intValue, err := strconv.ParseInt(value, 10, 64)
if err != nil {
return defaultValue
}
return intValue
}
// GetFormBool 获取表单布尔值(公共方法)
// r: HTTP请求
// key: 参数名
// defaultValue: 默认值
func GetFormBool(r *http.Request, key string, defaultValue bool) bool {
value := r.FormValue(key)
if value == "" {
return defaultValue
}
boolValue, err := strconv.ParseBool(value)
if err != nil {
return defaultValue
}
return boolValue
}
// GetHeader 获取请求头(公共方法)
// r: HTTP请求
// key: 请求头名称
// defaultValue: 默认值
func GetHeader(r *http.Request, key, defaultValue string) string {
value := r.Header.Get(key)
if value == "" {
return defaultValue
}
return value
}
// GetTimezone 从请求的context中获取时区公共方法
// r: HTTP请求
// 如果使用了middleware.Timezone中间件可以从context中获取时区信息
// 如果未设置,返回默认时区 AsiaShanghai
func GetTimezone(r *http.Request) string { func GetTimezone(r *http.Request) string {
return middleware.GetTimezoneFromContext(r.Context()) return requestctx.Timezone(r.Context())
}
// GetLanguage 从请求的 context 中获取语言
func GetLanguage(r *http.Request) string {
return requestctx.Language(r.Context())
} }

View File

@@ -8,36 +8,24 @@ import (
// Response 标准响应结构 // Response 标准响应结构
type Response struct { type Response struct {
Code int `json:"code"` // 业务状态码0表示成功 Code int `json:"code"`
Message string `json:"message"` // 响应消息 Message string `json:"message"`
Timestamp int64 `json:"timestamp"` // 时间戳 Timestamp int64 `json:"timestamp"`
Data interface{} `json:"data"` // 响应数据 Data interface{} `json:"data"`
}
// PageResponse 分页响应结构
type PageResponse struct {
Code int `json:"code"`
Message string `json:"message"`
Timestamp int64 `json:"timestamp"`
Data *PageData `json:"data"`
} }
// PageData 分页数据 // PageData 分页数据
type PageData struct { type PageData struct {
List interface{} `json:"list"` // 数据列表 List interface{} `json:"list"`
Total int64 `json:"total"` // 总记录数 Total int64 `json:"total"`
Page int `json:"page"` // 当前页码 Page int `json:"page"`
PageSize int `json:"pageSize"` // 每页大小 PageSize int `json:"pageSize"`
} }
// writeJSON 写入JSON响应公共方法 // writeResponse 统一 JSON 出参HTTP 恒 200
// httpCode: HTTP状态码200表示正常500表示系统错误等 func writeResponse(w http.ResponseWriter, code int, message string, data interface{}) {
// code: 业务状态码0表示成功非0表示业务错误
// message: 响应消息
// data: 响应数据
func writeJSON(w http.ResponseWriter, httpCode, code int, message string, data interface{}) {
w.Header().Set("Content-Type", "application/json; charset=utf-8") w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(httpCode) w.WriteHeader(http.StatusOK)
response := Response{ response := Response{
Code: code, Code: code,
@@ -46,60 +34,5 @@ func writeJSON(w http.ResponseWriter, httpCode, code int, message string, data i
Data: data, Data: data,
} }
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
View 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: 消息mapkey为消息代码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本身作为messagecode为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本身作为messagecode为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)
}

View File

@@ -1,72 +1,100 @@
package logger package logger
import ( import (
"context"
"encoding/json"
"fmt" "fmt"
"io" "io"
"log"
"os" "os"
"path/filepath" "path/filepath"
"sync" "sync"
"sync/atomic"
"time"
"git.toowon.com/jimmy/go-common/config" "git.toowon.com/jimmy/go-common/config"
) )
type ctxKey int
const requestIDKey ctxKey = iota
// WithRequestID 将 Request ID 写入 context
func WithRequestID(ctx context.Context, id string) context.Context {
return context.WithValue(ctx, requestIDKey, id)
}
// RequestIDFromContext 从 context 读取 Request ID
func RequestIDFromContext(ctx context.Context) string {
if ctx == nil {
return ""
}
if id, ok := ctx.Value(requestIDKey).(string); ok {
return id
}
return ""
}
var ( var (
// defaultLogger 全局默认日志记录器
// 用于中间件和其他需要快速日志记录的场景
defaultLogger *Logger defaultLogger *Logger
defaultMux sync.RWMutex defaultMux sync.RWMutex
) )
func init() { func init() {
// 初始化默认logger同步模式输出到stdout l, err := NewLogger(nil)
var err error
defaultLogger, err = NewLogger(nil)
if err != nil { if err != nil {
// 如果初始化失败使用nil后续会降级到标准输出
defaultLogger = nil defaultLogger = nil
return
} }
defaultLogger = l
} }
// logMessage 异步日志消息结构 // SetDefaultLogger 设置全局默认 logger
type logMessage struct { func SetDefaultLogger(l *Logger) {
level string // debug, info, warn, error defaultMux.Lock()
format string defer defaultMux.Unlock()
args []interface{} if defaultLogger != nil && defaultLogger != l {
fields map[string]interface{} // 用于带字段的日志 _ = defaultLogger.Close()
}
defaultLogger = l
}
func getDefaultLogger() *Logger {
defaultMux.RLock()
defer defaultMux.RUnlock()
return defaultLogger
}
type logEntry struct {
level string
message string
fields map[string]any
} }
// Logger 日志记录器 // Logger 日志记录器
type Logger struct { type Logger struct {
infoLog *log.Logger level string
errorLog *log.Logger writers []io.Writer
warnLog *log.Logger prefix string
debugLog *log.Logger async bool
config *config.LoggerConfig logChan chan logEntry
done chan struct{}
// 异步相关字段 wg sync.WaitGroup
async bool // 是否异步模式 closed bool
logChan chan *logMessage // 异步日志channel mu sync.RWMutex
done chan struct{} // 用于优雅关闭 dropped atomic.Uint64
wg sync.WaitGroup // 等待所有日志写入完成
closed bool // 是否已关闭
closeMux sync.RWMutex // 保护closed字段
} }
// NewLogger 创建日志记录器 // NewLogger 创建日志记录器
func NewLogger(cfg *config.LoggerConfig) (*Logger, error) { func NewLogger(cfg *config.LoggerConfig) (*Logger, error) {
if cfg == nil { if cfg == nil {
// 使用默认配置
cfg = &config.LoggerConfig{ cfg = &config.LoggerConfig{
Level: "info", Level: "info",
Output: "stdout", Output: "stdout",
FilePath: "", Async: config.BoolPtr(true),
Async: false, // 默认同步 BufferSize: 1000,
BufferSize: 1000, // 默认缓冲区大小
} }
} }
// 设置默认值
if cfg.Level == "" { if cfg.Level == "" {
cfg.Level = "info" cfg.Level = "info"
} }
@@ -74,10 +102,37 @@ func NewLogger(cfg *config.LoggerConfig) (*Logger, error) {
cfg.Output = "stdout" cfg.Output = "stdout"
} }
if cfg.BufferSize <= 0 { if cfg.BufferSize <= 0 {
cfg.BufferSize = 1000 // 默认缓冲区大小 cfg.BufferSize = 1000
} }
// 创建输出目标 writers, err := createWriters(cfg)
if err != nil {
return nil, err
}
prefix := ""
if cfg.Prefix != "" {
prefix = cfg.Prefix + " "
}
l := &Logger{
level: cfg.Level,
writers: writers,
prefix: prefix,
async: cfg.IsAsync(),
}
if cfg.IsAsync() {
l.logChan = make(chan logEntry, cfg.BufferSize)
l.done = make(chan struct{})
l.wg.Add(1)
go l.processLogs()
}
return l, nil
}
func createWriters(cfg *config.LoggerConfig) ([]io.Writer, error) {
var writers []io.Writer var writers []io.Writer
switch cfg.Output { switch cfg.Output {
case "stdout": case "stdout":
@@ -88,96 +143,56 @@ func NewLogger(cfg *config.LoggerConfig) (*Logger, error) {
if cfg.FilePath == "" { if cfg.FilePath == "" {
return nil, fmt.Errorf("file path is required when output is file") return nil, fmt.Errorf("file path is required when output is file")
} }
// 确保目录存在 w, err := openLogFile(cfg.FilePath)
dir := filepath.Dir(cfg.FilePath)
if err := os.MkdirAll(dir, 0755); err != nil {
return nil, fmt.Errorf("failed to create log directory: %w", err)
}
file, err := os.OpenFile(cfg.FilePath, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
if err != nil { if err != nil {
return nil, fmt.Errorf("failed to open log file: %w", err) return nil, err
} }
writers = append(writers, file) writers = append(writers, w)
case "both": case "both":
writers = append(writers, os.Stdout) writers = append(writers, os.Stdout)
if cfg.FilePath == "" { if cfg.FilePath == "" {
return nil, fmt.Errorf("file path is required when output is both") return nil, fmt.Errorf("file path is required when output is both")
} }
dir := filepath.Dir(cfg.FilePath) w, err := openLogFile(cfg.FilePath)
if err := os.MkdirAll(dir, 0755); err != nil {
return nil, fmt.Errorf("failed to create log directory: %w", err)
}
file, err := os.OpenFile(cfg.FilePath, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
if err != nil { if err != nil {
return nil, fmt.Errorf("failed to open log file: %w", err) return nil, err
} }
writers = append(writers, file) writers = append(writers, w)
default: default:
return nil, fmt.Errorf("invalid output type: %s", cfg.Output) return nil, fmt.Errorf("invalid output type: %s", cfg.Output)
} }
return writers, nil
// 创建多写入器 }
multiWriter := io.MultiWriter(writers...)
func openLogFile(path string) (io.Writer, error) {
// 创建日志前缀 dir := filepath.Dir(path)
prefix := "" if err := os.MkdirAll(dir, 0o755); err != nil {
if cfg.Prefix != "" { return nil, fmt.Errorf("failed to create log directory: %w", err)
prefix = cfg.Prefix + " " }
} f, err := os.OpenFile(path, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0o666)
if err != nil {
// 创建日志记录器 return nil, fmt.Errorf("failed to open log file: %w", err)
logger := &Logger{ }
config: cfg, return f, nil
async: cfg.Async,
}
// 根据日志级别创建不同的logger
flags := log.LstdFlags
if cfg.DisableTimestamp {
flags = 0
}
if cfg.Level == "debug" || cfg.Level == "info" || cfg.Level == "warn" || cfg.Level == "error" {
logger.infoLog = log.New(multiWriter, prefix+"[INFO] ", flags)
logger.warnLog = log.New(multiWriter, prefix+"[WARN] ", flags)
logger.errorLog = log.New(multiWriter, prefix+"[ERROR] ", flags)
if cfg.Level == "debug" {
logger.debugLog = log.New(multiWriter, prefix+"[DEBUG] ", flags)
}
}
// 如果启用异步模式启动goroutine处理日志
if cfg.Async {
logger.logChan = make(chan *logMessage, cfg.BufferSize)
logger.done = make(chan struct{})
logger.wg.Add(1)
go logger.processLogs()
}
return logger, nil
} }
// processLogs 异步处理日志goroutine
func (l *Logger) processLogs() { func (l *Logger) processLogs() {
defer l.wg.Done() defer l.wg.Done()
for { for {
select { select {
case msg := <-l.logChan: case msg, ok := <-l.logChan:
if msg == nil { if !ok {
// channel已关闭退出
return return
} }
l.writeLog(msg) l.writeEntry(msg)
case <-l.done: case <-l.done:
// 收到关闭信号,处理完剩余日志后退出
for { for {
select { select {
case msg := <-l.logChan: case msg, ok := <-l.logChan:
if msg == nil { if !ok {
return return
} }
l.writeLog(msg) l.writeEntry(msg)
default: default:
return return
} }
@@ -186,278 +201,161 @@ func (l *Logger) processLogs() {
} }
} }
// writeLog 实际写入日志(内部方法)
func (l *Logger) writeLog(msg *logMessage) {
var logger *log.Logger
switch msg.level {
case "debug":
logger = l.debugLog
case "info":
logger = l.infoLog
case "warn":
logger = l.warnLog
case "error":
logger = l.errorLog
default:
return
}
if logger == nil {
return
}
// 如果有字段,先格式化字段
format := msg.format
if len(msg.fields) > 0 {
fieldStr := formatFields(msg.fields)
format = fieldStr + format
}
// 写入日志
logger.Printf(format, msg.args...)
}
// isClosed 检查logger是否已关闭
func (l *Logger) isClosed() bool { func (l *Logger) isClosed() bool {
l.closeMux.RLock() l.mu.RLock()
defer l.closeMux.RUnlock() defer l.mu.RUnlock()
return l.closed return l.closed
} }
// setClosed 设置logger为已关闭状态 func (l *Logger) shouldLog(level string) bool {
func (l *Logger) setClosed() { switch l.level {
l.closeMux.Lock() case "debug":
defer l.closeMux.Unlock() return true
l.closed = true case "info":
return level != "debug"
case "error":
return level == "error"
default:
return level != "debug"
}
} }
// log 内部日志方法,根据模式选择同步或异步 func (l *Logger) emit(level, message string, fields map[string]any) {
func (l *Logger) log(level string, format string, args []interface{}, fields map[string]interface{}) { if l.isClosed() || !l.shouldLog(level) {
// 如果已关闭,直接返回
if l.isClosed() {
return return
} }
// 如果是异步模式发送到channel entry := logEntry{level: level, message: message, fields: fields}
if l.async { if l.async {
// 检查channel是否已关闭
select { select {
case l.logChan <- &logMessage{ case l.logChan <- entry:
level: level,
format: format,
args: args,
fields: fields,
}:
// 成功发送
default: default:
// channel已满或已关闭同步写入降级处理 l.dropped.Add(1)
l.writeLog(&logMessage{
level: level,
format: format,
args: args,
fields: fields,
})
} }
} else { return
// 同步模式,直接写入
l.writeLog(&logMessage{
level: level,
format: format,
args: args,
fields: fields,
})
} }
l.writeEntry(entry)
}
func (l *Logger) writeEntry(entry logEntry) {
line := l.formatLine(entry.level, entry.message, entry.fields)
for _, w := range l.writers {
_, _ = fmt.Fprintln(w, line)
}
}
func (l *Logger) formatLine(level, message string, fields map[string]any) string {
ts := time.Now().Format("2006-01-02 15:04:05")
payload := map[string]any{
"time": ts,
"level": level,
"message": message,
}
for k, v := range fields {
payload[k] = v
}
b, err := json.Marshal(payload)
if err != nil {
return fmt.Sprintf("%s[%s] %s %v", l.prefix, level, message, fields)
}
return l.prefix + string(b)
} }
// Debug 记录调试日志 // Debug 记录调试日志
func (l *Logger) Debug(format string, v ...interface{}) { func (l *Logger) Debug(message string, fields map[string]any) {
l.log("debug", format, v, nil) l.emit("debug", message, fields)
} }
// Info 记录信息日志 // Info 记录信息日志
func (l *Logger) Info(format string, v ...interface{}) { func (l *Logger) Info(message string, fields map[string]any) {
l.log("info", format, v, nil) l.emit("info", message, fields)
}
// Warn 记录警告日志
func (l *Logger) Warn(format string, v ...interface{}) {
l.log("warn", format, v, nil)
} }
// Error 记录错误日志 // Error 记录错误日志
func (l *Logger) Error(format string, v ...interface{}) { func (l *Logger) Error(message string, fields map[string]any) {
l.log("error", format, v, nil) l.emit("error", message, fields)
} }
// Fatal 记录致命错误日志并退出程序(始终同步) // Close 刷盘并关闭异步队列
func (l *Logger) Fatal(format string, v ...interface{}) {
// Fatal必须同步执行确保日志写入后再退出
if l.errorLog != nil {
l.errorLog.Fatalf(format, v...)
} else {
log.Fatalf(format, v...)
}
}
// Panic 记录恐慌日志并触发panic始终同步
func (l *Logger) Panic(format string, v ...interface{}) {
// Panic必须同步执行确保日志写入后再panic
if l.errorLog != nil {
l.errorLog.Panicf(format, v...)
} else {
log.Panicf(format, v...)
}
}
// WithFields 创建带字段的日志记录器(简化版,返回格式化字符串)
func (l *Logger) WithFields(fields map[string]interface{}) *Logger {
// 返回自身实际使用时可以在format中包含fields
return l
}
// formatFields 格式化字段
func formatFields(fields map[string]interface{}) string {
if len(fields) == 0 {
return ""
}
result := ""
for k, v := range fields {
result += fmt.Sprintf("%s=%v ", k, v)
}
return result
}
// Debugf 记录调试日志(带字段)
func (l *Logger) Debugf(fields map[string]interface{}, format string, v ...interface{}) {
l.log("debug", format, v, fields)
}
// Infof 记录信息日志(带字段)
func (l *Logger) Infof(fields map[string]interface{}, format string, v ...interface{}) {
l.log("info", format, v, fields)
}
// Warnf 记录警告日志(带字段)
func (l *Logger) Warnf(fields map[string]interface{}, format string, v ...interface{}) {
l.log("warn", format, v, fields)
}
// Errorf 记录错误日志(带字段)
func (l *Logger) Errorf(fields map[string]interface{}, format string, v ...interface{}) {
l.log("error", format, v, fields)
}
// Close 优雅关闭logger仅异步模式需要
// 等待所有日志写入完成后再返回
func (l *Logger) Close() error { func (l *Logger) Close() error {
if !l.async { if !l.async {
// 同步模式不需要关闭
return nil return nil
} }
l.mu.Lock()
// 检查是否已关闭 if l.closed {
if l.isClosed() { l.mu.Unlock()
return nil return nil
} }
l.closed = true
l.mu.Unlock()
// 设置关闭状态
l.setClosed()
// 发送关闭信号
close(l.done) close(l.done)
// 关闭channel会触发processLogs退出
close(l.logChan) close(l.logChan)
// 等待所有日志写入完成
l.wg.Wait() l.wg.Wait()
return nil return nil
} }
// ========== 全局默认Logger相关方法 ========== // DroppedCount 返回因队列满而丢弃的日志条数
func (l *Logger) DroppedCount() uint64 {
return l.dropped.Load()
}
// SetDefaultLogger 设置全局默认logger // ContextLogger 带 context 的 logger自动附加 request_id
// 用于在应用启动时统一配置logger type ContextLogger struct {
func SetDefaultLogger(log *Logger) { base *Logger
defaultMux.Lock() ctx context.Context
defer defaultMux.Unlock() }
// 如果之前有logger先关闭它 // FromContext 从 context 获取 logger自动附加 request_id
if defaultLogger != nil { func FromContext(ctx context.Context) *ContextLogger {
defaultLogger.Close() base := getDefaultLogger()
if base == nil {
if l, err := NewLogger(nil); err == nil {
base = l
}
} }
return &ContextLogger{base: base, ctx: ctx}
defaultLogger = log
} }
// GetDefaultLogger 获取全局默认logger // FromContextWithLogger 使用指定 logger 并从 context 附加 request_id
func GetDefaultLogger() *Logger { func FromContextWithLogger(ctx context.Context, base *Logger) *ContextLogger {
defaultMux.RLock() if base == nil {
defer defaultMux.RUnlock() base = getDefaultLogger()
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...)
} }
return &ContextLogger{base: base, ctx: ctx}
} }
// Info 使用全局logger记录信息日志 func (c *ContextLogger) mergeFields(fields map[string]any) map[string]any {
func Info(format string, v ...interface{}) { out := make(map[string]any, len(fields)+1)
if log := GetDefaultLogger(); log != nil { for k, v := range fields {
log.Info(format, v...) out[k] = v
} }
if id := RequestIDFromContext(c.ctx); id != "" {
out["request_id"] = id
}
return out
} }
// Warn 使用全局logger记录警告日志 // Debug 记录调试日志
func Warn(format string, v ...interface{}) { func (c *ContextLogger) Debug(message string, fields map[string]any) {
if log := GetDefaultLogger(); log != nil { if c.base == nil {
log.Warn(format, v...) return
} }
c.base.Debug(message, c.mergeFields(fields))
} }
// Error 使用全局logger记录错误日志 // Info 记录信息日志
func Error(format string, v ...interface{}) { func (c *ContextLogger) Info(message string, fields map[string]any) {
if log := GetDefaultLogger(); log != nil { if c.base == nil {
log.Error(format, v...) return
} }
c.base.Info(message, c.mergeFields(fields))
} }
// Debugf 使用全局logger记录调试日志带字段 // Error 记录错误日志
func Debugf(fields map[string]interface{}, format string, v ...interface{}) { func (c *ContextLogger) Error(message string, fields map[string]any) {
if log := GetDefaultLogger(); log != nil { if c.base == nil {
log.Debugf(fields, format, v...) return
}
}
// 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...)
} }
c.base.Error(message, c.mergeFields(fields))
} }

26
middleware/clientip.go Normal file
View File

@@ -0,0 +1,26 @@
package middleware
import "net/http"
// GetClientIP 获取客户端真实 IP
func GetClientIP(r *http.Request) string {
xff := r.Header.Get("X-Forwarded-For")
if xff != "" {
for i := 0; i < len(xff); i++ {
if xff[i] == ',' {
return xff[:i]
}
}
return xff
}
if xri := r.Header.Get("X-Real-IP"); xri != "" {
return xri
}
remoteAddr := r.RemoteAddr
for i := len(remoteAddr) - 1; i >= 0; i-- {
if remoteAddr[i] == ':' {
return remoteAddr[:i]
}
}
return remoteAddr
}

93
middleware/language.go Normal file
View File

@@ -0,0 +1,93 @@
package middleware
import (
"context"
"net/http"
"strings"
"git.toowon.com/jimmy/go-common/requestctx"
)
// LanguageHeaderName 语言请求头名称
const LanguageHeaderName = "X-Language"
// AcceptLanguageHeaderName Accept-Language 请求头名称
const AcceptLanguageHeaderName = "Accept-Language"
// GetLanguageFromContext 从 context 中获取语言
func GetLanguageFromContext(ctx context.Context) string {
return requestctx.Language(ctx)
}
// 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 = requestctx.DefaultLanguage
}
ctx := requestctx.WithLanguage(r.Context(), 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
}
ctx := requestctx.WithLanguage(r.Context(), 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
}

View File

@@ -2,17 +2,15 @@ package middleware
import ( import (
"net/http" "net/http"
"strconv"
"time" "time"
"git.toowon.com/jimmy/go-common/logger" "git.toowon.com/jimmy/go-common/logger"
) )
// responseWriter 包装 http.ResponseWriter 以捕获状态码和响应大小 // responseWriter 包装 ResponseWriter 以捕获状态码
type responseWriter struct { type responseWriter struct {
http.ResponseWriter http.ResponseWriter
statusCode int statusCode int
size int
} }
func (rw *responseWriter) WriteHeader(statusCode int) { func (rw *responseWriter) WriteHeader(statusCode int) {
@@ -20,202 +18,49 @@ func (rw *responseWriter) WriteHeader(statusCode int) {
rw.ResponseWriter.WriteHeader(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 日志中间件配置 // LoggingConfig 日志中间件配置
type LoggingConfig struct { type LoggingConfig struct {
// Logger 日志记录器可选如果为nil则使用默认logger Logger *logger.Logger
Logger *logger.Logger
// SkipPaths 跳过记录的路径列表(如健康检查接口)
SkipPaths []string SkipPaths []string
// LogRequestBody 是否记录请求体(谨慎使用,可能影响性能)
LogRequestBody bool
// LogResponseBody 是否记录响应体(谨慎使用,可能影响性能和内存)
LogResponseBody bool
} }
// Logging HTTP请求日志中间件 // Logging HTTP 访问日志(固定 Info 级别)
// 记录每个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 { func Logging(config *LoggingConfig) func(http.Handler) http.Handler {
// 如果没有配置,使用默认配置
if config == nil { if config == nil {
config = &LoggingConfig{} config = &LoggingConfig{}
} }
// 如果没有提供logger创建一个默认的
if config.Logger == nil {
// 使用默认配置创建logger输出到stdoutinfo级别
defaultLogger, err := logger.NewLogger(nil)
if err != nil {
// 如果创建失败使用nil后面会降级处理
config.Logger = nil
} else {
config.Logger = defaultLogger
}
}
return func(next http.Handler) http.Handler { return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// 检查是否跳过此路径
if shouldSkipPath(r.URL.Path, config.SkipPaths) { if shouldSkipPath(r.URL.Path, config.SkipPaths) {
next.ServeHTTP(w, r) next.ServeHTTP(w, r)
return return
} }
// 记录开始时间 start := time.Now()
startTime := time.Now() rw := &responseWriter{ResponseWriter: w, statusCode: http.StatusOK}
// 包装 ResponseWriter 以捕获状态码和响应大小
rw := &responseWriter{
ResponseWriter: w,
statusCode: http.StatusOK, // 默认200
size: 0,
}
// 处理请求
next.ServeHTTP(rw, r) next.ServeHTTP(rw, r)
// 计算处理时间 fields := map[string]any{
duration := time.Since(startTime) "method": r.Method,
"path": r.URL.Path,
"duration": time.Since(start).Milliseconds(),
}
// 记录日志 log := logger.FromContext(r.Context())
logHTTPRequest(config.Logger, r, rw, duration) if config.Logger != nil {
log = logger.FromContextWithLogger(r.Context(), config.Logger)
}
log.Info("HTTP Request", fields)
}) })
} }
} }
// shouldSkipPath 检查是否应该跳过该路径
func shouldSkipPath(path string, skipPaths []string) bool { func shouldSkipPath(path string, skipPaths []string) bool {
for _, skipPath := range skipPaths { for _, skip := range skipPaths {
if path == skipPath { if path == skip {
return true return true
} }
} }
return false 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
}

View File

@@ -5,145 +5,43 @@ import (
"net/http" "net/http"
"runtime/debug" "runtime/debug"
commonhttp "git.toowon.com/jimmy/go-common/http"
"git.toowon.com/jimmy/go-common/i18n"
"git.toowon.com/jimmy/go-common/logger" "git.toowon.com/jimmy/go-common/logger"
) )
// RecoveryConfig Recovery中间件配置 // RecoveryConfig Recovery 中间件配置
type RecoveryConfig struct { type RecoveryConfig struct {
// Logger 日志记录器可选如果为nil则使用默认logger
Logger *logger.Logger Logger *logger.Logger
I18n *i18n.I18n
// EnableStackTrace 是否在日志中包含堆栈跟踪
EnableStackTrace bool
// CustomHandler 自定义错误处理函数(可选)
// 如果设置了,会在记录日志后调用此函数
// 可以用于自定义错误响应格式
CustomHandler func(w http.ResponseWriter, r *http.Request, err interface{})
} }
// Recovery Panic恢复中间件 // Recovery Panic 恢复中间件,响应统一 JSON 200 + system.internal_error
// 捕获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 { 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 func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
defer func() { defer func() {
if err := recover(); err != nil { if err := recover(); err != nil {
// 记录panic信息 fields := map[string]any{
logPanic(config.Logger, r, err, config.EnableStackTrace) "method": r.Method,
"path": r.URL.Path,
// 如果提供了自定义处理函数,调用它 "error": fmt.Sprintf("%v", err),
if config.CustomHandler != nil { "stack": string(debug.Stack()),
config.CustomHandler(w, r, err)
return
} }
log := logger.FromContextWithLogger(r.Context(), nil)
if config != nil && config.Logger != nil {
log = logger.FromContextWithLogger(r.Context(), config.Logger)
}
log.Error("panic recovered", fields)
// 默认错误响应 h := commonhttp.NewHandler(w, r)
http.Error(w, "Internal Server Error", http.StatusInternalServerError) if config != nil && config.I18n != nil {
h = commonhttp.NewHandler(w, r, commonhttp.WithI18n(config.I18n))
}
h.Error("system.internal_error")
} }
}() }()
next.ServeHTTP(w, r) 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,
})
}

23
middleware/requestid.go Normal file
View File

@@ -0,0 +1,23 @@
package middleware
import (
"net/http"
"git.toowon.com/jimmy/go-common/logger"
"github.com/google/uuid"
)
// RequestID 为每个请求生成或透传 Request ID写入 context 与响应头
func RequestID() func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
id := r.Header.Get("X-Request-ID")
if id == "" {
id = uuid.NewString()
}
w.Header().Set("X-Request-ID", id)
ctx := logger.WithRequestID(r.Context(), id)
next.ServeHTTP(w, r.WithContext(ctx))
})
}
}

View File

@@ -4,77 +4,48 @@ import (
"context" "context"
"net/http" "net/http"
"git.toowon.com/jimmy/go-common/requestctx"
"git.toowon.com/jimmy/go-common/tools" "git.toowon.com/jimmy/go-common/tools"
) )
// TimezoneKey context中存储时区的key
type timezoneKey struct{}
// TimezoneHeaderName 时区请求头名称 // TimezoneHeaderName 时区请求头名称
const TimezoneHeaderName = "X-Timezone" const TimezoneHeaderName = "X-Timezone"
// DefaultTimezone 默认时区 // GetTimezoneFromContext 从 context 中获取时区
const DefaultTimezone = tools.AsiaShanghai
// GetTimezoneFromContext 从context中获取时区
func GetTimezoneFromContext(ctx context.Context) string { func GetTimezoneFromContext(ctx context.Context) string {
if tz, ok := ctx.Value(timezoneKey{}).(string); ok && tz != "" { return requestctx.Timezone(ctx)
return tz
}
return DefaultTimezone
} }
// Timezone 时区处理中间件 // Timezone 时区处理中间件
// 从请求头 X-Timezone 读取时区信息,如果未传递则使用默认时区 AsiaShanghai
// 时区信息会存储到context中可以通过 GetTimezoneFromContext 获取
func Timezone(next http.Handler) http.Handler { func Timezone(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// 从请求头获取时区
timezone := r.Header.Get(TimezoneHeaderName) timezone := r.Header.Get(TimezoneHeaderName)
// 如果未传递时区信息,使用默认时区
if timezone == "" { if timezone == "" {
timezone = DefaultTimezone timezone = requestctx.DefaultTimezone
} }
// 验证时区是否有效
if _, err := tools.GetLocation(timezone); err != nil { if _, err := tools.GetLocation(timezone); err != nil {
// 如果时区无效,使用默认时区 timezone = requestctx.DefaultTimezone
timezone = DefaultTimezone
} }
ctx := requestctx.WithTimezone(r.Context(), timezone)
// 将时区存储到context中
ctx := context.WithValue(r.Context(), timezoneKey{}, timezone)
next.ServeHTTP(w, r.WithContext(ctx)) next.ServeHTTP(w, r.WithContext(ctx))
}) })
} }
// TimezoneWithDefault 时区处理中间件(可自定义默认时区) // TimezoneWithDefault 时区处理中间件(可自定义默认时区)
// defaultTimezone: 默认时区,如果未指定则使用 AsiaShanghai
func TimezoneWithDefault(defaultTimezone string) func(http.Handler) http.Handler { func TimezoneWithDefault(defaultTimezone string) func(http.Handler) http.Handler {
// 验证默认时区是否有效
if _, err := tools.GetLocation(defaultTimezone); err != nil { if _, err := tools.GetLocation(defaultTimezone); err != nil {
defaultTimezone = DefaultTimezone defaultTimezone = requestctx.DefaultTimezone
} }
return func(next http.Handler) http.Handler { return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// 从请求头获取时区
timezone := r.Header.Get(TimezoneHeaderName) timezone := r.Header.Get(TimezoneHeaderName)
// 如果未传递时区信息,使用指定的默认时区
if timezone == "" { if timezone == "" {
timezone = defaultTimezone timezone = defaultTimezone
} }
// 验证时区是否有效
if _, err := tools.GetLocation(timezone); err != nil { if _, err := tools.GetLocation(timezone); err != nil {
// 如果时区无效,使用默认时区
timezone = defaultTimezone timezone = defaultTimezone
} }
ctx := requestctx.WithTimezone(r.Context(), timezone)
// 将时区存储到context中
ctx := context.WithValue(r.Context(), timezoneKey{}, timezone)
next.ServeHTTP(w, r.WithContext(ctx)) next.ServeHTTP(w, r.WithContext(ctx))
}) })
} }

41
requestctx/requestctx.go Normal file
View File

@@ -0,0 +1,41 @@
package requestctx
import (
"context"
"git.toowon.com/jimmy/go-common/tools"
)
type languageKey struct{}
type timezoneKey struct{}
const (
DefaultLanguage = "zh-CN"
DefaultTimezone = tools.AsiaShanghai
)
// WithLanguage 写入语言到 context
func WithLanguage(ctx context.Context, lang string) context.Context {
return context.WithValue(ctx, languageKey{}, lang)
}
// Language 从 context 读取语言
func Language(ctx context.Context) string {
if lang, ok := ctx.Value(languageKey{}).(string); ok && lang != "" {
return lang
}
return DefaultLanguage
}
// WithTimezone 写入时区到 context
func WithTimezone(ctx context.Context, tz string) context.Context {
return context.WithValue(ctx, timezoneKey{}, tz)
}
// Timezone 从 context 读取时区
func Timezone(ctx context.Context) string {
if tz, ok := ctx.Value(timezoneKey{}).(string); ok && tz != "" {
return tz
}
return DefaultTimezone
}

View File

@@ -1,6 +1,7 @@
package sms package sms
import ( import (
"context"
"crypto/hmac" "crypto/hmac"
"crypto/sha1" "crypto/sha1"
"encoding/base64" "encoding/base64"
@@ -11,29 +12,40 @@ import (
"net/url" "net/url"
"sort" "sort"
"strings" "strings"
"sync"
"sync/atomic"
"time" "time"
"git.toowon.com/jimmy/go-common/config" "git.toowon.com/jimmy/go-common/config"
"git.toowon.com/jimmy/go-common/logger"
) )
// SendResponse 发送短信响应 // SendResponse 发送短信响应
type SendResponse struct { type SendResponse struct {
// RequestID 请求ID
RequestID string `json:"RequestId"` RequestID string `json:"RequestId"`
Code string `json:"Code"`
// Code 响应码 Message string `json:"Message"`
Code string `json:"Code"` BizID string `json:"BizId"`
// Message 响应消息
Message string `json:"Message"`
// BizID 业务ID
BizID string `json:"BizId"`
} }
// SMS 短信发送器 // SMS 短信发送器
type SMS struct { type SMS struct {
config *config.SMSConfig config *config.SMSConfig
async bool
queue chan smsTask
workers int
wg sync.WaitGroup
closed bool
mu sync.Mutex
dropped atomic.Uint64
}
type smsTask struct {
phones []string
templateParam interface{}
templateCode string
requestID string
} }
// NewSMS 创建短信发送器 // NewSMS 创建短信发送器
@@ -41,81 +53,87 @@ func NewSMS(cfg *config.Config) *SMS {
if cfg == nil || cfg.SMS == nil { if cfg == nil || cfg.SMS == nil {
return &SMS{config: nil} return &SMS{config: nil}
} }
return &SMS{config: cfg.SMS} s := &SMS{
config: cfg.SMS,
async: cfg.SMS.IsAsync(),
workers: cfg.SMS.Workers,
}
if s.workers <= 0 {
s.workers = 2
}
queueSize := cfg.SMS.QueueSize
if queueSize <= 0 {
queueSize = 1000
}
if s.async {
s.queue = make(chan smsTask, queueSize)
for i := 0; i < s.workers; i++ {
s.wg.Add(1)
go s.worker()
}
}
return s
}
func (s *SMS) worker() {
defer s.wg.Done()
for task := range s.queue {
if _, err := s.SendSMS(task.phones, task.templateParam, task.templateCode); err != nil {
logger.FromContext(context.Background()).Error("async sms send failed", map[string]any{
"error": err.Error(),
"request_id": task.requestID,
"phones": task.phones,
})
}
}
} }
// getSMSConfig 获取短信配置(内部方法)
func (s *SMS) getSMSConfig() (*config.SMSConfig, error) { func (s *SMS) getSMSConfig() (*config.SMSConfig, error) {
if s.config == nil { if s.config == nil {
return nil, fmt.Errorf("SMS config is nil") return nil, fmt.Errorf("SMS config is nil")
} }
if s.config.AccessKeyID == "" { if s.config.AccessKeyID == "" {
return nil, fmt.Errorf("AccessKeyID is required") return nil, fmt.Errorf("AccessKeyID is required")
} }
if s.config.AccessKeySecret == "" { if s.config.AccessKeySecret == "" {
return nil, fmt.Errorf("AccessKeySecret is required") return nil, fmt.Errorf("AccessKeySecret is required")
} }
if s.config.SignName == "" { if s.config.SignName == "" {
return nil, fmt.Errorf("SignName is required") return nil, fmt.Errorf("SignName is required")
} }
// 设置默认值
if s.config.Region == "" { if s.config.Region == "" {
s.config.Region = "cn-hangzhou" s.config.Region = "cn-hangzhou"
} }
if s.config.Timeout == 0 { if s.config.Timeout == 0 {
s.config.Timeout = 10 s.config.Timeout = 5
} }
return s.config, nil return s.config, nil
} }
// SendSMS 发送短信 // SendSMS 同步发送短信
// phoneNumbers: 手机号列表
// templateParam: 模板参数map或JSON字符串
// templateCode: 模板代码(可选,如果为空使用配置中的模板代码)
func (s *SMS) SendSMS(phoneNumbers []string, templateParam interface{}, templateCode ...string) (*SendResponse, error) { func (s *SMS) SendSMS(phoneNumbers []string, templateParam interface{}, templateCode ...string) (*SendResponse, error) {
cfg, err := s.getSMSConfig() cfg, err := s.getSMSConfig()
if err != nil { if err != nil {
return nil, err return nil, err
} }
if len(phoneNumbers) == 0 { if len(phoneNumbers) == 0 {
return nil, fmt.Errorf("phone numbers are required") return nil, fmt.Errorf("phone numbers are required")
} }
// 使用配置中的模板代码(如果请求中未指定) templateCodeValue := cfg.TemplateCode
templateCodeValue := ""
if len(templateCode) > 0 && templateCode[0] != "" { if len(templateCode) > 0 && templateCode[0] != "" {
templateCodeValue = templateCode[0] templateCodeValue = templateCode[0]
} else {
templateCodeValue = cfg.TemplateCode
} }
if templateCodeValue == "" { if templateCodeValue == "" {
return nil, fmt.Errorf("template code is required") return nil, fmt.Errorf("template code is required")
} }
signName := cfg.SignName
// 处理模板参数
var templateParamJSON string var templateParamJSON string
if templateParam != nil { if templateParam != nil {
switch v := templateParam.(type) { switch v := templateParam.(type) {
case string: case string:
// 直接使用字符串必须是有效的JSON
templateParamJSON = v 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: default:
// 尝试JSON序列化
paramBytes, err := json.Marshal(v) paramBytes, err := json.Marshal(v)
if err != nil { if err != nil {
return nil, fmt.Errorf("failed to marshal template param: %w", err) return nil, fmt.Errorf("failed to marshal template param: %w", err)
@@ -126,104 +144,120 @@ func (s *SMS) SendSMS(phoneNumbers []string, templateParam interface{}, template
templateParamJSON = "{}" templateParamJSON = "{}"
} }
// 构建请求参数 params := map[string]string{
params := make(map[string]string) "Action": "SendSms",
params["Action"] = "SendSms" "Version": "2017-05-25",
params["Version"] = "2017-05-25" "RegionId": cfg.Region,
params["RegionId"] = cfg.Region "AccessKeyId": cfg.AccessKeyID,
params["AccessKeyId"] = cfg.AccessKeyID "Format": "JSON",
params["Format"] = "JSON" "SignatureMethod": "HMAC-SHA1",
params["SignatureMethod"] = "HMAC-SHA1" "SignatureVersion": "1.0",
params["SignatureVersion"] = "1.0" "SignatureNonce": fmt.Sprint(time.Now().UnixNano()),
params["SignatureNonce"] = fmt.Sprint(time.Now().UnixNano()) "Timestamp": time.Now().UTC().Format("2006-01-02T15:04:05Z"),
params["Timestamp"] = time.Now().UTC().Format("2006-01-02T15:04:05Z") "PhoneNumbers": strings.Join(phoneNumbers, ","),
params["PhoneNumbers"] = strings.Join(phoneNumbers, ",") "SignName": cfg.SignName,
params["SignName"] = signName "TemplateCode": templateCodeValue,
params["TemplateCode"] = templateCodeValue "TemplateParam": templateParamJSON,
params["TemplateParam"] = templateParamJSON }
params["Signature"] = s.calculateSignature(params, "POST", cfg.AccessKeySecret)
// 计算签名
signature := s.calculateSignature(params, "POST", cfg.AccessKeySecret)
params["Signature"] = signature
// 构建请求URL
endpoint := cfg.Endpoint endpoint := cfg.Endpoint
if endpoint == "" { if endpoint == "" {
endpoint = "https://dysmsapi.aliyuncs.com" endpoint = "https://dysmsapi.aliyuncs.com"
} }
// 发送HTTP请求
formData := url.Values{} formData := url.Values{}
for k, v := range params { for k, v := range params {
formData.Set(k, v) formData.Set(k, v)
} }
httpReq, err := http.NewRequest("POST", endpoint, strings.NewReader(formData.Encode())) httpReq, err := http.NewRequest(http.MethodPost, endpoint, strings.NewReader(formData.Encode()))
if err != nil { if err != nil {
return nil, fmt.Errorf("failed to create request: %w", err) return nil, fmt.Errorf("failed to create request: %w", err)
} }
httpReq.Header.Set("Content-Type", "application/x-www-form-urlencoded") httpReq.Header.Set("Content-Type", "application/x-www-form-urlencoded")
httpReq.Header.Set("Accept", "application/json") httpReq.Header.Set("Accept", "application/json")
client := &http.Client{ client := &http.Client{Timeout: time.Duration(cfg.Timeout) * time.Second}
Timeout: time.Duration(cfg.Timeout) * time.Second,
}
resp, err := client.Do(httpReq) resp, err := client.Do(httpReq)
if err != nil { if err != nil {
return nil, fmt.Errorf("failed to send request: %w", err) return nil, fmt.Errorf("failed to send request: %w", err)
} }
defer resp.Body.Close() defer resp.Body.Close()
// 读取响应
body, err := io.ReadAll(resp.Body) body, err := io.ReadAll(resp.Body)
if err != nil { if err != nil {
return nil, fmt.Errorf("failed to read response: %w", err) return nil, fmt.Errorf("failed to read response: %w", err)
} }
// 解析响应
var sendResp SendResponse var sendResp SendResponse
if err := json.Unmarshal(body, &sendResp); err != nil { if err := json.Unmarshal(body, &sendResp); err != nil {
return nil, fmt.Errorf("failed to parse response: %w", err) return nil, fmt.Errorf("failed to parse response: %w", err)
} }
// 检查响应码
if sendResp.Code != "OK" { if sendResp.Code != "OK" {
return &sendResp, fmt.Errorf("SMS send failed: Code=%s, Message=%s", sendResp.Code, sendResp.Message) return &sendResp, fmt.Errorf("SMS send failed: Code=%s, Message=%s", sendResp.Code, sendResp.Message)
} }
return &sendResp, nil return &sendResp, nil
} }
// calculateSignature 计算签名 // SendSMSAsync 异步发送短信
func (s *SMS) SendSMSAsync(ctx context.Context, phoneNumbers []string, templateParam interface{}, templateCode ...string) {
code := ""
if len(templateCode) > 0 {
code = templateCode[0]
}
task := smsTask{
phones: append([]string(nil), phoneNumbers...),
templateParam: templateParam,
templateCode: code,
requestID: logger.RequestIDFromContext(ctx),
}
if !s.async {
_, _ = s.SendSMS(task.phones, task.templateParam, task.templateCode)
return
}
select {
case s.queue <- task:
default:
s.dropped.Add(1)
logger.FromContext(ctx).Error("sms queue full, task dropped", map[string]any{
"phones": phoneNumbers,
})
}
}
// Close 关闭异步 worker
func (s *SMS) Close() error {
if !s.async {
return nil
}
s.mu.Lock()
if s.closed {
s.mu.Unlock()
return nil
}
s.closed = true
s.mu.Unlock()
close(s.queue)
s.wg.Wait()
return nil
}
func (s *SMS) calculateSignature(params map[string]string, method, accessKeySecret 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 {
keys = append(keys, k) keys = append(keys, k)
} }
sort.Strings(keys) sort.Strings(keys)
// 构建查询字符串
var queryParts []string var queryParts []string
for _, k := range keys { for _, k := range keys {
v := params[k] queryParts = append(queryParts, url.QueryEscape(k)+"="+url.QueryEscape(params[k]))
// URL编码
encodedKey := url.QueryEscape(k)
encodedValue := url.QueryEscape(v)
queryParts = append(queryParts, encodedKey+"="+encodedValue)
} }
queryString := strings.Join(queryParts, "&") queryString := strings.Join(queryParts, "&")
// 构建待签名字符串
stringToSign := method + "&" + url.QueryEscape("/") + "&" + url.QueryEscape(queryString) stringToSign := method + "&" + url.QueryEscape("/") + "&" + url.QueryEscape(queryString)
// 计算HMAC-SHA1签名
mac := hmac.New(sha1.New, []byte(accessKeySecret+"&")) mac := hmac.New(sha1.New, []byte(accessKeySecret+"&"))
mac.Write([]byte(stringToSign)) mac.Write([]byte(stringToSign))
signature := base64.StdEncoding.EncodeToString(mac.Sum(nil)) return base64.StdEncoding.EncodeToString(mac.Sum(nil))
return signature
} }

View File

@@ -39,37 +39,32 @@ func NewUploadHandler(cfg UploadHandlerConfig) *UploadHandler {
} }
// ServeHTTP 处理文件上传请求 // ServeHTTP 处理文件上传请求
// 请求方式: POST
// 表单字段: file (文件)
// 可选字段: 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 {
commonhttp.Error(w, 4001, "Method not allowed") handler.Error("common.method_not_allowed")
return return
} }
// 解析multipart表单
err := r.ParseMultipartForm(h.maxFileSize) err := r.ParseMultipartForm(h.maxFileSize)
if err != nil { if err != nil {
commonhttp.Error(w, 4002, fmt.Sprintf("Failed to parse form: %v", err)) handler.Error("common.invalid_request")
return return
} }
// 获取文件
file, header, err := r.FormFile("file") file, header, err := r.FormFile("file")
if err != nil { if err != nil {
commonhttp.Error(w, 4003, fmt.Sprintf("Failed to get file: %v", err)) handler.Error("common.invalid_request")
return return
} }
defer file.Close() defer file.Close()
// 检查文件大小
if h.maxFileSize > 0 && header.Size > h.maxFileSize { if h.maxFileSize > 0 && header.Size > h.maxFileSize {
commonhttp.Error(w, 1001, fmt.Sprintf("File size exceeds limit: %d bytes", h.maxFileSize)) handler.Error("storage.file_too_large")
return return
} }
// 检查文件扩展名
if len(h.allowedExts) > 0 { if len(h.allowedExts) > 0 {
ext := strings.ToLower(filepath.Ext(header.Filename)) ext := strings.ToLower(filepath.Ext(header.Filename))
allowed := false allowed := false
@@ -80,22 +75,19 @@ func (h *UploadHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
} }
} }
if !allowed { if !allowed {
commonhttp.Error(w, 1002, fmt.Sprintf("File extension not allowed. Allowed: %v", h.allowedExts)) handler.Error("storage.invalid_extension")
return return
} }
} }
// 生成对象键
prefix := h.objectPrefix prefix := h.objectPrefix
if r.FormValue("prefix") != "" { if r.FormValue("prefix") != "" {
prefix = r.FormValue("prefix") prefix = r.FormValue("prefix")
} }
// 生成唯一文件名
filename := generateUniqueFilename(header.Filename) filename := generateUniqueFilename(header.Filename)
objectKey := GenerateObjectKey(prefix, filename) objectKey := GenerateObjectKey(prefix, filename)
// 获取文件类型
contentType := header.Header.Get("Content-Type") contentType := header.Header.Get("Content-Type")
if contentType == "" { if contentType == "" {
contentType = mime.TypeByExtension(filepath.Ext(header.Filename)) contentType = mime.TypeByExtension(filepath.Ext(header.Filename))
@@ -104,22 +96,18 @@ func (h *UploadHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
} }
} }
// 上传文件
ctx := r.Context() ctx := r.Context()
err = h.storage.Upload(ctx, objectKey, file, contentType) if err = h.storage.Upload(ctx, objectKey, file, contentType); err != nil {
if err != nil { handler.Error("system.internal_error")
commonhttp.SystemError(w, fmt.Sprintf("Failed to upload file: %v", err))
return return
} }
// 获取文件URL
fileURL, err := h.storage.GetURL(objectKey, 0) fileURL, err := h.storage.GetURL(objectKey, 0)
if err != nil { if err != nil {
commonhttp.SystemError(w, fmt.Sprintf("Failed to get file URL: %v", err)) handler.Error("system.internal_error")
return return
} }
// 返回结果
result := UploadResult{ result := UploadResult{
ObjectKey: objectKey, ObjectKey: objectKey,
URL: fileURL, URL: fileURL,
@@ -127,8 +115,7 @@ func (h *UploadHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
ContentType: contentType, ContentType: contentType,
UploadTime: time.Now(), UploadTime: time.Now(),
} }
handler.Success(result)
commonhttp.Success(w, result, "Upload successful")
} }
// generateUniqueFilename 生成唯一文件名 // generateUniqueFilename 生成唯一文件名

222
storage/local.go Normal file
View File

@@ -0,0 +1,222 @@
package storage
import (
"context"
"fmt"
"io"
"net/url"
"os"
"path"
"path/filepath"
"strings"
"git.toowon.com/jimmy/go-common/config"
)
// LocalStorage 本地存储实现
// 将对象写入本地文件夹BaseDir对象键 objectKey 作为相对路径使用。
//
// 典型用法:
// - 上传Upload(ctx, "uploads/2026/01/01/a.png", reader)
// - 查看:配合 ProxyHandler 或 http.FileServer 对外提供访问
type LocalStorage struct {
baseDir string
publicURL string
}
// NewLocalStorage 创建本地存储实例
func NewLocalStorage(cfg *config.LocalStorageConfig) (*LocalStorage, error) {
if cfg == nil {
return nil, fmt.Errorf("LocalStorage config is nil")
}
if strings.TrimSpace(cfg.BaseDir) == "" {
return nil, fmt.Errorf("LocalStorage baseDir is empty")
}
absBase, err := filepath.Abs(cfg.BaseDir)
if err != nil {
return nil, fmt.Errorf("failed to get absolute baseDir: %w", err)
}
// 确保根目录存在
if err := os.MkdirAll(absBase, 0o755); err != nil {
return nil, fmt.Errorf("failed to create baseDir: %w", err)
}
return &LocalStorage{
baseDir: absBase,
publicURL: strings.TrimSpace(cfg.PublicURL),
}, nil
}
// Upload 上传文件到本地文件夹
func (s *LocalStorage) Upload(ctx context.Context, objectKey string, reader io.Reader, contentType ...string) error {
_ = ctx
_ = contentType // 本地写文件不依赖 contentType可由上层自行记录
dstPath, err := s.resolvePath(objectKey)
if err != nil {
return err
}
// 确保目录存在
if err := os.MkdirAll(filepath.Dir(dstPath), 0o755); err != nil {
return fmt.Errorf("failed to create directory: %w", err)
}
// 原子写入:先写临时文件,再 rename
tmp, err := os.CreateTemp(filepath.Dir(dstPath), ".upload-*")
if err != nil {
return fmt.Errorf("failed to create temp file: %w", err)
}
tmpName := tmp.Name()
defer func() {
_ = tmp.Close()
_ = os.Remove(tmpName)
}()
if _, err := io.Copy(tmp, reader); err != nil {
return fmt.Errorf("failed to write temp file: %w", err)
}
if err := tmp.Close(); err != nil {
return fmt.Errorf("failed to close temp file: %w", err)
}
// 如果目标文件已存在,先删除(保证跨平台兼容 rename 行为)
_ = os.Remove(dstPath)
if err := os.Rename(tmpName, dstPath); err != nil {
return fmt.Errorf("failed to move temp file to destination: %w", err)
}
return nil
}
// GetURL 获取本地文件访问URL
// - 若配置了 publicURL
// - 包含 "{objectKey}" 占位符:替换为 url.QueryEscape(objectKey)
// - 否则认为是 URL 前缀:自动拼接 objectKey用 path.Join 处理斜杠)
//
// - 未配置 publicURL返回 objectKey相对路径
func (s *LocalStorage) GetURL(objectKey string, expires int64) (string, error) {
_ = expires // 本地存储不提供签名URL忽略 expires
cleanKey, err := normalizeObjectKey(objectKey)
if err != nil {
return "", err
}
if s.publicURL == "" {
return cleanKey, nil
}
if strings.Contains(s.publicURL, "{objectKey}") {
return strings.ReplaceAll(s.publicURL, "{objectKey}", url.QueryEscape(cleanKey)), nil
}
// 作为前缀拼接
trimmed := strings.TrimRight(s.publicURL, "/")
return trimmed + "/" + path.Clean("/" + cleanKey)[1:], nil
}
// Delete 删除本地文件
func (s *LocalStorage) Delete(ctx context.Context, objectKey string) error {
_ = ctx
dstPath, err := s.resolvePath(objectKey)
if err != nil {
return err
}
if err := os.Remove(dstPath); err != nil {
if os.IsNotExist(err) {
return nil
}
return fmt.Errorf("failed to delete file: %w", err)
}
return nil
}
// Exists 检查本地文件是否存在
func (s *LocalStorage) Exists(ctx context.Context, objectKey string) (bool, error) {
_ = ctx
dstPath, err := s.resolvePath(objectKey)
if err != nil {
return false, err
}
info, err := os.Stat(dstPath)
if err != nil {
if os.IsNotExist(err) {
return false, nil
}
return false, fmt.Errorf("failed to stat file: %w", err)
}
if info.IsDir() {
return false, nil
}
return true, nil
}
// GetObject 获取本地文件内容
func (s *LocalStorage) GetObject(ctx context.Context, objectKey string) (io.ReadCloser, error) {
_ = ctx
dstPath, err := s.resolvePath(objectKey)
if err != nil {
return nil, err
}
f, err := os.Open(dstPath)
if err != nil {
return nil, fmt.Errorf("failed to open file: %w", err)
}
return f, nil
}
func (s *LocalStorage) resolvePath(objectKey string) (string, error) {
cleanKey, err := normalizeObjectKey(objectKey)
if err != nil {
return "", err
}
// 将 URL 风格路径转换为 OS 路径
full := filepath.Join(s.baseDir, filepath.FromSlash(cleanKey))
// 防御:确保仍在 baseDir 下
rel, err := filepath.Rel(s.baseDir, full)
if err != nil {
return "", fmt.Errorf("failed to resolve path: %w", err)
}
if rel == "." || strings.HasPrefix(rel, ".."+string(os.PathSeparator)) || rel == ".." {
return "", fmt.Errorf("invalid objectKey: %s", objectKey)
}
return full, nil
}
func normalizeObjectKey(objectKey string) (string, error) {
key := strings.TrimSpace(objectKey)
if key == "" {
return "", fmt.Errorf("objectKey is empty")
}
// 兼容 Windows 风格路径,统一为 URL 风格
key = strings.ReplaceAll(key, "\\", "/")
// 清洗路径,去除多余的 . / ..
// 加前缀 "/" 让 Clean 以绝对路径方式处理,避免出现空结果
clean := path.Clean("/" + key)
clean = strings.TrimPrefix(clean, "/")
if clean == "" || clean == "." {
return "", fmt.Errorf("invalid objectKey: %s", objectKey)
}
// 不允许以 "/" 结尾(必须指向文件)
if strings.HasSuffix(clean, "/") {
return "", fmt.Errorf("objectKey cannot be a directory: %s", objectKey)
}
return clean, nil
}

102
storage/local_test.go Normal file
View File

@@ -0,0 +1,102 @@
package storage
import (
"bytes"
"context"
"io"
"testing"
"git.toowon.com/jimmy/go-common/config"
)
func TestLocalStorage_UploadGetExistsDelete(t *testing.T) {
t.Parallel()
cfg := &config.LocalStorageConfig{
BaseDir: t.TempDir(),
PublicURL: "http://localhost:8080/file?key={objectKey}",
}
s, err := NewLocalStorage(cfg)
if err != nil {
t.Fatalf("NewLocalStorage error: %v", err)
}
ctx := context.Background()
objectKey := "uploads/2026/01/30/hello.txt"
body := []byte("hello local storage")
if err := s.Upload(ctx, objectKey, bytes.NewReader(body), "text/plain"); err != nil {
t.Fatalf("Upload error: %v", err)
}
exists, err := s.Exists(ctx, objectKey)
if err != nil {
t.Fatalf("Exists error: %v", err)
}
if !exists {
t.Fatalf("expected exists=true")
}
rc, err := s.GetObject(ctx, objectKey)
if err != nil {
t.Fatalf("GetObject error: %v", err)
}
defer rc.Close()
got, err := io.ReadAll(rc)
if err != nil {
t.Fatalf("ReadAll error: %v", err)
}
if !bytes.Equal(got, body) {
t.Fatalf("content mismatch: got=%q want=%q", string(got), string(body))
}
u, err := s.GetURL(objectKey, 0)
if err != nil {
t.Fatalf("GetURL error: %v", err)
}
if u == "" {
t.Fatalf("expected non-empty url")
}
if err := s.Delete(ctx, objectKey); err != nil {
t.Fatalf("Delete error: %v", err)
}
exists, err = s.Exists(ctx, objectKey)
if err != nil {
t.Fatalf("Exists error: %v", err)
}
if exists {
t.Fatalf("expected exists=false after delete")
}
}
func TestNormalizeObjectKey(t *testing.T) {
t.Parallel()
if _, err := normalizeObjectKey(""); err == nil {
t.Fatalf("expected error for empty objectKey")
}
if _, err := normalizeObjectKey(" "); err == nil {
t.Fatalf("expected error for blank objectKey")
}
if _, err := normalizeObjectKey("."); err == nil {
t.Fatalf("expected error for '.'")
}
clean1, err := normalizeObjectKey("a/b/")
if err != nil {
t.Fatalf("normalizeObjectKey error: %v", err)
}
if clean1 != "a/b" {
t.Fatalf("unexpected clean key: %q", clean1)
}
clean, err := normalizeObjectKey(`\a\..\b\c.txt`)
if err != nil {
t.Fatalf("normalizeObjectKey error: %v", err)
}
if clean != "b/c.txt" {
t.Fatalf("unexpected clean key: %q", clean)
}
}

View File

@@ -39,10 +39,11 @@ type StorageType string
const ( const (
StorageTypeOSS StorageType = "oss" StorageTypeOSS StorageType = "oss"
StorageTypeMinIO StorageType = "minio" StorageTypeMinIO StorageType = "minio"
StorageTypeLocal StorageType = "local"
) )
// NewStorage 创建存储实例 // NewStorage 创建存储实例
// storageType: 存储类型ossminio // storageType: 存储类型oss/minio/local
// cfg: 配置对象 // cfg: 配置对象
func NewStorage(storageType StorageType, cfg *config.Config) (Storage, error) { func NewStorage(storageType StorageType, cfg *config.Config) (Storage, error) {
switch storageType { switch storageType {
@@ -58,6 +59,12 @@ func NewStorage(storageType StorageType, cfg *config.Config) (Storage, error) {
return nil, fmt.Errorf("MinIO config is nil") return nil, fmt.Errorf("MinIO config is nil")
} }
return NewMinIOStorage(minioConfig) return NewMinIOStorage(minioConfig)
case StorageTypeLocal:
localCfg := cfg.GetLocalStorage()
if localCfg == nil {
return nil, fmt.Errorf("LocalStorage config is nil")
}
return NewLocalStorage(localCfg)
default: default:
return nil, fmt.Errorf("unsupported storage type: %s", storageType) return nil, fmt.Errorf("unsupported storage type: %s", storageType)
} }

View File

@@ -37,4 +37,4 @@ cp templates/Makefile.example Makefile
## 完整文档 ## 完整文档
详细使用说明请查看:[MIGRATION.md](../MIGRATION.md) 详细使用说明请查看:[INTEGRATION.md](../INTEGRATION.md) 第 7 节「数据库迁移」

99
tools/convertor.go Normal file
View 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
}