Compare commits
6 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| e3d9bbbcc5 | |||
| 47cbdbb2de | |||
| f8f4df4073 | |||
| 684923f9cb | |||
| 545c6ef6a4 | |||
| 5cfa0d7ce5 |
25
README.md
25
README.md
@@ -67,10 +67,20 @@
|
|||||||
### 8. 短信工具 (sms)
|
### 8. 短信工具 (sms)
|
||||||
提供阿里云短信发送功能,支持模板短信和批量发送,使用Go标准库实现。
|
提供阿里云短信发送功能,支持模板短信和批量发送,使用Go标准库实现。
|
||||||
|
|
||||||
### 9. 工厂工具 (factory)
|
### 9. Excel导出工具 (excel)
|
||||||
提供从配置文件直接创建已初始化客户端对象的功能,包括数据库、Redis、邮件、短信、日志等,避免调用方重复实现创建逻辑。
|
提供数据导出到Excel文件的功能,支持结构体切片、自定义格式化、多工作表等特性。
|
||||||
|
|
||||||
### 10. 日志工具 (logger)
|
**功能特性**:
|
||||||
|
- 支持结构体切片自动导出
|
||||||
|
- 支持嵌套字段访问(如 "User.Name")
|
||||||
|
- 支持自定义格式化函数
|
||||||
|
- 自动调整列宽和表头样式
|
||||||
|
- 支持导出到文件或HTTP响应
|
||||||
|
|
||||||
|
### 10. 工厂工具 (factory)
|
||||||
|
提供从配置文件直接创建已初始化客户端对象的功能,包括数据库、Redis、邮件、短信、日志、Excel等,避免调用方重复实现创建逻辑。
|
||||||
|
|
||||||
|
### 11. 日志工具 (logger)
|
||||||
提供统一的日志记录功能,支持多种日志级别和输出方式,使用Go标准库实现。
|
提供统一的日志记录功能,支持多种日志级别和输出方式,使用Go标准库实现。
|
||||||
|
|
||||||
---
|
---
|
||||||
@@ -90,6 +100,7 @@
|
|||||||
| 邮件 | `SendEmail()` | 直接调用 | ⭐⭐⭐ |
|
| 邮件 | `SendEmail()` | 直接调用 | ⭐⭐⭐ |
|
||||||
| 短信 | `SendSMS()` | 直接调用 | ⭐⭐⭐ |
|
| 短信 | `SendSMS()` | 直接调用 | ⭐⭐⭐ |
|
||||||
| 存储 | `UploadFile()`, `GetFileURL()` | 直接调用 | ⭐⭐⭐ |
|
| 存储 | `UploadFile()`, `GetFileURL()` | 直接调用 | ⭐⭐⭐ |
|
||||||
|
| Excel导出 | `ExportToExcel()`, `ExportToExcelFile()` | 直接调用 | ⭐⭐⭐ |
|
||||||
| **Get方法(高级功能)** | | | |
|
| **Get方法(高级功能)** | | | |
|
||||||
| 数据库 | `GetDatabase()` | 返回GORM对象,用于复杂查询 | ⭐⭐ |
|
| 数据库 | `GetDatabase()` | 返回GORM对象,用于复杂查询 | ⭐⭐ |
|
||||||
| Redis高级 | `GetRedisClient()` | 返回Redis客户端,用于Hash/List/Set等 | ⭐ |
|
| Redis高级 | `GetRedisClient()` | 返回Redis客户端,用于Hash/List/Set等 | ⭐ |
|
||||||
@@ -277,6 +288,14 @@ fac.SendSMS([]string{"13800138000"}, map[string]string{"code": "123456"})
|
|||||||
// 文件上传
|
// 文件上传
|
||||||
url, _ := fac.UploadFile(ctx, "images/test.jpg", file, "image/jpeg")
|
url, _ := fac.UploadFile(ctx, "images/test.jpg", file, "image/jpeg")
|
||||||
|
|
||||||
|
// Excel导出
|
||||||
|
columns := []factory.ExportColumn{
|
||||||
|
{Header: "ID", Field: "ID", Width: 10},
|
||||||
|
{Header: "姓名", Field: "Name", Width: 20},
|
||||||
|
{Header: "邮箱", Field: "Email", Width: 30},
|
||||||
|
}
|
||||||
|
fac.ExportToExcelFile("users.xlsx", "用户列表", columns, users)
|
||||||
|
|
||||||
// 数据库(高级功能)
|
// 数据库(高级功能)
|
||||||
db, _ := fac.GetDatabase()
|
db, _ := fac.GetDatabase()
|
||||||
db.Find(&users)
|
db.Find(&users)
|
||||||
|
|||||||
@@ -11,8 +11,10 @@
|
|||||||
- [存储工具](./storage.md) - 文件上传和查看(OSS、MinIO)
|
- [存储工具](./storage.md) - 文件上传和查看(OSS、MinIO)
|
||||||
- [邮件工具](./email.md) - SMTP邮件发送
|
- [邮件工具](./email.md) - SMTP邮件发送
|
||||||
- [短信工具](./sms.md) - 阿里云短信发送
|
- [短信工具](./sms.md) - 阿里云短信发送
|
||||||
|
- [Excel导出工具](./excel.md) - 数据导出到Excel文件
|
||||||
- [工厂工具](./factory.md) - 从配置直接创建已初始化客户端对象
|
- [工厂工具](./factory.md) - 从配置直接创建已初始化客户端对象
|
||||||
- [日志工具](./logger.md) - 统一的日志记录功能
|
- [日志工具](./logger.md) - 统一的日志记录功能
|
||||||
|
- [国际化工具](./i18n.md) - 多语言内容管理和国际化支持
|
||||||
|
|
||||||
## 快速开始
|
## 快速开始
|
||||||
|
|
||||||
@@ -77,20 +79,26 @@ now := tools.Now()
|
|||||||
str := tools.FormatDateTime(now)
|
str := tools.FormatDateTime(now)
|
||||||
```
|
```
|
||||||
|
|
||||||
#### HTTP响应(Handler黑盒模式)
|
#### HTTP响应(Factory黑盒模式,推荐)
|
||||||
|
|
||||||
```go
|
```go
|
||||||
import (
|
import (
|
||||||
"net/http"
|
"net/http"
|
||||||
commonhttp "git.toowon.com/jimmy/go-common/http"
|
"git.toowon.com/jimmy/go-common/factory"
|
||||||
|
"git.toowon.com/jimmy/go-common/tools"
|
||||||
)
|
)
|
||||||
|
|
||||||
func GetUser(h *commonhttp.Handler) {
|
func GetUser(w http.ResponseWriter, r *http.Request) {
|
||||||
id := h.GetQueryInt64("id", 0)
|
fac, _ := factory.NewFactoryFromFile("config.json")
|
||||||
h.Success(data)
|
|
||||||
|
// 获取查询参数(使用类型转换方法)
|
||||||
|
id := tools.ConvertInt64(r.URL.Query().Get("id"), 0)
|
||||||
|
|
||||||
|
// 返回成功响应
|
||||||
|
fac.Success(w, data)
|
||||||
}
|
}
|
||||||
|
|
||||||
http.HandleFunc("/user", commonhttp.HandleFunc(GetUser))
|
http.HandleFunc("/user", GetUser)
|
||||||
```
|
```
|
||||||
|
|
||||||
#### 中间件(生产级配置)
|
#### 中间件(生产级配置)
|
||||||
|
|||||||
459
docs/excel.md
Normal file
459
docs/excel.md
Normal file
@@ -0,0 +1,459 @@
|
|||||||
|
# Excel导出工具文档
|
||||||
|
|
||||||
|
## 概述
|
||||||
|
|
||||||
|
Excel导出工具提供了将数据导出到Excel文件的功能,支持结构体切片、自定义格式化、多工作表等特性。通过工厂模式,外部项目可以方便地使用Excel导出功能。
|
||||||
|
|
||||||
|
## 功能特性
|
||||||
|
|
||||||
|
- **黑盒模式**:提供直接调用的方法,无需获取Excel对象
|
||||||
|
- **延迟初始化**:Excel导出器在首次使用时才创建
|
||||||
|
- **支持结构体切片**:自动将结构体切片转换为Excel行数据
|
||||||
|
- **支持嵌套字段**:支持访问嵌套结构体字段(如 "User.Name")
|
||||||
|
- **自定义格式化**:支持自定义字段值的格式化函数
|
||||||
|
- **自动列宽**:自动调整列宽以适应内容
|
||||||
|
- **表头样式**:自动应用表头样式(加粗、背景色等)
|
||||||
|
- **智能工作表管理**:自动处理工作表的创建和删除,避免产生空sheet
|
||||||
|
- **ExportData接口**:支持实现ExportData接口进行高级定制
|
||||||
|
|
||||||
|
## 使用方法
|
||||||
|
|
||||||
|
### 1. 创建工厂(推荐)
|
||||||
|
|
||||||
|
```go
|
||||||
|
import "git.toowon.com/jimmy/go-common/factory"
|
||||||
|
|
||||||
|
// 方式1:从配置文件创建(推荐)
|
||||||
|
fac, err := factory.NewFactoryFromFile("./config.json")
|
||||||
|
if err != nil {
|
||||||
|
log.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// 方式2:从配置对象创建
|
||||||
|
cfg, _ := config.LoadFromFile("./config.json")
|
||||||
|
fac := factory.NewFactory(cfg)
|
||||||
|
|
||||||
|
// 方式3:Excel导出不需要配置,可以传nil
|
||||||
|
fac := factory.NewFactory(nil)
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2. 导出结构体切片到文件(黑盒模式,推荐)
|
||||||
|
|
||||||
|
```go
|
||||||
|
// 定义结构体
|
||||||
|
type User struct {
|
||||||
|
ID int `json:"id"`
|
||||||
|
Name string `json:"name"`
|
||||||
|
Email string `json:"email"`
|
||||||
|
CreatedAt time.Time `json:"created_at"`
|
||||||
|
Status int `json:"status"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// 准备数据
|
||||||
|
users := []User{
|
||||||
|
{ID: 1, Name: "Alice", Email: "alice@example.com", CreatedAt: time.Now(), Status: 1},
|
||||||
|
{ID: 2, Name: "Bob", Email: "bob@example.com", CreatedAt: time.Now(), Status: 1},
|
||||||
|
}
|
||||||
|
|
||||||
|
// 定义导出列
|
||||||
|
columns := []factory.ExportColumn{
|
||||||
|
{Header: "ID", Field: "ID", Width: 10},
|
||||||
|
{Header: "姓名", Field: "Name", Width: 20},
|
||||||
|
{Header: "邮箱", Field: "Email", Width: 30},
|
||||||
|
{Header: "创建时间", Field: "CreatedAt", Width: 20},
|
||||||
|
{Header: "状态", Field: "Status", Width: 10},
|
||||||
|
}
|
||||||
|
|
||||||
|
// 导出到文件
|
||||||
|
err := fac.ExportToExcelFile("users.xlsx", "用户列表", columns, users)
|
||||||
|
if err != nil {
|
||||||
|
log.Fatal(err)
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 3. 导出到HTTP响应(黑盒模式,推荐)
|
||||||
|
|
||||||
|
```go
|
||||||
|
import "net/http"
|
||||||
|
|
||||||
|
func exportUsersHandler(w http.ResponseWriter, r *http.Request) {
|
||||||
|
fac, _ := factory.NewFactoryFromFile("./config.json")
|
||||||
|
|
||||||
|
users := []User{
|
||||||
|
{ID: 1, Name: "Alice", Email: "alice@example.com", CreatedAt: time.Now(), Status: 1},
|
||||||
|
{ID: 2, Name: "Bob", Email: "bob@example.com", CreatedAt: time.Now(), Status: 1},
|
||||||
|
}
|
||||||
|
|
||||||
|
columns := []factory.ExportColumn{
|
||||||
|
{Header: "ID", Field: "ID"},
|
||||||
|
{Header: "姓名", Field: "Name"},
|
||||||
|
{Header: "邮箱", Field: "Email"},
|
||||||
|
}
|
||||||
|
|
||||||
|
// 设置HTTP响应头
|
||||||
|
w.Header().Set("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
|
||||||
|
w.Header().Set("Content-Disposition", "attachment; filename=users.xlsx")
|
||||||
|
|
||||||
|
// 导出到响应
|
||||||
|
err := fac.ExportToExcel(w, "用户列表", columns, users)
|
||||||
|
if err != nil {
|
||||||
|
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 4. 使用格式化函数(黑盒模式,推荐)
|
||||||
|
|
||||||
|
```go
|
||||||
|
import "git.toowon.com/jimmy/go-common/excel"
|
||||||
|
|
||||||
|
columns := []factory.ExportColumn{
|
||||||
|
{Header: "ID", Field: "ID", Width: 10},
|
||||||
|
{Header: "姓名", Field: "Name", Width: 20},
|
||||||
|
{
|
||||||
|
Header: "创建时间",
|
||||||
|
Field: "CreatedAt",
|
||||||
|
Width: 20,
|
||||||
|
Format: excel.AdaptTimeFormatter(tools.FormatDateTime), // 使用适配器直接调用tools函数
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Header: "状态",
|
||||||
|
Field: "Status",
|
||||||
|
Width: 10,
|
||||||
|
Format: func(value interface{}) string {
|
||||||
|
// 自定义格式化函数
|
||||||
|
if status, ok := value.(int); ok {
|
||||||
|
if status == 1 {
|
||||||
|
return "启用"
|
||||||
|
}
|
||||||
|
return "禁用"
|
||||||
|
}
|
||||||
|
return ""
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
err := fac.ExportToExcelFile("users.xlsx", "用户列表", columns, users)
|
||||||
|
```
|
||||||
|
|
||||||
|
### 5. 使用ExportData接口(高级功能)
|
||||||
|
|
||||||
|
```go
|
||||||
|
// 实现ExportData接口
|
||||||
|
type UserExportData struct {
|
||||||
|
users []User
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetExportColumns 获取导出列定义
|
||||||
|
func (d *UserExportData) GetExportColumns() []excel.ExportColumn {
|
||||||
|
return []excel.ExportColumn{
|
||||||
|
{Header: "ID", Field: "ID", Width: 10},
|
||||||
|
{Header: "姓名", Field: "Name", Width: 20},
|
||||||
|
{Header: "邮箱", Field: "Email", Width: 30},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetExportRows 获取导出数据行
|
||||||
|
func (d *UserExportData) GetExportRows() [][]interface{} {
|
||||||
|
rows := make([][]interface{}, 0, len(d.users))
|
||||||
|
for _, user := range d.users {
|
||||||
|
row := []interface{}{
|
||||||
|
user.ID,
|
||||||
|
user.Name,
|
||||||
|
user.Email,
|
||||||
|
}
|
||||||
|
rows = append(rows, row)
|
||||||
|
}
|
||||||
|
return rows
|
||||||
|
}
|
||||||
|
|
||||||
|
// 使用
|
||||||
|
exportData := &UserExportData{users: users}
|
||||||
|
columns := exportData.GetExportColumns()
|
||||||
|
err := fac.ExportToExcelFile("users.xlsx", "用户列表", columns, exportData)
|
||||||
|
```
|
||||||
|
|
||||||
|
### 6. 获取Excel对象(高级功能)
|
||||||
|
|
||||||
|
```go
|
||||||
|
// 获取Excel导出器对象(仅在需要高级功能时使用)
|
||||||
|
excel, err := fac.GetExcel()
|
||||||
|
if err != nil {
|
||||||
|
log.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// 获取excelize.File对象,用于高级操作
|
||||||
|
file := excel.GetFile()
|
||||||
|
|
||||||
|
// 创建多个工作表
|
||||||
|
file.NewSheet("Sheet2")
|
||||||
|
file.SetCellValue("Sheet2", "A1", "数据")
|
||||||
|
|
||||||
|
// 自定义样式
|
||||||
|
style, _ := file.NewStyle(&excelize.Style{
|
||||||
|
Font: &excelize.Font{
|
||||||
|
Bold: true,
|
||||||
|
Size: 14,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
file.SetCellStyle("Sheet2", "A1", "A1", style)
|
||||||
|
```
|
||||||
|
|
||||||
|
## API 参考
|
||||||
|
|
||||||
|
### 工厂方法(黑盒模式,推荐使用)
|
||||||
|
|
||||||
|
#### ExportToExcel(w io.Writer, sheetName string, columns []ExportColumn, data interface{}) error
|
||||||
|
|
||||||
|
导出数据到Writer。
|
||||||
|
|
||||||
|
**参数:**
|
||||||
|
- `w`: Writer对象(如http.ResponseWriter)
|
||||||
|
- `sheetName`: 工作表名称(可选,默认为"Sheet1")
|
||||||
|
- `columns`: 列定义
|
||||||
|
- `data`: 数据列表(可以是结构体切片或实现了ExportData接口的对象)
|
||||||
|
|
||||||
|
**返回:** 错误信息
|
||||||
|
|
||||||
|
**工作表处理逻辑:**
|
||||||
|
- 如果 `sheetName` 为空或未指定,默认使用 "Sheet1"
|
||||||
|
- 如果指定的工作表已存在,直接使用该工作表
|
||||||
|
- 如果指定的工作表不存在,会自动创建新工作表
|
||||||
|
- 如果使用自定义名称(非"Sheet1"),会自动删除默认的"Sheet1"工作表,避免产生空sheet
|
||||||
|
|
||||||
|
**示例:**
|
||||||
|
```go
|
||||||
|
// 使用默认Sheet1
|
||||||
|
fac.ExportToExcel(w, "", columns, users)
|
||||||
|
|
||||||
|
// 使用自定义工作表名称
|
||||||
|
fac.ExportToExcel(w, "用户列表", columns, users)
|
||||||
|
```
|
||||||
|
|
||||||
|
#### ExportToExcelFile(filePath string, sheetName string, columns []ExportColumn, data interface{}) error
|
||||||
|
|
||||||
|
导出数据到文件。
|
||||||
|
|
||||||
|
**参数:**
|
||||||
|
- `filePath`: 文件路径
|
||||||
|
- `sheetName`: 工作表名称(可选,默认为"Sheet1")
|
||||||
|
- `columns`: 列定义
|
||||||
|
- `data`: 数据列表
|
||||||
|
|
||||||
|
**返回:** 错误信息
|
||||||
|
|
||||||
|
**工作表处理逻辑:**
|
||||||
|
- 如果 `sheetName` 为空或未指定,默认使用 "Sheet1"
|
||||||
|
- 如果指定的工作表已存在,直接使用该工作表
|
||||||
|
- 如果指定的工作表不存在,会自动创建新工作表
|
||||||
|
- 如果使用自定义名称(非"Sheet1"),会自动删除默认的"Sheet1"工作表,避免产生空sheet
|
||||||
|
|
||||||
|
**示例:**
|
||||||
|
```go
|
||||||
|
// 使用默认Sheet1
|
||||||
|
fac.ExportToExcelFile("users.xlsx", "", columns, users)
|
||||||
|
|
||||||
|
// 使用自定义工作表名称
|
||||||
|
fac.ExportToExcelFile("users.xlsx", "用户列表", columns, users)
|
||||||
|
```
|
||||||
|
|
||||||
|
### 高级方法
|
||||||
|
|
||||||
|
#### GetExcel() (*excel.Excel, error)
|
||||||
|
|
||||||
|
获取Excel导出器对象。
|
||||||
|
|
||||||
|
**返回:** Excel导出器对象和错误信息
|
||||||
|
|
||||||
|
**说明:**
|
||||||
|
- 仅在需要使用高级功能时使用
|
||||||
|
- 推荐使用黑盒方法:`ExportToExcel()`、`ExportToExcelFile()`
|
||||||
|
|
||||||
|
### 结构体类型
|
||||||
|
|
||||||
|
#### ExportColumn
|
||||||
|
|
||||||
|
导出列定义。
|
||||||
|
|
||||||
|
```go
|
||||||
|
type ExportColumn struct {
|
||||||
|
Header string // 表头名称
|
||||||
|
Field string // 数据字段名(支持嵌套字段,如 "User.Name")
|
||||||
|
Width float64 // 列宽(可选,0表示自动)
|
||||||
|
Format func(interface{}) string // 格式化函数(可选)
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**字段说明:**
|
||||||
|
- `Header`: 表头显示的名称
|
||||||
|
- `Field`: 数据字段名,支持嵌套字段(如 "User.Name")
|
||||||
|
- `Width`: 列宽,0表示自动调整
|
||||||
|
- `Format`: 格式化函数,用于自定义字段值的显示格式
|
||||||
|
|
||||||
|
### 格式化函数适配器
|
||||||
|
|
||||||
|
#### excel.AdaptTimeFormatter(fn func(time.Time, ...string) string) func(interface{}) string
|
||||||
|
|
||||||
|
适配器函数:将tools包的格式化函数转换为Excel Format字段需要的函数类型。
|
||||||
|
|
||||||
|
**参数:**
|
||||||
|
- `fn`: tools包的格式化函数(如 `tools.FormatDate`、`tools.FormatDateTime` 等)
|
||||||
|
|
||||||
|
**返回:** Excel Format字段需要的格式化函数
|
||||||
|
|
||||||
|
**说明:**
|
||||||
|
- 允许直接使用tools包的任何格式化函数
|
||||||
|
- 推荐使用此适配器,避免重复实现格式化逻辑
|
||||||
|
- 与factory中的FormatDateTime等方法保持一致
|
||||||
|
|
||||||
|
**示例:**
|
||||||
|
```go
|
||||||
|
import (
|
||||||
|
"git.toowon.com/jimmy/go-common/excel"
|
||||||
|
"git.toowon.com/jimmy/go-common/tools"
|
||||||
|
)
|
||||||
|
|
||||||
|
// 使用tools.FormatDate
|
||||||
|
Format: excel.AdaptTimeFormatter(tools.FormatDate)
|
||||||
|
|
||||||
|
// 使用tools.FormatDateTime
|
||||||
|
Format: excel.AdaptTimeFormatter(tools.FormatDateTime)
|
||||||
|
|
||||||
|
// 使用tools.FormatTime
|
||||||
|
Format: excel.AdaptTimeFormatter(tools.FormatTime)
|
||||||
|
|
||||||
|
// 使用自定义格式化函数
|
||||||
|
Format: excel.AdaptTimeFormatter(func(t time.Time) string {
|
||||||
|
return tools.Format(t, "2006-01-02 15:04:05", "Asia/Shanghai")
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
### ExportData接口
|
||||||
|
|
||||||
|
实现此接口的结构体可以直接导出。
|
||||||
|
|
||||||
|
```go
|
||||||
|
type ExportData interface {
|
||||||
|
// GetExportColumns 获取导出列定义
|
||||||
|
GetExportColumns() []ExportColumn
|
||||||
|
// GetExportRows 获取导出数据行
|
||||||
|
GetExportRows() [][]interface{}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## 完整示例
|
||||||
|
|
||||||
|
```go
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"git.toowon.com/jimmy/go-common/excel"
|
||||||
|
"git.toowon.com/jimmy/go-common/factory"
|
||||||
|
)
|
||||||
|
|
||||||
|
type User struct {
|
||||||
|
ID int `json:"id"`
|
||||||
|
Name string `json:"name"`
|
||||||
|
Email string `json:"email"`
|
||||||
|
CreatedAt time.Time `json:"created_at"`
|
||||||
|
Status int `json:"status"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func exportUsersHandler(w http.ResponseWriter, r *http.Request) {
|
||||||
|
fac, _ := factory.NewFactoryFromFile("./config.json")
|
||||||
|
|
||||||
|
// 从数据库或其他数据源获取数据
|
||||||
|
users := []User{
|
||||||
|
{ID: 1, Name: "Alice", Email: "alice@example.com", CreatedAt: time.Now(), Status: 1},
|
||||||
|
{ID: 2, Name: "Bob", Email: "bob@example.com", CreatedAt: time.Now(), Status: 1},
|
||||||
|
}
|
||||||
|
|
||||||
|
// 定义导出列
|
||||||
|
columns := []factory.ExportColumn{
|
||||||
|
{Header: "ID", Field: "ID", Width: 10},
|
||||||
|
{Header: "姓名", Field: "Name", Width: 20},
|
||||||
|
{Header: "邮箱", Field: "Email", Width: 30},
|
||||||
|
{
|
||||||
|
Header: "创建时间",
|
||||||
|
Field: "CreatedAt",
|
||||||
|
Width: 20,
|
||||||
|
Format: excel.AdaptTimeFormatter(tools.FormatDateTime),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Header: "状态",
|
||||||
|
Field: "Status",
|
||||||
|
Width: 10,
|
||||||
|
Format: func(value interface{}) string {
|
||||||
|
if status, ok := value.(int); ok {
|
||||||
|
if status == 1 {
|
||||||
|
return "启用"
|
||||||
|
}
|
||||||
|
return "禁用"
|
||||||
|
}
|
||||||
|
return ""
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
// 设置HTTP响应头
|
||||||
|
w.Header().Set("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
|
||||||
|
w.Header().Set("Content-Disposition", "attachment; filename=users.xlsx")
|
||||||
|
|
||||||
|
// 导出到响应
|
||||||
|
err := fac.ExportToExcel(w, "用户列表", columns, users)
|
||||||
|
if err != nil {
|
||||||
|
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
http.HandleFunc("/export/users", exportUsersHandler)
|
||||||
|
http.ListenAndServe(":8080", nil)
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## 设计优势
|
||||||
|
|
||||||
|
### 优势总结
|
||||||
|
|
||||||
|
1. **降低复杂度**:调用方无需关心Excel文件对象的创建和管理
|
||||||
|
2. **延迟初始化**:Excel导出器在首次使用时才创建,提高性能
|
||||||
|
3. **统一接口**:所有操作通过工厂方法调用,接口统一
|
||||||
|
4. **灵活扩展**:支持结构体切片、自定义格式化、ExportData接口等多种方式
|
||||||
|
5. **自动优化**:自动调整列宽、应用表头样式等
|
||||||
|
|
||||||
|
## 注意事项
|
||||||
|
|
||||||
|
1. **配置检查**:Excel导出不需要配置,可以传nil创建工厂
|
||||||
|
2. **错误处理**:所有方法都可能返回错误,需要正确处理
|
||||||
|
3. **延迟初始化**:Excel导出器在首次使用时才创建,首次调用可能稍慢
|
||||||
|
4. **字段名匹配**:Field字段名必须与结构体字段名匹配(区分大小写)
|
||||||
|
5. **嵌套字段**:支持嵌套字段访问(如 "User.Name"),但需要确保字段路径正确
|
||||||
|
6. **格式化函数**:格式化函数返回的字符串会直接写入Excel单元格
|
||||||
|
7. **列宽设置**:Width为0时会自动调整列宽,但可能影响性能(大数据量时建议设置固定宽度)
|
||||||
|
8. **工作表处理**:
|
||||||
|
- 使用默认"Sheet1"时,会直接使用默认工作表,不会产生空sheet
|
||||||
|
- 使用自定义工作表名称时,会自动删除默认的"Sheet1",确保文件只有一个工作表
|
||||||
|
- 如果指定的工作表已存在,会直接使用,不会重复创建
|
||||||
|
|
||||||
|
## 最佳实践
|
||||||
|
|
||||||
|
1. **使用黑盒方法**:推荐使用 `ExportToExcel()` 和 `ExportToExcelFile()`,无需获取Excel对象
|
||||||
|
2. **设置列宽**:对于大数据量,建议设置固定列宽以提高性能
|
||||||
|
3. **使用格式化函数**:对于日期时间、状态等字段,使用格式化函数提高可读性
|
||||||
|
4. **错误处理**:始终检查导出方法的返回值
|
||||||
|
5. **HTTP响应**:导出到HTTP响应时,记得设置正确的Content-Type和Content-Disposition头
|
||||||
|
6. **工作表命名**:
|
||||||
|
- 推荐使用有意义的工作表名称(如"用户列表"、"订单数据"等),提高可读性
|
||||||
|
- 如果不指定工作表名称,会使用默认的"Sheet1"
|
||||||
|
- 工具会自动处理工作表的创建和删除,确保不会产生空sheet
|
||||||
|
|
||||||
|
## 示例
|
||||||
|
|
||||||
|
完整示例请参考 `examples/excel_example.go`
|
||||||
|
|
||||||
207
docs/factory.md
207
docs/factory.md
@@ -26,13 +26,14 @@
|
|||||||
| **邮件** | `SendEmail()` | `fac.SendEmail(to, subject, body)` |
|
| **邮件** | `SendEmail()` | `fac.SendEmail(to, subject, body)` |
|
||||||
| **短信** | `SendSMS()` | `fac.SendSMS(phones, params)` |
|
| **短信** | `SendSMS()` | `fac.SendSMS(phones, params)` |
|
||||||
| **存储** | `UploadFile()`, `GetFileURL()` | `fac.UploadFile(ctx, key, file)` |
|
| **存储** | `UploadFile()`, `GetFileURL()` | `fac.UploadFile(ctx, key, file)` |
|
||||||
|
| **Excel导出** | `ExportToExcel()`, `ExportToExcelFile()` | `fac.ExportToExcelFile("users.xlsx", "用户列表", columns, users)` |
|
||||||
| **日期时间** | `Now()`, `ParseDateTime()`, `FormatDateTime()` 等 | `fac.Now("Asia/Shanghai")` |
|
| **日期时间** | `Now()`, `ParseDateTime()`, `FormatDateTime()` 等 | `fac.Now("Asia/Shanghai")` |
|
||||||
| **时间工具** | `GetTimestamp()`, `IsToday()`, `GetBeginOfWeek()` 等 | `fac.GetTimestamp()` |
|
| **时间工具** | `GetTimestamp()`, `IsToday()`, `GetBeginOfWeek()` 等 | `fac.GetTimestamp()` |
|
||||||
| **加密工具** | `HashPassword()`, `MD5()`, `SHA256()`, `GenerateSMSCode()` 等 | `fac.HashPassword("password")` |
|
| **加密工具** | `HashPassword()`, `MD5()`, `SHA256()`, `GenerateSMSCode()` 等 | `fac.HashPassword("password")` |
|
||||||
| **金额计算** | `YuanToCents()`, `CentsToYuan()`, `FormatYuan()` | `fac.YuanToCents(100.5)` |
|
| **金额计算** | `YuanToCents()`, `CentsToYuan()`, `FormatYuan()` | `fac.YuanToCents(100.5)` |
|
||||||
| **版本信息** | `GetVersion()` | `fac.GetVersion()` |
|
| **版本信息** | `GetVersion()` | `fac.GetVersion()` |
|
||||||
| **HTTP响应** | `Success()`, `Error()`, `SuccessPage()` | `fac.Success(w, data)` |
|
| **HTTP响应** | `Success()`, `Error()`, `SuccessPage()` | `fac.Success(w, data)` |
|
||||||
| **HTTP请求** | `ParseJSON()`, `GetQuery()`, `GetTimezone()` 等 | `fac.ParseJSON(r, &req)` |
|
| **HTTP请求** | `ParseJSON()`, `ConvertInt()`, `GetTimezone()` 等 | `fac.ParseJSON(r, &req)` |
|
||||||
|
|
||||||
### 🔧 高级功能:Get方法(仅在必要时使用)
|
### 🔧 高级功能:Get方法(仅在必要时使用)
|
||||||
|
|
||||||
@@ -42,6 +43,7 @@
|
|||||||
|------|----------|----------|
|
|------|----------|----------|
|
||||||
| `GetDatabase()` | `*gorm.DB` | 数据库复杂查询、事务、关联查询等 |
|
| `GetDatabase()` | `*gorm.DB` | 数据库复杂查询、事务、关联查询等 |
|
||||||
| `GetRedisClient()` | `*redis.Client` | Hash、List、Set、ZSet、Pub/Sub等高级操作 |
|
| `GetRedisClient()` | `*redis.Client` | Hash、List、Set、ZSet、Pub/Sub等高级操作 |
|
||||||
|
| `GetExcel()` | `*excel.Excel` | 多工作表、自定义样式、图表等高级操作 |
|
||||||
| `GetLogger()` | `*logger.Logger` | Close()、设置全局logger等 |
|
| `GetLogger()` | `*logger.Logger` | Close()、设置全局logger等 |
|
||||||
|
|
||||||
## 使用方法
|
## 使用方法
|
||||||
@@ -145,7 +147,54 @@ url, _ := fac.GetFileURL("images/test.jpg", 0)
|
|||||||
url, _ := fac.GetFileURL("images/test.jpg", 3600)
|
url, _ := fac.GetFileURL("images/test.jpg", 3600)
|
||||||
```
|
```
|
||||||
|
|
||||||
### 6. Redis操作(黑盒模式,推荐)
|
### 6. Excel导出(黑盒模式,推荐)
|
||||||
|
|
||||||
|
```go
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
"time"
|
||||||
|
"git.toowon.com/jimmy/go-common/excel"
|
||||||
|
)
|
||||||
|
|
||||||
|
// 定义结构体
|
||||||
|
type User struct {
|
||||||
|
ID int `json:"id"`
|
||||||
|
Name string `json:"name"`
|
||||||
|
Email string `json:"email"`
|
||||||
|
CreatedAt time.Time `json:"created_at"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// 准备数据
|
||||||
|
users := []User{
|
||||||
|
{ID: 1, Name: "Alice", Email: "alice@example.com", CreatedAt: time.Now()},
|
||||||
|
{ID: 2, Name: "Bob", Email: "bob@example.com", CreatedAt: time.Now()},
|
||||||
|
}
|
||||||
|
|
||||||
|
// 定义导出列
|
||||||
|
columns := []factory.ExportColumn{
|
||||||
|
{Header: "ID", Field: "ID", Width: 10},
|
||||||
|
{Header: "姓名", Field: "Name", Width: 20},
|
||||||
|
{Header: "邮箱", Field: "Email", Width: 30},
|
||||||
|
{
|
||||||
|
Header: "创建时间",
|
||||||
|
Field: "CreatedAt",
|
||||||
|
Width: 20,
|
||||||
|
Format: excel.AdaptTimeFormatter(tools.FormatDateTime),
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
// 导出到文件
|
||||||
|
err := fac.ExportToExcelFile("users.xlsx", "用户列表", columns, users)
|
||||||
|
|
||||||
|
// 导出到HTTP响应
|
||||||
|
func exportUsersHandler(w http.ResponseWriter, r *http.Request) {
|
||||||
|
w.Header().Set("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
|
||||||
|
w.Header().Set("Content-Disposition", "attachment; filename=users.xlsx")
|
||||||
|
fac.ExportToExcel(w, "用户列表", columns, users)
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 7. Redis操作(黑盒模式,推荐)
|
||||||
|
|
||||||
```go
|
```go
|
||||||
import "context"
|
import "context"
|
||||||
@@ -168,7 +217,7 @@ err := fac.RedisDelete(ctx, "user:123", "user:456")
|
|||||||
exists, err := fac.RedisExists(ctx, "user:123")
|
exists, err := fac.RedisExists(ctx, "user:123")
|
||||||
```
|
```
|
||||||
|
|
||||||
### 7. 数据库操作(黑盒模式)
|
### 8. 数据库操作(黑盒模式)
|
||||||
|
|
||||||
```go
|
```go
|
||||||
// 获取数据库对象(已初始化,黑盒模式)
|
// 获取数据库对象(已初始化,黑盒模式)
|
||||||
@@ -183,7 +232,7 @@ db.Find(&users)
|
|||||||
db.Create(&user)
|
db.Create(&user)
|
||||||
```
|
```
|
||||||
|
|
||||||
### 8. 日期时间操作(黑盒模式)
|
### 9. 日期时间操作(黑盒模式)
|
||||||
|
|
||||||
```go
|
```go
|
||||||
// 获取当前时间
|
// 获取当前时间
|
||||||
@@ -205,7 +254,7 @@ unix := fac.ToUnix(now)
|
|||||||
t2 := fac.FromUnix(unix, "Asia/Shanghai")
|
t2 := fac.FromUnix(unix, "Asia/Shanghai")
|
||||||
```
|
```
|
||||||
|
|
||||||
### 9. 时间操作(黑盒模式)
|
### 10. 时间操作(黑盒模式)
|
||||||
|
|
||||||
```go
|
```go
|
||||||
// 时间戳
|
// 时间戳
|
||||||
@@ -240,7 +289,7 @@ timeInfo := fac.GenerateTimeInfoWithTimezone(now, "Asia/Shanghai")
|
|||||||
fmt.Printf("UTC: %s, Local: %s, Unix: %d\n", timeInfo.UTC, timeInfo.Local, timeInfo.Unix)
|
fmt.Printf("UTC: %s, Local: %s, Unix: %d\n", timeInfo.UTC, timeInfo.Local, timeInfo.Unix)
|
||||||
```
|
```
|
||||||
|
|
||||||
### 10. 金额计算(黑盒模式)
|
### 11. 金额计算(黑盒模式)
|
||||||
|
|
||||||
```go
|
```go
|
||||||
// 元转分
|
// 元转分
|
||||||
@@ -260,7 +309,7 @@ version := fac.GetVersion()
|
|||||||
fmt.Println("当前版本:", version)
|
fmt.Println("当前版本:", version)
|
||||||
```
|
```
|
||||||
|
|
||||||
### 13. HTTP响应(黑盒模式)
|
### 13. HTTP响应(黑盒模式,推荐)
|
||||||
|
|
||||||
```go
|
```go
|
||||||
import "net/http"
|
import "net/http"
|
||||||
@@ -277,7 +326,7 @@ fac.Error(w, 1001, "用户不存在")
|
|||||||
fac.SystemError(w, "系统错误")
|
fac.SystemError(w, "系统错误")
|
||||||
```
|
```
|
||||||
|
|
||||||
### 14. HTTP请求解析(黑盒模式)
|
### 14. HTTP请求解析(黑盒模式,推荐)
|
||||||
|
|
||||||
```go
|
```go
|
||||||
import "net/http"
|
import "net/http"
|
||||||
@@ -286,15 +335,21 @@ import "net/http"
|
|||||||
var req UserRequest
|
var req UserRequest
|
||||||
fac.ParseJSON(r, &req)
|
fac.ParseJSON(r, &req)
|
||||||
|
|
||||||
// 获取查询参数
|
// 获取查询参数(使用类型转换方法)
|
||||||
id := fac.GetQueryInt64(r, "id", 0)
|
id := fac.ConvertInt64(r.URL.Query().Get("id"), 0)
|
||||||
keyword := fac.GetQuery(r, "keyword", "")
|
uid := fac.ConvertUint64(r.URL.Query().Get("uid"), 0)
|
||||||
|
userId := fac.ConvertUint32(r.URL.Query().Get("user_id"), 0)
|
||||||
|
keyword := r.URL.Query().Get("keyword") // 字符串直接获取
|
||||||
|
|
||||||
|
// 获取表单参数
|
||||||
|
age := fac.ConvertInt(r.FormValue("age"), 0)
|
||||||
|
isActive := fac.ConvertBool(r.FormValue("is_active"), false)
|
||||||
|
|
||||||
// 获取时区(需要配合middleware.Timezone使用)
|
// 获取时区(需要配合middleware.Timezone使用)
|
||||||
timezone := fac.GetTimezone(r)
|
timezone := fac.GetTimezone(r)
|
||||||
```
|
```
|
||||||
|
|
||||||
### 15. Redis操作(获取客户端对象)
|
### 15. Redis操作(获取客户端对象,高级功能)
|
||||||
|
|
||||||
```go
|
```go
|
||||||
import (
|
import (
|
||||||
@@ -519,6 +574,54 @@ func main() {
|
|||||||
|
|
||||||
**返回:** 文件访问URL和错误信息
|
**返回:** 文件访问URL和错误信息
|
||||||
|
|
||||||
|
### Excel导出方法(黑盒模式)
|
||||||
|
|
||||||
|
#### ExportToExcel(w io.Writer, sheetName string, columns []ExportColumn, data interface{}) error
|
||||||
|
|
||||||
|
导出数据到Writer。
|
||||||
|
|
||||||
|
**参数:**
|
||||||
|
- `w`: Writer对象(如http.ResponseWriter)
|
||||||
|
- `sheetName`: 工作表名称(可选,默认为"Sheet1")
|
||||||
|
- `columns`: 列定义
|
||||||
|
- `data`: 数据列表(可以是结构体切片或实现了ExportData接口的对象)
|
||||||
|
|
||||||
|
**返回:** 错误信息
|
||||||
|
|
||||||
|
**示例:**
|
||||||
|
```go
|
||||||
|
fac.ExportToExcel(w, "用户列表", columns, users)
|
||||||
|
```
|
||||||
|
|
||||||
|
#### ExportToExcelFile(filePath string, sheetName string, columns []ExportColumn, data interface{}) error
|
||||||
|
|
||||||
|
导出数据到文件。
|
||||||
|
|
||||||
|
**参数:**
|
||||||
|
- `filePath`: 文件路径
|
||||||
|
- `sheetName`: 工作表名称(可选,默认为"Sheet1")
|
||||||
|
- `columns`: 列定义
|
||||||
|
- `data`: 数据列表
|
||||||
|
|
||||||
|
**返回:** 错误信息
|
||||||
|
|
||||||
|
**示例:**
|
||||||
|
```go
|
||||||
|
fac.ExportToExcelFile("users.xlsx", "用户列表", columns, users)
|
||||||
|
```
|
||||||
|
|
||||||
|
#### GetExcel() (*excel.Excel, error)
|
||||||
|
|
||||||
|
获取Excel导出器对象(高级功能时使用)。
|
||||||
|
|
||||||
|
**返回:** Excel导出器对象和错误信息
|
||||||
|
|
||||||
|
**说明:**
|
||||||
|
- 仅在需要使用高级功能时使用
|
||||||
|
- 推荐使用黑盒方法:`ExportToExcel()`、`ExportToExcelFile()`
|
||||||
|
|
||||||
|
**详细说明请参考:[Excel导出工具文档](./excel.md)**
|
||||||
|
|
||||||
### Redis方法(黑盒模式)
|
### Redis方法(黑盒模式)
|
||||||
|
|
||||||
#### RedisGet(ctx context.Context, key string) (string, error)
|
#### RedisGet(ctx context.Context, key string) (string, error)
|
||||||
@@ -655,26 +758,74 @@ fac.Success(w, user, "获取成功") // 自定义消息
|
|||||||
- `r`: HTTP请求
|
- `r`: HTTP请求
|
||||||
- `v`: 目标结构体指针
|
- `v`: 目标结构体指针
|
||||||
|
|
||||||
#### GetQuery(r *http.Request, key, defaultValue string) string
|
|
||||||
|
|
||||||
获取查询参数。
|
|
||||||
|
|
||||||
#### GetQueryInt(r *http.Request, key string, defaultValue int) int
|
|
||||||
|
|
||||||
获取查询整数参数。
|
|
||||||
|
|
||||||
#### GetQueryInt64(r *http.Request, key string, defaultValue int64) int64
|
|
||||||
|
|
||||||
获取查询64位整数参数。
|
|
||||||
|
|
||||||
#### GetFormValue(r *http.Request, key, defaultValue string) string
|
|
||||||
|
|
||||||
获取表单值。
|
|
||||||
|
|
||||||
#### GetTimezone(r *http.Request) string
|
#### GetTimezone(r *http.Request) string
|
||||||
|
|
||||||
从请求的context中获取时区(需要配合middleware.Timezone使用)。
|
从请求的context中获取时区(需要配合middleware.Timezone使用)。
|
||||||
|
|
||||||
|
### 类型转换方法(黑盒模式)
|
||||||
|
|
||||||
|
#### ConvertInt(value string, defaultValue int) int
|
||||||
|
|
||||||
|
将字符串转换为int类型。
|
||||||
|
|
||||||
|
**参数:**
|
||||||
|
- `value`: 待转换的字符串
|
||||||
|
- `defaultValue`: 转换失败或字符串为空时返回的默认值
|
||||||
|
|
||||||
|
**示例:**
|
||||||
|
```go
|
||||||
|
// 从查询参数获取整数
|
||||||
|
id := fac.ConvertInt(r.URL.Query().Get("id"), 0)
|
||||||
|
|
||||||
|
// 从表单获取整数
|
||||||
|
age := fac.ConvertInt(r.FormValue("age"), 0)
|
||||||
|
```
|
||||||
|
|
||||||
|
#### ConvertInt64(value string, defaultValue int64) int64
|
||||||
|
|
||||||
|
将字符串转换为int64类型。
|
||||||
|
|
||||||
|
**示例:**
|
||||||
|
```go
|
||||||
|
id := fac.ConvertInt64(r.URL.Query().Get("id"), 0)
|
||||||
|
```
|
||||||
|
|
||||||
|
#### ConvertUint64(value string, defaultValue uint64) uint64
|
||||||
|
|
||||||
|
将字符串转换为uint64类型。
|
||||||
|
|
||||||
|
**示例:**
|
||||||
|
```go
|
||||||
|
uid := fac.ConvertUint64(r.URL.Query().Get("uid"), 0)
|
||||||
|
```
|
||||||
|
|
||||||
|
#### ConvertUint32(value string, defaultValue uint32) uint32
|
||||||
|
|
||||||
|
将字符串转换为uint32类型。
|
||||||
|
|
||||||
|
**示例:**
|
||||||
|
```go
|
||||||
|
userId := fac.ConvertUint32(r.URL.Query().Get("user_id"), 0)
|
||||||
|
```
|
||||||
|
|
||||||
|
#### ConvertBool(value string, defaultValue bool) bool
|
||||||
|
|
||||||
|
将字符串转换为bool类型。
|
||||||
|
|
||||||
|
**示例:**
|
||||||
|
```go
|
||||||
|
isActive := fac.ConvertBool(r.URL.Query().Get("is_active"), false)
|
||||||
|
```
|
||||||
|
|
||||||
|
#### ConvertFloat64(value string, defaultValue float64) float64
|
||||||
|
|
||||||
|
将字符串转换为float64类型。
|
||||||
|
|
||||||
|
**示例:**
|
||||||
|
```go
|
||||||
|
price := fac.ConvertFloat64(r.URL.Query().Get("price"), 0.0)
|
||||||
|
```
|
||||||
|
|
||||||
### 日期时间工具方法(黑盒模式)
|
### 日期时间工具方法(黑盒模式)
|
||||||
|
|
||||||
#### Now(timezone ...string) time.Time
|
#### Now(timezone ...string) time.Time
|
||||||
|
|||||||
133
docs/http.md
133
docs/http.md
@@ -111,13 +111,14 @@ import (
|
|||||||
"net/http"
|
"net/http"
|
||||||
"git.toowon.com/jimmy/go-common/factory"
|
"git.toowon.com/jimmy/go-common/factory"
|
||||||
commonhttp "git.toowon.com/jimmy/go-common/http"
|
commonhttp "git.toowon.com/jimmy/go-common/http"
|
||||||
|
"git.toowon.com/jimmy/go-common/tools"
|
||||||
)
|
)
|
||||||
|
|
||||||
func GetUser(w http.ResponseWriter, r *http.Request) {
|
func GetUser(w http.ResponseWriter, r *http.Request) {
|
||||||
fac, _ := factory.NewFactoryFromFile("config.json")
|
fac, _ := factory.NewFactoryFromFile("config.json")
|
||||||
|
|
||||||
// 获取查询参数(使用公共方法)
|
// 获取查询参数(使用类型转换方法)
|
||||||
id := commonhttp.GetQueryInt64(r, "id", 0)
|
id := tools.ConvertInt64(r.URL.Query().Get("id"), 0)
|
||||||
|
|
||||||
// 返回成功响应(使用factory方法)
|
// 返回成功响应(使用factory方法)
|
||||||
fac.Success(w, data)
|
fac.Success(w, data)
|
||||||
@@ -145,10 +146,10 @@ func GetUserList(w http.ResponseWriter, r *http.Request) {
|
|||||||
// 获取分页参数(使用factory方法,推荐)
|
// 获取分页参数(使用factory方法,推荐)
|
||||||
pagination := fac.ParsePaginationRequest(r)
|
pagination := fac.ParsePaginationRequest(r)
|
||||||
page := pagination.GetPage()
|
page := pagination.GetPage()
|
||||||
pageSize := pagination.GetSize()
|
pageSize := pagination.GetPageSize()
|
||||||
|
|
||||||
// 获取查询参数(使用factory方法,推荐)
|
// 获取查询参数(直接使用HTTP原生方法)
|
||||||
keyword := fac.GetQuery(r, "keyword", "")
|
keyword := r.URL.Query().Get("keyword")
|
||||||
|
|
||||||
// 查询数据
|
// 查询数据
|
||||||
list, total := getDataList(keyword, page, pageSize)
|
list, total := getDataList(keyword, page, pageSize)
|
||||||
@@ -170,11 +171,12 @@ http.HandleFunc("/users", GetUserList)
|
|||||||
import (
|
import (
|
||||||
"net/http"
|
"net/http"
|
||||||
commonhttp "git.toowon.com/jimmy/go-common/http"
|
commonhttp "git.toowon.com/jimmy/go-common/http"
|
||||||
|
"git.toowon.com/jimmy/go-common/tools"
|
||||||
)
|
)
|
||||||
|
|
||||||
func GetUser(w http.ResponseWriter, r *http.Request) {
|
func GetUser(w http.ResponseWriter, r *http.Request) {
|
||||||
// 获取查询参数
|
// 获取查询参数
|
||||||
id := commonhttp.GetQueryInt64(r, "id", 0)
|
id := tools.ConvertInt64(r.URL.Query().Get("id"), 0)
|
||||||
|
|
||||||
// 返回成功响应
|
// 返回成功响应
|
||||||
commonhttp.Success(w, data)
|
commonhttp.Success(w, data)
|
||||||
@@ -252,30 +254,41 @@ if err := commonhttp.ParseJSON(r, &req); err != nil {
|
|||||||
#### 获取查询参数
|
#### 获取查询参数
|
||||||
|
|
||||||
```go
|
```go
|
||||||
// 使用公共方法
|
import "git.toowon.com/jimmy/go-common/tools"
|
||||||
name := commonhttp.GetQuery(r, "name", "")
|
|
||||||
id := commonhttp.GetQueryInt(r, "id", 0)
|
// 字符串直接获取
|
||||||
userId := commonhttp.GetQueryInt64(r, "userId", 0)
|
name := r.URL.Query().Get("name")
|
||||||
isActive := commonhttp.GetQueryBool(r, "isActive", false)
|
|
||||||
price := commonhttp.GetQueryFloat64(r, "price", 0.0)
|
// 使用类型转换方法
|
||||||
|
id := tools.ConvertInt(r.URL.Query().Get("id"), 0)
|
||||||
|
userId := tools.ConvertInt64(r.URL.Query().Get("userId"), 0)
|
||||||
|
isActive := tools.ConvertBool(r.URL.Query().Get("isActive"), false)
|
||||||
|
price := tools.ConvertFloat64(r.URL.Query().Get("price"), 0.0)
|
||||||
```
|
```
|
||||||
|
|
||||||
#### 获取表单参数
|
#### 获取表单参数
|
||||||
|
|
||||||
```go
|
```go
|
||||||
// 使用公共方法
|
import "git.toowon.com/jimmy/go-common/tools"
|
||||||
name := commonhttp.GetFormValue(r, "name", "")
|
|
||||||
age := commonhttp.GetFormInt(r, "age", 0)
|
// 字符串直接获取
|
||||||
userId := commonhttp.GetFormInt64(r, "userId", 0)
|
name := r.FormValue("name")
|
||||||
isActive := commonhttp.GetFormBool(r, "isActive", false)
|
|
||||||
|
// 使用类型转换方法
|
||||||
|
age := tools.ConvertInt(r.FormValue("age"), 0)
|
||||||
|
userId := tools.ConvertInt64(r.FormValue("userId"), 0)
|
||||||
|
isActive := tools.ConvertBool(r.FormValue("isActive"), false)
|
||||||
```
|
```
|
||||||
|
|
||||||
#### 获取请求头
|
#### 获取请求头
|
||||||
|
|
||||||
```go
|
```go
|
||||||
// 使用公共方法
|
// 直接使用HTTP原生方法
|
||||||
token := commonhttp.GetHeader(r, "Authorization", "")
|
token := r.Header.Get("Authorization")
|
||||||
contentType := commonhttp.GetHeader(r, "Content-Type", "application/json")
|
contentType := r.Header.Get("Content-Type")
|
||||||
|
if contentType == "" {
|
||||||
|
contentType = "application/json" // 设置默认值
|
||||||
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
#### 获取分页参数
|
#### 获取分页参数
|
||||||
@@ -298,7 +311,7 @@ if err := commonhttp.ParseJSON(r, &req); err != nil {
|
|||||||
|
|
||||||
// 使用分页方法
|
// 使用分页方法
|
||||||
page := req.GetPage() // 获取页码(默认1)
|
page := req.GetPage() // 获取页码(默认1)
|
||||||
size := req.GetSize() // 获取每页数量(默认20,最大100,优先使用page_size)
|
pageSize := req.GetPageSize() // 获取每页数量(默认20,最大100)
|
||||||
offset := req.GetOffset() // 计算偏移量
|
offset := req.GetOffset() // 计算偏移量
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -308,7 +321,7 @@ offset := req.GetOffset() // 计算偏移量
|
|||||||
// 使用公共方法
|
// 使用公共方法
|
||||||
pagination := commonhttp.ParsePaginationRequest(r)
|
pagination := commonhttp.ParsePaginationRequest(r)
|
||||||
page := pagination.GetPage()
|
page := pagination.GetPage()
|
||||||
size := pagination.GetSize()
|
pageSize := pagination.GetPageSize()
|
||||||
offset := pagination.GetOffset()
|
offset := pagination.GetOffset()
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -333,6 +346,7 @@ import (
|
|||||||
"net/http"
|
"net/http"
|
||||||
"git.toowon.com/jimmy/go-common/factory"
|
"git.toowon.com/jimmy/go-common/factory"
|
||||||
commonhttp "git.toowon.com/jimmy/go-common/http"
|
commonhttp "git.toowon.com/jimmy/go-common/http"
|
||||||
|
"git.toowon.com/jimmy/go-common/tools"
|
||||||
)
|
)
|
||||||
|
|
||||||
// 用户结构
|
// 用户结构
|
||||||
@@ -349,10 +363,10 @@ func GetUserList(w http.ResponseWriter, r *http.Request) {
|
|||||||
// 获取分页参数(使用公共方法)
|
// 获取分页参数(使用公共方法)
|
||||||
pagination := commonhttp.ParsePaginationRequest(r)
|
pagination := commonhttp.ParsePaginationRequest(r)
|
||||||
page := pagination.GetPage()
|
page := pagination.GetPage()
|
||||||
pageSize := pagination.GetSize()
|
pageSize := pagination.GetPageSize()
|
||||||
|
|
||||||
// 获取查询参数(使用公共方法)
|
// 获取查询参数(直接使用HTTP原生方法)
|
||||||
keyword := commonhttp.GetQuery(r, "keyword", "")
|
keyword := r.URL.Query().Get("keyword")
|
||||||
|
|
||||||
// 查询数据
|
// 查询数据
|
||||||
users, total := queryUsers(keyword, page, pageSize)
|
users, total := queryUsers(keyword, page, pageSize)
|
||||||
@@ -397,8 +411,8 @@ func CreateUser(w http.ResponseWriter, r *http.Request) {
|
|||||||
func GetUser(w http.ResponseWriter, r *http.Request) {
|
func GetUser(w http.ResponseWriter, r *http.Request) {
|
||||||
fac, _ := factory.NewFactoryFromFile("config.json")
|
fac, _ := factory.NewFactoryFromFile("config.json")
|
||||||
|
|
||||||
// 获取查询参数(使用factory方法,推荐)
|
// 获取查询参数(使用类型转换方法)
|
||||||
id := fac.GetQueryInt64(r, "id", 0)
|
id := tools.ConvertInt64(r.URL.Query().Get("id"), 0)
|
||||||
|
|
||||||
if id == 0 {
|
if id == 0 {
|
||||||
commonhttp.WriteJSON(w, http.StatusBadRequest, 400, "用户ID不能为空", nil)
|
commonhttp.WriteJSON(w, http.StatusBadRequest, 400, "用户ID不能为空", nil)
|
||||||
@@ -593,45 +607,45 @@ if err := commonhttp.ParseJSON(r, &req); err != nil {
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
#### GetQuery(r *http.Request, key, defaultValue string) string
|
#### 获取查询参数和表单参数
|
||||||
|
|
||||||
获取查询参数(字符串)。
|
**推荐方式:使用类型转换工具**
|
||||||
|
|
||||||
#### GetQueryInt(r *http.Request, key string, defaultValue int) int
|
```go
|
||||||
|
import "git.toowon.com/jimmy/go-common/tools"
|
||||||
|
|
||||||
获取查询参数(整数)。
|
// 字符串直接使用HTTP原生方法
|
||||||
|
name := r.URL.Query().Get("name")
|
||||||
|
if name == "" {
|
||||||
|
name = "default" // 设置默认值
|
||||||
|
}
|
||||||
|
|
||||||
#### GetQueryInt64(r *http.Request, key string, defaultValue int64) int64
|
// 类型转换使用tools包
|
||||||
|
id := tools.ConvertInt(r.URL.Query().Get("id"), 0)
|
||||||
|
userId := tools.ConvertInt64(r.URL.Query().Get("userId"), 0)
|
||||||
|
isActive := tools.ConvertBool(r.URL.Query().Get("isActive"), false)
|
||||||
|
price := tools.ConvertFloat64(r.URL.Query().Get("price"), 0.0)
|
||||||
|
|
||||||
获取查询参数(int64)。
|
// 表单参数类似
|
||||||
|
age := tools.ConvertInt(r.FormValue("age"), 0)
|
||||||
|
```
|
||||||
|
|
||||||
#### GetQueryBool(r *http.Request, key string, defaultValue bool) bool
|
**类型转换方法说明:**
|
||||||
|
|
||||||
获取查询参数(布尔值)。
|
- `tools.ConvertInt(value string, defaultValue int) int` - 转换为int
|
||||||
|
- `tools.ConvertInt64(value string, defaultValue int64) int64` - 转换为int64
|
||||||
|
- `tools.ConvertUint64(value string, defaultValue uint64) uint64` - 转换为uint64
|
||||||
|
- `tools.ConvertUint32(value string, defaultValue uint32) uint32` - 转换为uint32
|
||||||
|
- `tools.ConvertBool(value string, defaultValue bool) bool` - 转换为bool
|
||||||
|
- `tools.ConvertFloat64(value string, defaultValue float64) float64` - 转换为float64
|
||||||
|
|
||||||
#### GetQueryFloat64(r *http.Request, key string, defaultValue float64) float64
|
**获取请求头:**
|
||||||
|
|
||||||
获取查询参数(浮点数)。
|
```go
|
||||||
|
// 直接使用HTTP原生方法
|
||||||
#### GetFormValue(r *http.Request, key, defaultValue string) string
|
token := r.Header.Get("Authorization")
|
||||||
|
contentType := r.Header.Get("Content-Type")
|
||||||
获取表单值(字符串)。
|
```
|
||||||
|
|
||||||
#### 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
|
#### ParsePaginationRequest(r *http.Request) *PaginationRequest
|
||||||
|
|
||||||
@@ -692,12 +706,11 @@ commonhttp.Success(w, data, "操作成功") // 数据+消息
|
|||||||
|
|
||||||
**字段:**
|
**字段:**
|
||||||
- `Page`: 页码(默认1)
|
- `Page`: 页码(默认1)
|
||||||
- `Size`: 每页数量(兼容旧版本)
|
- `PageSize`: 每页数量
|
||||||
- `PageSize`: 每页数量(推荐使用,优先于Size)
|
|
||||||
|
|
||||||
**方法:**
|
**方法:**
|
||||||
- `GetPage() int`: 获取页码,如果未设置则返回默认值1
|
- `GetPage() int`: 获取页码,如果未设置则返回默认值1
|
||||||
- `GetSize() int`: 获取每页数量,优先使用PageSize,如果未设置则使用Size,默认20,最大100
|
- `GetPageSize() int`: 获取每页数量,如果未设置则返回默认值20,最大限制100
|
||||||
- `GetOffset() int`: 计算数据库查询的偏移量
|
- `GetOffset() int`: 计算数据库查询的偏移量
|
||||||
|
|
||||||
#### ParsePaginationRequest(r *http.Request) *PaginationRequest
|
#### ParsePaginationRequest(r *http.Request) *PaginationRequest
|
||||||
|
|||||||
510
docs/i18n.md
Normal file
510
docs/i18n.md
Normal file
@@ -0,0 +1,510 @@
|
|||||||
|
# 国际化工具文档
|
||||||
|
|
||||||
|
## 概述
|
||||||
|
|
||||||
|
国际化工具(i18n)提供多语言内容管理功能,支持从文件加载语言内容,通过语言代码和消息代码获取对应语言的内容。
|
||||||
|
|
||||||
|
## 功能特性
|
||||||
|
|
||||||
|
- **多语言支持**:支持加载多个语言文件
|
||||||
|
- **文件加载**:支持从目录或单个文件加载语言内容
|
||||||
|
- **语言回退**:当指定语言不存在时,自动回退到默认语言
|
||||||
|
- **参数替换**:支持在消息中使用格式化参数(类似 fmt.Sprintf)
|
||||||
|
- **并发安全**:使用读写锁保证并发安全
|
||||||
|
- **动态加载**:支持重新加载语言文件
|
||||||
|
|
||||||
|
## 快速开始
|
||||||
|
|
||||||
|
### 1. 创建语言文件
|
||||||
|
|
||||||
|
创建语言文件目录 `locales/`,并创建对应的语言文件:
|
||||||
|
|
||||||
|
**locales/zh-CN.json**:
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"user.not_found": {
|
||||||
|
"code": 100002,
|
||||||
|
"message": "用户不存在"
|
||||||
|
},
|
||||||
|
"user.login_success": {
|
||||||
|
"code": 0,
|
||||||
|
"message": "登录成功"
|
||||||
|
},
|
||||||
|
"user.welcome": {
|
||||||
|
"code": 0,
|
||||||
|
"message": "欢迎,%s"
|
||||||
|
},
|
||||||
|
"error.invalid_params": {
|
||||||
|
"code": 100001,
|
||||||
|
"message": "参数无效"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**locales/en-US.json**:
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"user.not_found": {
|
||||||
|
"code": 100002,
|
||||||
|
"message": "User not found"
|
||||||
|
},
|
||||||
|
"user.login_success": {
|
||||||
|
"code": 0,
|
||||||
|
"message": "Login successful"
|
||||||
|
},
|
||||||
|
"user.welcome": {
|
||||||
|
"code": 0,
|
||||||
|
"message": "Welcome, %s"
|
||||||
|
},
|
||||||
|
"error.invalid_params": {
|
||||||
|
"code": 100001,
|
||||||
|
"message": "Invalid parameters"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2. 初始化并使用
|
||||||
|
|
||||||
|
```go
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"git.toowon.com/jimmy/go-common/factory"
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
// 创建工厂实例
|
||||||
|
fac, _ := factory.NewFactoryFromFile("config.json")
|
||||||
|
|
||||||
|
// 初始化国际化工具,设置默认语言为中文
|
||||||
|
fac.InitI18n("zh-CN")
|
||||||
|
|
||||||
|
// 从目录加载所有语言文件
|
||||||
|
fac.LoadI18nFromDir("locales")
|
||||||
|
|
||||||
|
// 获取消息
|
||||||
|
msg := fac.GetMessage("zh-CN", "user.not_found")
|
||||||
|
// 返回: "用户不存在"
|
||||||
|
|
||||||
|
// 带参数的消息
|
||||||
|
msg = fac.GetMessage("zh-CN", "user.welcome", "Alice")
|
||||||
|
// 返回: "欢迎,Alice"
|
||||||
|
|
||||||
|
// 在HTTP handler中使用Error方法(推荐)
|
||||||
|
// fac.Error(w, r, 0, "user.not_found")
|
||||||
|
// 会自动从语言文件获取业务code和国际化消息
|
||||||
|
// 返回: {"code": 100002, "message": "用户不存在"}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## API 文档
|
||||||
|
|
||||||
|
### 初始化方法
|
||||||
|
|
||||||
|
#### InitI18n
|
||||||
|
|
||||||
|
初始化国际化工具,设置默认语言。
|
||||||
|
|
||||||
|
```go
|
||||||
|
fac.InitI18n(defaultLang string)
|
||||||
|
```
|
||||||
|
|
||||||
|
**参数**:
|
||||||
|
- `defaultLang`: 默认语言代码(如 "zh-CN", "en-US")
|
||||||
|
|
||||||
|
**示例**:
|
||||||
|
```go
|
||||||
|
fac.InitI18n("zh-CN")
|
||||||
|
```
|
||||||
|
|
||||||
|
### 加载方法
|
||||||
|
|
||||||
|
#### LoadI18nFromDir
|
||||||
|
|
||||||
|
从目录加载多个语言文件(推荐方式)。
|
||||||
|
|
||||||
|
```go
|
||||||
|
fac.LoadI18nFromDir(dirPath string) error
|
||||||
|
```
|
||||||
|
|
||||||
|
**参数**:
|
||||||
|
- `dirPath`: 语言文件目录路径
|
||||||
|
|
||||||
|
**文件命名规则**:
|
||||||
|
- 文件必须以 `.json` 结尾
|
||||||
|
- 文件名(去掉 `.json` 后缀)作为语言代码
|
||||||
|
- 例如:`zh-CN.json` 对应语言代码 `zh-CN`
|
||||||
|
|
||||||
|
**示例**:
|
||||||
|
```go
|
||||||
|
fac.LoadI18nFromDir("locales")
|
||||||
|
```
|
||||||
|
|
||||||
|
#### LoadI18nFromFile
|
||||||
|
|
||||||
|
从单个语言文件加载内容。
|
||||||
|
|
||||||
|
```go
|
||||||
|
fac.LoadI18nFromFile(filePath, lang string) error
|
||||||
|
```
|
||||||
|
|
||||||
|
**参数**:
|
||||||
|
- `filePath`: 语言文件路径(JSON格式)
|
||||||
|
- `lang`: 语言代码(如 "zh-CN", "en-US")
|
||||||
|
|
||||||
|
**示例**:
|
||||||
|
```go
|
||||||
|
fac.LoadI18nFromFile("locales/zh-CN.json", "zh-CN")
|
||||||
|
fac.LoadI18nFromFile("locales/en-US.json", "en-US")
|
||||||
|
```
|
||||||
|
|
||||||
|
### 错误响应方法
|
||||||
|
|
||||||
|
#### Error
|
||||||
|
|
||||||
|
错误响应(自动国际化,推荐使用)。
|
||||||
|
|
||||||
|
```go
|
||||||
|
fac.Error(w, r, code int, message string, args ...interface{})
|
||||||
|
```
|
||||||
|
|
||||||
|
**参数**:
|
||||||
|
- `w`: ResponseWriter
|
||||||
|
- `r`: HTTP请求(用于获取语言信息)
|
||||||
|
- `code`: 业务错误码(如果message是消息代码,此参数会被语言文件中的code覆盖)
|
||||||
|
- `message`: 错误消息或消息代码(如果i18n已初始化且message是消息代码格式,会自动获取国际化消息和业务code)
|
||||||
|
- `args`: 可选参数,用于格式化消息(类似 fmt.Sprintf,仅在message是消息代码时使用)
|
||||||
|
|
||||||
|
**使用逻辑**:
|
||||||
|
1. 如果i18n已初始化,且message看起来是消息代码(包含点号,如 "user.not_found"),
|
||||||
|
则从请求context中获取语言,并尝试从语言文件中获取国际化消息和业务code
|
||||||
|
2. 如果获取到国际化消息,使用语言文件中的code作为响应code,使用国际化消息作为响应message
|
||||||
|
3. 如果未获取到或i18n未初始化,使用传入的code和message
|
||||||
|
|
||||||
|
**示例**:
|
||||||
|
```go
|
||||||
|
// 方式1:传入消息代码(推荐,自动获取业务code和国际化消息)
|
||||||
|
fac.Error(w, r, 0, "user.not_found")
|
||||||
|
// 如果请求语言是 zh-CN,且语言文件中 "user.not_found" 的 code 是 100002,
|
||||||
|
// 返回: {"code": 100002, "message": "用户不存在"}
|
||||||
|
// 如果请求语言是 en-US,返回: {"code": 100002, "message": "User not found"}
|
||||||
|
// 注意:业务code在所有语言中保持一致
|
||||||
|
|
||||||
|
// 方式2:带参数的消息代码
|
||||||
|
fac.Error(w, r, 0, "user.welcome", "Alice")
|
||||||
|
// 如果消息内容是 "欢迎,%s",返回: {"code": 0, "message": "欢迎,Alice"}
|
||||||
|
|
||||||
|
// 方式3:直接传入消息文本(不使用国际化)
|
||||||
|
fac.Error(w, r, 500, "系统错误")
|
||||||
|
// 返回: {"code": 500, "message": "系统错误"}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 获取消息方法
|
||||||
|
|
||||||
|
#### GetMessage
|
||||||
|
|
||||||
|
获取指定语言和代码的消息内容(推荐使用)。
|
||||||
|
|
||||||
|
```go
|
||||||
|
fac.GetMessage(lang, code string, args ...interface{}) string
|
||||||
|
```
|
||||||
|
|
||||||
|
**参数**:
|
||||||
|
- `lang`: 语言代码(如 "zh-CN", "en-US")
|
||||||
|
- `code`: 消息代码(如 "user.not_found")
|
||||||
|
- `args`: 可选参数,用于格式化消息(类似 fmt.Sprintf)
|
||||||
|
|
||||||
|
**返回逻辑**:
|
||||||
|
1. 如果指定语言存在该code,返回对应内容
|
||||||
|
2. 如果指定语言不存在,尝试使用默认语言
|
||||||
|
3. 如果默认语言也不存在,返回code本身(作为fallback)
|
||||||
|
|
||||||
|
**示例**:
|
||||||
|
```go
|
||||||
|
// 简单消息
|
||||||
|
msg := fac.GetMessage("zh-CN", "user.not_found")
|
||||||
|
// 返回: "用户不存在"
|
||||||
|
|
||||||
|
// 带参数的消息
|
||||||
|
msg := fac.GetMessage("zh-CN", "user.welcome", "Alice")
|
||||||
|
// 如果消息内容是 "欢迎,%s",返回: "欢迎,Alice"
|
||||||
|
```
|
||||||
|
|
||||||
|
### GetLanguage
|
||||||
|
|
||||||
|
从请求的context中获取语言代码(推荐使用)。
|
||||||
|
|
||||||
|
```go
|
||||||
|
fac.GetLanguage(r *http.Request) string
|
||||||
|
```
|
||||||
|
|
||||||
|
**参数**:
|
||||||
|
- `r`: HTTP请求
|
||||||
|
|
||||||
|
**返回逻辑**:
|
||||||
|
1. 从请求context中获取语言(由middleware.Language中间件设置)
|
||||||
|
2. 如果未设置,返回默认语言 zh-CN
|
||||||
|
|
||||||
|
**示例**:
|
||||||
|
```go
|
||||||
|
lang := fac.GetLanguage(r)
|
||||||
|
// 可能返回: "zh-CN", "en-US" 等
|
||||||
|
```
|
||||||
|
|
||||||
|
### 高级功能
|
||||||
|
|
||||||
|
#### GetI18n
|
||||||
|
|
||||||
|
获取国际化工具对象(仅在需要高级功能时使用)。
|
||||||
|
|
||||||
|
```go
|
||||||
|
fac.GetI18n() (*i18n.I18n, error)
|
||||||
|
```
|
||||||
|
|
||||||
|
**返回**:国际化工具对象
|
||||||
|
|
||||||
|
**高级功能示例**:
|
||||||
|
```go
|
||||||
|
i18n, _ := fac.GetI18n()
|
||||||
|
|
||||||
|
// 检查语言是否存在
|
||||||
|
hasLang := i18n.HasLang("en-US")
|
||||||
|
|
||||||
|
// 获取所有支持的语言
|
||||||
|
langs := i18n.GetSupportedLangs()
|
||||||
|
|
||||||
|
// 重新加载语言文件
|
||||||
|
i18n.ReloadFromFile("locales/zh-CN.json", "zh-CN")
|
||||||
|
|
||||||
|
// 动态设置默认语言
|
||||||
|
i18n.SetDefaultLang("en-US")
|
||||||
|
```
|
||||||
|
|
||||||
|
## 使用场景
|
||||||
|
|
||||||
|
### 场景1:HTTP API 响应消息(推荐使用 Error 方法)
|
||||||
|
|
||||||
|
**推荐方式**:使用 `Error` 方法,自动从请求中获取语言并返回国际化消息和业务code:
|
||||||
|
|
||||||
|
```go
|
||||||
|
func handleLogin(w http.ResponseWriter, r *http.Request) {
|
||||||
|
fac, _ := factory.NewFactoryFromFile("config.json")
|
||||||
|
|
||||||
|
// 验证用户
|
||||||
|
user, err := validateUser(r)
|
||||||
|
if err != nil {
|
||||||
|
// 直接传入消息代码,自动获取业务code和国际化消息(推荐)
|
||||||
|
// 会自动从请求context获取语言(由middleware.Language中间件设置)
|
||||||
|
fac.Error(w, r, 0, "user.not_found")
|
||||||
|
// 返回: {"code": 100002, "message": "用户不存在"} 或 {"code": 100002, "message": "User not found"}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// 成功消息
|
||||||
|
lang := fac.GetLanguage(r)
|
||||||
|
msg := fac.GetMessage(lang, "user.login_success")
|
||||||
|
fac.Success(w, user, msg)
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 场景2:带参数的消息
|
||||||
|
|
||||||
|
```go
|
||||||
|
func handleWelcome(w http.ResponseWriter, r *http.Request) {
|
||||||
|
fac, _ := factory.NewFactoryFromFile("config.json")
|
||||||
|
lang := getLangFromRequest(r)
|
||||||
|
|
||||||
|
username := "Alice"
|
||||||
|
// 消息内容: "欢迎,%s"
|
||||||
|
msg := fac.GetMessage(lang, "user.welcome", username)
|
||||||
|
// 返回: "欢迎,Alice" 或 "Welcome, Alice"
|
||||||
|
|
||||||
|
fac.Success(w, nil, msg)
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 场景3:错误消息国际化(推荐使用 Error 方法)
|
||||||
|
|
||||||
|
**推荐方式**:使用 `Error` 方法,自动获取业务code和国际化消息:
|
||||||
|
|
||||||
|
```go
|
||||||
|
func handleError(w http.ResponseWriter, r *http.Request, messageCode string) {
|
||||||
|
fac, _ := factory.NewFactoryFromFile("config.json")
|
||||||
|
|
||||||
|
// 直接传入消息代码,自动获取业务code和国际化消息(推荐)
|
||||||
|
// 会自动从请求context获取语言并查找对应的国际化消息和业务code
|
||||||
|
fac.Error(w, r, 0, "error."+messageCode)
|
||||||
|
// 例如:fac.Error(w, r, 0, "error.invalid_params")
|
||||||
|
// 返回: {"code": 100001, "message": "参数无效"} 或 {"code": 100001, "message": "Invalid parameters"}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## 语言文件格式
|
||||||
|
|
||||||
|
语言文件必须是 JSON 格式,每个消息包含业务code和消息内容:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"user.not_found": {
|
||||||
|
"code": 100002,
|
||||||
|
"message": "用户不存在"
|
||||||
|
},
|
||||||
|
"user.login_success": {
|
||||||
|
"code": 0,
|
||||||
|
"message": "登录成功"
|
||||||
|
},
|
||||||
|
"user.welcome": {
|
||||||
|
"code": 0,
|
||||||
|
"message": "欢迎,%s"
|
||||||
|
},
|
||||||
|
"error.invalid_params": {
|
||||||
|
"code": 100001,
|
||||||
|
"message": "参数无效"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**注意事项**:
|
||||||
|
- key(消息代码)建议使用点号分隔的层级结构(如 `user.not_found`)
|
||||||
|
- value 是一个对象,包含:
|
||||||
|
- `code`: 业务错误码(整数),用于业务逻辑判断,所有语言的同一消息代码应使用相同的code
|
||||||
|
- `message`: 消息内容(字符串),支持格式化占位符(如 `%s`, `%d`)
|
||||||
|
- 所有语言文件应该包含相同的 key,确保所有语言都有对应的翻译
|
||||||
|
- **重要**:同一消息代码在所有语言文件中的 `code` 必须保持一致,只有 `message` 会根据语言变化
|
||||||
|
|
||||||
|
## 最佳实践
|
||||||
|
|
||||||
|
### 1. 消息代码命名规范
|
||||||
|
|
||||||
|
建议使用层级结构,便于管理和查找:
|
||||||
|
|
||||||
|
```
|
||||||
|
模块.功能.状态
|
||||||
|
例如:
|
||||||
|
- user.not_found
|
||||||
|
- user.login_success
|
||||||
|
- order.created
|
||||||
|
- order.paid
|
||||||
|
- error.invalid_params
|
||||||
|
- error.server_error
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2. 默认语言设置
|
||||||
|
|
||||||
|
建议将最常用的语言设置为默认语言,确保在语言不存在时有合理的回退:
|
||||||
|
|
||||||
|
```go
|
||||||
|
fac.InitI18n("zh-CN") // 中文作为默认语言
|
||||||
|
```
|
||||||
|
|
||||||
|
### 3. 语言代码规范
|
||||||
|
|
||||||
|
建议使用标准的语言代码格式:
|
||||||
|
- `zh-CN`: 简体中文
|
||||||
|
- `zh-TW`: 繁体中文
|
||||||
|
- `en-US`: 美式英语
|
||||||
|
- `en-GB`: 英式英语
|
||||||
|
- `ja-JP`: 日语
|
||||||
|
- `ko-KR`: 韩语
|
||||||
|
|
||||||
|
### 4. 文件组织
|
||||||
|
|
||||||
|
建议将所有语言文件放在统一的目录下:
|
||||||
|
|
||||||
|
```
|
||||||
|
project/
|
||||||
|
locales/
|
||||||
|
zh-CN.json
|
||||||
|
en-US.json
|
||||||
|
ja-JP.json
|
||||||
|
```
|
||||||
|
|
||||||
|
### 5. 参数使用
|
||||||
|
|
||||||
|
对于需要动态内容的消息,使用格式化参数:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"user.welcome": {
|
||||||
|
"code": 0,
|
||||||
|
"message": "欢迎,%s"
|
||||||
|
},
|
||||||
|
"order.total": {
|
||||||
|
"code": 0,
|
||||||
|
"message": "订单总额:%.2f 元"
|
||||||
|
},
|
||||||
|
"message.count": {
|
||||||
|
"code": 0,
|
||||||
|
"message": "您有 %d 条新消息"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
使用方式:
|
||||||
|
```go
|
||||||
|
// 使用 GetMessage
|
||||||
|
msg := fac.GetMessage("zh-CN", "user.welcome", "Alice")
|
||||||
|
msg := fac.GetMessage("zh-CN", "order.total", 99.99)
|
||||||
|
msg := fac.GetMessage("zh-CN", "message.count", 5)
|
||||||
|
|
||||||
|
// 使用 Error 方法(推荐)
|
||||||
|
fac.Error(w, r, 0, "user.welcome", "Alice")
|
||||||
|
fac.Error(w, r, 0, "message.count", 5)
|
||||||
|
```
|
||||||
|
|
||||||
|
### 6. 业务Code管理
|
||||||
|
|
||||||
|
**重要原则**:同一消息代码在所有语言文件中的业务code必须保持一致。
|
||||||
|
|
||||||
|
```json
|
||||||
|
// zh-CN.json
|
||||||
|
{
|
||||||
|
"user.not_found": {
|
||||||
|
"code": 100002, // 业务code
|
||||||
|
"message": "用户不存在"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// en-US.json
|
||||||
|
{
|
||||||
|
"user.not_found": {
|
||||||
|
"code": 100002, // 必须与zh-CN.json中的code相同
|
||||||
|
"message": "User not found" // 只有message会根据语言变化
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
这样设计的好处:
|
||||||
|
- 调用端可以根据返回的 `code` 进行业务逻辑判断,不受语言影响
|
||||||
|
- 所有语言的同一错误使用相同的业务code,便于统一管理
|
||||||
|
|
||||||
|
## 常见问题
|
||||||
|
|
||||||
|
### Q1: 如果语言文件不存在会怎样?
|
||||||
|
|
||||||
|
A: 如果语言文件不存在,`LoadI18nFromFile` 或 `LoadI18nFromDir` 会返回错误。建议在初始化时检查错误。
|
||||||
|
|
||||||
|
### Q2: 如果消息代码不存在会怎样?
|
||||||
|
|
||||||
|
A: `GetMessage` 和 `Error` 会按以下顺序查找:
|
||||||
|
1. 指定语言的消息
|
||||||
|
2. 默认语言的消息
|
||||||
|
3. 如果都不存在:
|
||||||
|
- `GetMessage` 返回消息代码本身(作为fallback)
|
||||||
|
- `Error` 使用传入的code参数和消息代码作为message
|
||||||
|
|
||||||
|
### Q5: 业务code在不同语言中必须相同吗?
|
||||||
|
|
||||||
|
A: **是的,必须相同**。同一消息代码在所有语言文件中的业务code必须保持一致,只有message内容会根据语言变化。这样调用端可以根据code进行业务逻辑判断,不受语言影响。
|
||||||
|
|
||||||
|
### Q3: 如何支持动态加载语言文件?
|
||||||
|
|
||||||
|
A: 可以使用 `GetI18n()` 获取对象,然后调用 `ReloadFromFile()` 或 `ReloadFromDir()` 方法。
|
||||||
|
|
||||||
|
### Q4: 是否支持嵌套的消息结构?
|
||||||
|
|
||||||
|
A: 当前版本只支持扁平结构(key-value),不支持嵌套。如果需要嵌套结构,建议使用点号分隔的层级命名(如 `user.profile.name`)。
|
||||||
|
|
||||||
|
## 完整示例
|
||||||
|
|
||||||
|
参考 [examples/i18n_example.go](../examples/i18n_example.go)
|
||||||
233
examples/excel_example.go
Normal file
233
examples/excel_example.go
Normal file
@@ -0,0 +1,233 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"log"
|
||||||
|
"net/http"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"git.toowon.com/jimmy/go-common/excel"
|
||||||
|
"git.toowon.com/jimmy/go-common/factory"
|
||||||
|
"git.toowon.com/jimmy/go-common/tools"
|
||||||
|
)
|
||||||
|
|
||||||
|
// User 用户结构体示例
|
||||||
|
type User struct {
|
||||||
|
ID int `json:"id"`
|
||||||
|
Name string `json:"name"`
|
||||||
|
Email string `json:"email"`
|
||||||
|
CreatedAt time.Time `json:"created_at"`
|
||||||
|
Status int `json:"status"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
// 创建工厂(可选,Excel导出不需要配置)
|
||||||
|
fac, err := factory.NewFactoryFromFile("./config/example.json")
|
||||||
|
if err != nil {
|
||||||
|
// Excel导出不需要配置,可以传nil
|
||||||
|
fac = factory.NewFactory(nil)
|
||||||
|
}
|
||||||
|
|
||||||
|
// 示例1:导出结构体切片到文件
|
||||||
|
fmt.Println("=== Example 1: Export Struct Slice to File ===")
|
||||||
|
example1(fac)
|
||||||
|
|
||||||
|
// 示例2:导出到HTTP响应
|
||||||
|
fmt.Println("\n=== Example 2: Export to HTTP Response ===")
|
||||||
|
example2(fac)
|
||||||
|
|
||||||
|
// 示例3:使用格式化函数
|
||||||
|
fmt.Println("\n=== Example 3: Export with Format Functions ===")
|
||||||
|
example3(fac)
|
||||||
|
|
||||||
|
// 示例4:使用ExportData接口
|
||||||
|
fmt.Println("\n=== Example 4: Export with ExportData Interface ===")
|
||||||
|
example4(fac)
|
||||||
|
}
|
||||||
|
|
||||||
|
// 示例1:导出结构体切片到文件
|
||||||
|
func example1(fac *factory.Factory) {
|
||||||
|
users := []User{
|
||||||
|
{ID: 1, Name: "Alice", Email: "alice@example.com", CreatedAt: time.Now(), Status: 1},
|
||||||
|
{ID: 2, Name: "Bob", Email: "bob@example.com", CreatedAt: time.Now().Add(-24 * time.Hour), Status: 1},
|
||||||
|
{ID: 3, Name: "Charlie", Email: "charlie@example.com", CreatedAt: time.Now().Add(-48 * time.Hour), Status: 0},
|
||||||
|
}
|
||||||
|
|
||||||
|
columns := []factory.ExportColumn{
|
||||||
|
{Header: "ID", Field: "ID", Width: 10},
|
||||||
|
{Header: "姓名", Field: "Name", Width: 20},
|
||||||
|
{Header: "邮箱", Field: "Email", Width: 30},
|
||||||
|
{Header: "创建时间", Field: "CreatedAt", Width: 20},
|
||||||
|
{Header: "状态", Field: "Status", Width: 10},
|
||||||
|
}
|
||||||
|
|
||||||
|
err := fac.ExportToExcelFile("users.xlsx", "用户列表", columns, users)
|
||||||
|
if err != nil {
|
||||||
|
log.Printf("Failed to export to file: %v", err)
|
||||||
|
} else {
|
||||||
|
fmt.Println("Excel file exported successfully: users.xlsx")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 示例2:导出到HTTP响应
|
||||||
|
func example2(fac *factory.Factory) {
|
||||||
|
// 模拟HTTP响应
|
||||||
|
w := &mockResponseWriter{}
|
||||||
|
|
||||||
|
users := []User{
|
||||||
|
{ID: 1, Name: "Alice", Email: "alice@example.com", CreatedAt: time.Now(), Status: 1},
|
||||||
|
{ID: 2, Name: "Bob", Email: "bob@example.com", CreatedAt: time.Now(), Status: 1},
|
||||||
|
}
|
||||||
|
|
||||||
|
columns := []factory.ExportColumn{
|
||||||
|
{Header: "ID", Field: "ID"},
|
||||||
|
{Header: "姓名", Field: "Name"},
|
||||||
|
{Header: "邮箱", Field: "Email"},
|
||||||
|
}
|
||||||
|
|
||||||
|
// 设置HTTP响应头
|
||||||
|
w.Header().Set("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
|
||||||
|
w.Header().Set("Content-Disposition", "attachment; filename=users.xlsx")
|
||||||
|
|
||||||
|
err := fac.ExportToExcel(w, "用户列表", columns, users)
|
||||||
|
if err != nil {
|
||||||
|
log.Printf("Failed to export to HTTP response: %v", err)
|
||||||
|
} else {
|
||||||
|
fmt.Printf("Excel exported to HTTP response successfully, size: %d bytes\n", len(w.data))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 示例3:使用格式化函数
|
||||||
|
func example3(fac *factory.Factory) {
|
||||||
|
users := []User{
|
||||||
|
{ID: 1, Name: "Alice", Email: "alice@example.com", CreatedAt: time.Now(), Status: 1},
|
||||||
|
{ID: 2, Name: "Bob", Email: "bob@example.com", CreatedAt: time.Now().Add(-24 * time.Hour), Status: 0},
|
||||||
|
}
|
||||||
|
|
||||||
|
columns := []factory.ExportColumn{
|
||||||
|
{Header: "ID", Field: "ID", Width: 10},
|
||||||
|
{Header: "姓名", Field: "Name", Width: 20},
|
||||||
|
{Header: "邮箱", Field: "Email", Width: 30},
|
||||||
|
{
|
||||||
|
Header: "创建时间",
|
||||||
|
Field: "CreatedAt",
|
||||||
|
Width: 20,
|
||||||
|
Format: excel.AdaptTimeFormatter(tools.FormatDateTime), // 使用适配器直接调用tools函数
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Header: "状态",
|
||||||
|
Field: "Status",
|
||||||
|
Width: 10,
|
||||||
|
Format: func(value interface{}) string {
|
||||||
|
// 自定义格式化函数
|
||||||
|
if status, ok := value.(int); ok {
|
||||||
|
if status == 1 {
|
||||||
|
return "启用"
|
||||||
|
}
|
||||||
|
return "禁用"
|
||||||
|
}
|
||||||
|
return ""
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
err := fac.ExportToExcelFile("users_formatted.xlsx", "用户列表", columns, users)
|
||||||
|
if err != nil {
|
||||||
|
log.Printf("Failed to export with format: %v", err)
|
||||||
|
} else {
|
||||||
|
fmt.Println("Excel file exported with format successfully: users_formatted.xlsx")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 示例4:使用ExportData接口
|
||||||
|
func example4(fac *factory.Factory) {
|
||||||
|
// 创建实现了ExportData接口的数据对象
|
||||||
|
exportData := &UserExportData{
|
||||||
|
users: []User{
|
||||||
|
{ID: 1, Name: "Alice", Email: "alice@example.com", CreatedAt: time.Now(), Status: 1},
|
||||||
|
{ID: 2, Name: "Bob", Email: "bob@example.com", CreatedAt: time.Now(), Status: 1},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
// 使用接口方法获取列定义和数据
|
||||||
|
columns := exportData.GetExportColumns()
|
||||||
|
|
||||||
|
err := fac.ExportToExcelFile("users_interface.xlsx", "用户列表", columns, exportData)
|
||||||
|
if err != nil {
|
||||||
|
log.Printf("Failed to export with interface: %v", err)
|
||||||
|
} else {
|
||||||
|
fmt.Println("Excel file exported with interface successfully: users_interface.xlsx")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// UserExportData 实现了ExportData接口的用户导出数据
|
||||||
|
type UserExportData struct {
|
||||||
|
users []User
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetExportColumns 获取导出列定义
|
||||||
|
func (d *UserExportData) GetExportColumns() []excel.ExportColumn {
|
||||||
|
return []excel.ExportColumn{
|
||||||
|
{Header: "ID", Field: "ID", Width: 10},
|
||||||
|
{Header: "姓名", Field: "Name", Width: 20},
|
||||||
|
{Header: "邮箱", Field: "Email", Width: 30},
|
||||||
|
{
|
||||||
|
Header: "创建时间",
|
||||||
|
Field: "CreatedAt",
|
||||||
|
Width: 20,
|
||||||
|
Format: excel.AdaptTimeFormatter(tools.FormatDateTime),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Header: "状态",
|
||||||
|
Field: "Status",
|
||||||
|
Width: 10,
|
||||||
|
Format: func(value interface{}) string {
|
||||||
|
if status, ok := value.(int); ok {
|
||||||
|
if status == 1 {
|
||||||
|
return "启用"
|
||||||
|
}
|
||||||
|
return "禁用"
|
||||||
|
}
|
||||||
|
return ""
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetExportRows 获取导出数据行
|
||||||
|
func (d *UserExportData) GetExportRows() [][]interface{} {
|
||||||
|
rows := make([][]interface{}, 0, len(d.users))
|
||||||
|
for _, user := range d.users {
|
||||||
|
row := []interface{}{
|
||||||
|
user.ID,
|
||||||
|
user.Name,
|
||||||
|
user.Email,
|
||||||
|
user.CreatedAt,
|
||||||
|
user.Status,
|
||||||
|
}
|
||||||
|
rows = append(rows, row)
|
||||||
|
}
|
||||||
|
return rows
|
||||||
|
}
|
||||||
|
|
||||||
|
// mockResponseWriter 模拟HTTP响应写入器(用于示例)
|
||||||
|
type mockResponseWriter struct {
|
||||||
|
header http.Header
|
||||||
|
data []byte
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *mockResponseWriter) Header() http.Header {
|
||||||
|
if w.header == nil {
|
||||||
|
w.header = make(http.Header)
|
||||||
|
}
|
||||||
|
return w.header
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *mockResponseWriter) Write(data []byte) (int, error) {
|
||||||
|
w.data = append(w.data, data...)
|
||||||
|
return len(data), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *mockResponseWriter) WriteHeader(statusCode int) {
|
||||||
|
// 模拟实现
|
||||||
|
}
|
||||||
@@ -4,8 +4,9 @@ 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"
|
||||||
|
"git.toowon.com/jimmy/go-common/tools"
|
||||||
)
|
)
|
||||||
|
|
||||||
// 用户结构
|
// 用户结构
|
||||||
@@ -22,10 +23,10 @@ func GetUserList(w http.ResponseWriter, r *http.Request) {
|
|||||||
// 获取分页参数(使用公共方法)
|
// 获取分页参数(使用公共方法)
|
||||||
pagination := commonhttp.ParsePaginationRequest(r)
|
pagination := commonhttp.ParsePaginationRequest(r)
|
||||||
page := pagination.GetPage()
|
page := pagination.GetPage()
|
||||||
pageSize := pagination.GetSize()
|
pageSize := pagination.GetPageSize()
|
||||||
|
|
||||||
// 获取查询参数(使用公共方法)
|
// 获取查询参数(使用公共方法)
|
||||||
_ = commonhttp.GetQuery(r, "keyword", "") // 示例:获取查询参数
|
_ = r.URL.Query().Get("keyword") // 示例:获取查询参数
|
||||||
|
|
||||||
// 模拟查询数据
|
// 模拟查询数据
|
||||||
users := []User{
|
users := []User{
|
||||||
@@ -75,7 +76,7 @@ func GetUser(w http.ResponseWriter, r *http.Request) {
|
|||||||
fac, _ := factory.NewFactoryFromFile("config.json")
|
fac, _ := factory.NewFactoryFromFile("config.json")
|
||||||
|
|
||||||
// 获取查询参数(使用公共方法)
|
// 获取查询参数(使用公共方法)
|
||||||
id := commonhttp.GetQueryInt64(r, "id", 0)
|
id := tools.ConvertInt64(r.URL.Query().Get("id"), 0)
|
||||||
|
|
||||||
if id == 0 {
|
if id == 0 {
|
||||||
commonhttp.WriteJSON(w, http.StatusBadRequest, 400, "用户ID不能为空", nil)
|
commonhttp.WriteJSON(w, http.StatusBadRequest, 400, "用户ID不能为空", nil)
|
||||||
|
|||||||
@@ -4,8 +4,8 @@ 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 用户列表请求(包含分页字段)
|
// ListUserRequest 用户列表请求(包含分页字段)
|
||||||
@@ -36,12 +36,12 @@ func GetUserList(w http.ResponseWriter, r *http.Request) {
|
|||||||
// 方式2:从查询参数解析分页
|
// 方式2:从查询参数解析分页
|
||||||
pagination := commonhttp.ParsePaginationRequest(r)
|
pagination := commonhttp.ParsePaginationRequest(r)
|
||||||
req.PaginationRequest = *pagination
|
req.PaginationRequest = *pagination
|
||||||
req.Keyword = commonhttp.GetQuery(r, "keyword", "")
|
req.Keyword = r.URL.Query().Get("keyword")
|
||||||
}
|
}
|
||||||
|
|
||||||
// 使用分页方法
|
// 使用分页方法
|
||||||
page := req.GetPage() // 获取页码(默认1)
|
page := req.GetPage() // 获取页码(默认1)
|
||||||
size := req.GetSize() // 获取每页数量(默认20,最大100)
|
pageSize := req.GetPageSize() // 获取每页数量(默认20,最大100)
|
||||||
_ = req.GetOffset() // 计算偏移量
|
_ = req.GetOffset() // 计算偏移量
|
||||||
|
|
||||||
// 模拟查询数据
|
// 模拟查询数据
|
||||||
@@ -52,7 +52,7 @@ func GetUserList(w http.ResponseWriter, r *http.Request) {
|
|||||||
total := int64(100)
|
total := int64(100)
|
||||||
|
|
||||||
// 返回分页响应(使用factory方法)
|
// 返回分页响应(使用factory方法)
|
||||||
fac.SuccessPage(w, users, total, page, size)
|
fac.SuccessPage(w, users, total, page, pageSize)
|
||||||
}
|
}
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
|
|||||||
101
examples/i18n_example.go
Normal file
101
examples/i18n_example.go
Normal file
@@ -0,0 +1,101 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"log"
|
||||||
|
|
||||||
|
"git.toowon.com/jimmy/go-common/factory"
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
// 创建工厂实例
|
||||||
|
fac, err := factory.NewFactoryFromFile("config.json")
|
||||||
|
if err != nil {
|
||||||
|
log.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ====== 方式1:从目录加载多个语言文件(推荐) ======
|
||||||
|
// 目录结构:
|
||||||
|
// locales/
|
||||||
|
// zh-CN.json
|
||||||
|
// en-US.json
|
||||||
|
// ja-JP.json
|
||||||
|
|
||||||
|
fac.InitI18n("zh-CN") // 设置默认语言为中文
|
||||||
|
if err := fac.LoadI18nFromDir("locales"); err != nil {
|
||||||
|
log.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// 使用示例
|
||||||
|
fmt.Println("=== 示例1:简单消息 ===")
|
||||||
|
msg1 := fac.GetMessage("zh-CN", "user.not_found")
|
||||||
|
fmt.Printf("中文: %s\n", msg1)
|
||||||
|
|
||||||
|
msg2 := fac.GetMessage("en-US", "user.not_found")
|
||||||
|
fmt.Printf("英文: %s\n", msg2)
|
||||||
|
|
||||||
|
// ====== 方式2:从单个文件加载 ======
|
||||||
|
fmt.Println("\n=== 示例2:从单个文件加载 ===")
|
||||||
|
fac2, _ := factory.NewFactoryFromFile("config.json")
|
||||||
|
fac2.InitI18n("zh-CN")
|
||||||
|
fac2.LoadI18nFromFile("locales/zh-CN.json", "zh-CN")
|
||||||
|
fac2.LoadI18nFromFile("locales/en-US.json", "en-US")
|
||||||
|
|
||||||
|
msg3 := fac2.GetMessage("zh-CN", "user.login_success")
|
||||||
|
fmt.Printf("中文: %s\n", msg3)
|
||||||
|
|
||||||
|
// ====== 示例3:带参数的消息 ======
|
||||||
|
fmt.Println("\n=== 示例3:带参数的消息 ===")
|
||||||
|
// 如果消息内容是 "欢迎,%s",可以使用参数
|
||||||
|
msg4 := fac.GetMessage("zh-CN", "user.welcome", "Alice")
|
||||||
|
fmt.Printf("中文: %s\n", msg4)
|
||||||
|
|
||||||
|
msg5 := fac.GetMessage("en-US", "user.welcome", "Alice")
|
||||||
|
fmt.Printf("英文: %s\n", msg5)
|
||||||
|
|
||||||
|
// ====== 示例4:语言回退机制 ======
|
||||||
|
fmt.Println("\n=== 示例4:语言回退机制 ===")
|
||||||
|
// 如果请求的语言不存在,会使用默认语言
|
||||||
|
msg6 := fac.GetMessage("fr-FR", "user.not_found") // fr-FR 不存在,使用默认语言 zh-CN
|
||||||
|
fmt.Printf("法语(不存在,回退到默认语言): %s\n", msg6)
|
||||||
|
|
||||||
|
// ====== 示例5:高级功能 ======
|
||||||
|
fmt.Println("\n=== 示例5:高级功能 ===")
|
||||||
|
i18n, _ := fac.GetI18n()
|
||||||
|
langs := i18n.GetSupportedLangs()
|
||||||
|
fmt.Printf("支持的语言: %v\n", langs)
|
||||||
|
|
||||||
|
hasLang := i18n.HasLang("en-US")
|
||||||
|
fmt.Printf("是否支持英文: %v\n", hasLang)
|
||||||
|
|
||||||
|
// ====== 示例6:在HTTP处理中使用 ======
|
||||||
|
fmt.Println("\n=== 示例6:在HTTP处理中使用 ===")
|
||||||
|
// 在实际HTTP处理中,可以从请求头获取语言
|
||||||
|
// lang := r.Header.Get("Accept-Language") // 例如: "zh-CN,en-US;q=0.9"
|
||||||
|
// 简化示例,假设从请求中获取到语言代码
|
||||||
|
userLang := "zh-CN"
|
||||||
|
errorMsg := fac.GetMessage(userLang, "user.not_found")
|
||||||
|
fmt.Printf("错误消息: %s\n", errorMsg)
|
||||||
|
|
||||||
|
successMsg := fac.GetMessage(userLang, "user.login_success")
|
||||||
|
fmt.Printf("成功消息: %s\n", successMsg)
|
||||||
|
|
||||||
|
// ====== 示例7:通过错误码直接返回国际化消息(推荐) ======
|
||||||
|
fmt.Println("\n=== 示例7:通过错误码直接返回国际化消息 ===")
|
||||||
|
// 在实际HTTP处理中,Error 方法会自动识别消息代码并返回国际化消息
|
||||||
|
// 需要确保使用了 middleware.Language 中间件(factory.GetMiddlewareChain() 已包含)
|
||||||
|
//
|
||||||
|
// 示例代码(在HTTP handler中):
|
||||||
|
// func handleGetUser(w http.ResponseWriter, r *http.Request) {
|
||||||
|
// fac, _ := factory.NewFactoryFromFile("config.json")
|
||||||
|
//
|
||||||
|
// // 如果用户不存在,直接传入消息代码,会自动获取国际化消息
|
||||||
|
// fac.Error(w, r, 404, "user.not_found")
|
||||||
|
// // 自动从context获取语言(由middleware.Language设置),返回对应语言的错误消息
|
||||||
|
// // 返回: {"code": 404, "message": "用户不存在", "message_code": "user.not_found"}
|
||||||
|
// }
|
||||||
|
//
|
||||||
|
// 如果请求头是 Accept-Language: zh-CN,返回: {"code": 404, "message": "用户不存在", "message_code": "user.not_found"}
|
||||||
|
// 如果请求头是 Accept-Language: en-US,返回: {"code": 404, "message": "User not found", "message_code": "user.not_found"}
|
||||||
|
fmt.Println("Error 方法会自动识别消息代码并返回国际化消息和消息代码")
|
||||||
|
}
|
||||||
38
examples/locales/en-US.json
Normal file
38
examples/locales/en-US.json
Normal file
@@ -0,0 +1,38 @@
|
|||||||
|
{
|
||||||
|
"user.not_found": {
|
||||||
|
"code": 100002,
|
||||||
|
"message": "User not found"
|
||||||
|
},
|
||||||
|
"user.login_success": {
|
||||||
|
"code": 0,
|
||||||
|
"message": "Login successful"
|
||||||
|
},
|
||||||
|
"user.welcome": {
|
||||||
|
"code": 0,
|
||||||
|
"message": "Welcome, %s"
|
||||||
|
},
|
||||||
|
"user.logout": {
|
||||||
|
"code": 0,
|
||||||
|
"message": "Logout"
|
||||||
|
},
|
||||||
|
"error.invalid_params": {
|
||||||
|
"code": 100001,
|
||||||
|
"message": "Invalid parameters"
|
||||||
|
},
|
||||||
|
"error.server_error": {
|
||||||
|
"code": 100003,
|
||||||
|
"message": "Server error"
|
||||||
|
},
|
||||||
|
"order.created": {
|
||||||
|
"code": 0,
|
||||||
|
"message": "Order created successfully"
|
||||||
|
},
|
||||||
|
"order.paid": {
|
||||||
|
"code": 0,
|
||||||
|
"message": "Order paid successfully"
|
||||||
|
},
|
||||||
|
"message.count": {
|
||||||
|
"code": 0,
|
||||||
|
"message": "You have %d new messages"
|
||||||
|
}
|
||||||
|
}
|
||||||
38
examples/locales/zh-CN.json
Normal file
38
examples/locales/zh-CN.json
Normal file
@@ -0,0 +1,38 @@
|
|||||||
|
{
|
||||||
|
"user.not_found": {
|
||||||
|
"code": 100002,
|
||||||
|
"message": "用户不存在"
|
||||||
|
},
|
||||||
|
"user.login_success": {
|
||||||
|
"code": 0,
|
||||||
|
"message": "登录成功"
|
||||||
|
},
|
||||||
|
"user.welcome": {
|
||||||
|
"code": 0,
|
||||||
|
"message": "欢迎,%s"
|
||||||
|
},
|
||||||
|
"user.logout": {
|
||||||
|
"code": 0,
|
||||||
|
"message": "退出登录"
|
||||||
|
},
|
||||||
|
"error.invalid_params": {
|
||||||
|
"code": 100001,
|
||||||
|
"message": "参数无效"
|
||||||
|
},
|
||||||
|
"error.server_error": {
|
||||||
|
"code": 100003,
|
||||||
|
"message": "服务器错误"
|
||||||
|
},
|
||||||
|
"order.created": {
|
||||||
|
"code": 0,
|
||||||
|
"message": "订单创建成功"
|
||||||
|
},
|
||||||
|
"order.paid": {
|
||||||
|
"code": 0,
|
||||||
|
"message": "订单支付成功"
|
||||||
|
},
|
||||||
|
"message.count": {
|
||||||
|
"code": 0,
|
||||||
|
"message": "您有 %d 条新消息"
|
||||||
|
}
|
||||||
|
}
|
||||||
524
excel/excel.go
Normal file
524
excel/excel.go
Normal file
@@ -0,0 +1,524 @@
|
|||||||
|
package excel
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"reflect"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"git.toowon.com/jimmy/go-common/tools"
|
||||||
|
"github.com/xuri/excelize/v2"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Excel Excel导出器
|
||||||
|
type Excel struct {
|
||||||
|
file *excelize.File
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewExcel 创建Excel导出器
|
||||||
|
func NewExcel() *Excel {
|
||||||
|
return &Excel{
|
||||||
|
file: excelize.NewFile(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ExportColumn 导出列定义
|
||||||
|
type ExportColumn struct {
|
||||||
|
// Header 表头名称
|
||||||
|
Header string
|
||||||
|
// Field 数据字段名(支持嵌套字段,如 "User.Name")
|
||||||
|
Field string
|
||||||
|
// Width 列宽(可选,0表示自动)
|
||||||
|
Width float64
|
||||||
|
// Format 格式化函数(可选,用于自定义字段值的格式化)
|
||||||
|
Format func(value interface{}) string
|
||||||
|
}
|
||||||
|
|
||||||
|
// ExportData 导出数据接口
|
||||||
|
// 实现此接口的结构体可以直接导出
|
||||||
|
type ExportData interface {
|
||||||
|
// GetExportColumns 获取导出列定义
|
||||||
|
GetExportColumns() []ExportColumn
|
||||||
|
// GetExportRows 获取导出数据行
|
||||||
|
GetExportRows() [][]interface{}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ExportToWriter 导出数据到Writer(黑盒模式,推荐使用)
|
||||||
|
// sheetName: 工作表名称(可选,默认为"Sheet1")
|
||||||
|
// columns: 列定义
|
||||||
|
// data: 数据列表(可以是结构体切片或实现了ExportData接口的对象)
|
||||||
|
// 返回错误信息
|
||||||
|
//
|
||||||
|
// 示例1:导出结构体切片
|
||||||
|
//
|
||||||
|
// type User struct {
|
||||||
|
// ID int `json:"id"`
|
||||||
|
// Name string `json:"name"`
|
||||||
|
// Email string `json:"email"`
|
||||||
|
// }
|
||||||
|
//
|
||||||
|
// users := []User{
|
||||||
|
// {ID: 1, Name: "Alice", Email: "alice@example.com"},
|
||||||
|
// {ID: 2, Name: "Bob", Email: "bob@example.com"},
|
||||||
|
// }
|
||||||
|
//
|
||||||
|
// columns := []ExportColumn{
|
||||||
|
// {Header: "ID", Field: "ID"},
|
||||||
|
// {Header: "姓名", Field: "Name"},
|
||||||
|
// {Header: "邮箱", Field: "Email"},
|
||||||
|
// }
|
||||||
|
//
|
||||||
|
// excel := excel.NewExcel()
|
||||||
|
// err := excel.ExportToWriter(w, "用户列表", columns, users)
|
||||||
|
//
|
||||||
|
// 示例2:使用格式化函数
|
||||||
|
//
|
||||||
|
// columns := []ExportColumn{
|
||||||
|
// {Header: "ID", Field: "ID"},
|
||||||
|
// {Header: "姓名", Field: "Name"},
|
||||||
|
// {Header: "创建时间", Field: "CreatedAt", Format: func(v interface{}) string {
|
||||||
|
// if t, ok := v.(time.Time); ok {
|
||||||
|
// return t.Format("2006-01-02 15:04:05")
|
||||||
|
// }
|
||||||
|
// return ""
|
||||||
|
// }},
|
||||||
|
// }
|
||||||
|
//
|
||||||
|
// excel.ExportToWriter(w, "用户列表", columns, users)
|
||||||
|
func (e *Excel) ExportToWriter(w io.Writer, sheetName string, columns []ExportColumn, data interface{}) error {
|
||||||
|
if e.file == nil {
|
||||||
|
e.file = excelize.NewFile()
|
||||||
|
}
|
||||||
|
|
||||||
|
// 设置工作表名称
|
||||||
|
if sheetName == "" {
|
||||||
|
sheetName = "Sheet1"
|
||||||
|
}
|
||||||
|
|
||||||
|
// 检查工作表是否已存在
|
||||||
|
sheetIndex, err := e.file.GetSheetIndex(sheetName)
|
||||||
|
if err != nil || sheetIndex == 0 {
|
||||||
|
// 工作表不存在,需要创建
|
||||||
|
// 如果sheetName不是"Sheet1",且默认"Sheet1"存在,则删除它
|
||||||
|
if sheetName != "Sheet1" {
|
||||||
|
defaultIndex, _ := e.file.GetSheetIndex("Sheet1")
|
||||||
|
if defaultIndex > 0 {
|
||||||
|
e.file.DeleteSheet("Sheet1")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 创建新工作表
|
||||||
|
_, err = e.file.NewSheet(sheetName)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("failed to create sheet: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// 重新获取工作表索引
|
||||||
|
sheetIndex, err = e.file.GetSheetIndex(sheetName)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("failed to get sheet index: %w", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 设置活动工作表
|
||||||
|
if sheetIndex > 0 {
|
||||||
|
e.file.SetActiveSheet(sheetIndex)
|
||||||
|
}
|
||||||
|
|
||||||
|
// 写入表头
|
||||||
|
headerStyle, _ := e.file.NewStyle(&excelize.Style{
|
||||||
|
Font: &excelize.Font{
|
||||||
|
Bold: true,
|
||||||
|
Size: 12,
|
||||||
|
},
|
||||||
|
Fill: excelize.Fill{
|
||||||
|
Type: "pattern",
|
||||||
|
Color: []string{"#E0E0E0"},
|
||||||
|
Pattern: 1,
|
||||||
|
},
|
||||||
|
Alignment: &excelize.Alignment{
|
||||||
|
Horizontal: "center",
|
||||||
|
Vertical: "center",
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
for i, col := range columns {
|
||||||
|
cell := fmt.Sprintf("%c1", 'A'+i)
|
||||||
|
e.file.SetCellValue(sheetName, cell, col.Header)
|
||||||
|
|
||||||
|
// 设置表头样式
|
||||||
|
e.file.SetCellStyle(sheetName, cell, cell, headerStyle)
|
||||||
|
|
||||||
|
// 设置列宽
|
||||||
|
if col.Width > 0 {
|
||||||
|
colName, _ := excelize.ColumnNumberToName(i + 1)
|
||||||
|
e.file.SetColWidth(sheetName, colName, colName, col.Width)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 处理数据
|
||||||
|
var rows [][]interface{}
|
||||||
|
|
||||||
|
// 检查数据是否实现了ExportData接口
|
||||||
|
if exportData, ok := data.(ExportData); ok {
|
||||||
|
// 使用接口方法获取数据
|
||||||
|
rows = exportData.GetExportRows()
|
||||||
|
} else {
|
||||||
|
// 处理结构体切片
|
||||||
|
rows, err = e.convertDataToRows(data, columns)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("failed to convert data to rows: %w", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 写入数据行
|
||||||
|
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 导出数据到文件(黑盒模式,推荐使用)
|
||||||
|
// filePath: 文件路径
|
||||||
|
// sheetName: 工作表名称(可选,默认为"Sheet1")
|
||||||
|
// columns: 列定义
|
||||||
|
// data: 数据列表
|
||||||
|
// 返回错误信息
|
||||||
|
//
|
||||||
|
// 示例:
|
||||||
|
//
|
||||||
|
// excel := excel.NewExcel()
|
||||||
|
// err := excel.ExportToFile("users.xlsx", "用户列表", columns, users)
|
||||||
|
func (e *Excel) ExportToFile(filePath string, 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()
|
||||||
|
} else {
|
||||||
|
// 处理结构体切片
|
||||||
|
rows, err = e.convertDataToRows(data, columns)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("failed to convert data to rows: %w", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 写入数据行
|
||||||
|
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)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 保存文件
|
||||||
|
return e.file.SaveAs(filePath)
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetFile 获取Excel文件对象(高级功能时使用)
|
||||||
|
// 返回excelize.File对象,可用于高级操作
|
||||||
|
//
|
||||||
|
// ℹ️ 推荐使用黑盒方法:
|
||||||
|
// - ExportToWriter():导出到Writer
|
||||||
|
// - ExportToFile():导出到文件
|
||||||
|
//
|
||||||
|
// 仅在需要使用高级功能时获取对象:
|
||||||
|
// - 多工作表操作
|
||||||
|
// - 自定义样式
|
||||||
|
// - 图表、公式等高级功能
|
||||||
|
//
|
||||||
|
// 示例(常用操作,推荐):
|
||||||
|
//
|
||||||
|
// excel := excel.NewExcel()
|
||||||
|
// excel.ExportToFile("users.xlsx", "用户列表", 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 将数据转换为行数据
|
||||||
|
func (e *Excel) convertDataToRows(data interface{}, columns []ExportColumn) ([][]interface{}, error) {
|
||||||
|
// 使用反射处理数据
|
||||||
|
val := reflect.ValueOf(data)
|
||||||
|
if val.Kind() == reflect.Ptr {
|
||||||
|
val = val.Elem()
|
||||||
|
}
|
||||||
|
|
||||||
|
if val.Kind() != reflect.Slice {
|
||||||
|
return nil, fmt.Errorf("data must be a slice")
|
||||||
|
}
|
||||||
|
|
||||||
|
rows := make([][]interface{}, 0, val.Len())
|
||||||
|
|
||||||
|
for i := 0; i < val.Len(); i++ {
|
||||||
|
item := val.Index(i)
|
||||||
|
if item.Kind() == reflect.Ptr {
|
||||||
|
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)
|
||||||
@@ -5,11 +5,14 @@ import (
|
|||||||
"fmt"
|
"fmt"
|
||||||
"io"
|
"io"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"git.toowon.com/jimmy/go-common/config"
|
"git.toowon.com/jimmy/go-common/config"
|
||||||
"git.toowon.com/jimmy/go-common/email"
|
"git.toowon.com/jimmy/go-common/email"
|
||||||
|
"git.toowon.com/jimmy/go-common/excel"
|
||||||
commonhttp "git.toowon.com/jimmy/go-common/http"
|
commonhttp "git.toowon.com/jimmy/go-common/http"
|
||||||
|
"git.toowon.com/jimmy/go-common/i18n"
|
||||||
"git.toowon.com/jimmy/go-common/logger"
|
"git.toowon.com/jimmy/go-common/logger"
|
||||||
"git.toowon.com/jimmy/go-common/middleware"
|
"git.toowon.com/jimmy/go-common/middleware"
|
||||||
"git.toowon.com/jimmy/go-common/migration"
|
"git.toowon.com/jimmy/go-common/migration"
|
||||||
@@ -118,6 +121,8 @@ type Factory struct {
|
|||||||
sms *sms.SMS // 短信客户端(延迟初始化)
|
sms *sms.SMS // 短信客户端(延迟初始化)
|
||||||
db *gorm.DB // 数据库连接(延迟初始化)
|
db *gorm.DB // 数据库连接(延迟初始化)
|
||||||
redis *redis.Client // Redis客户端(延迟初始化)
|
redis *redis.Client // Redis客户端(延迟初始化)
|
||||||
|
i18n *i18n.I18n // 国际化工具(延迟初始化)
|
||||||
|
excel *excel.Excel // Excel导出器(延迟初始化)
|
||||||
}
|
}
|
||||||
|
|
||||||
// NewFactory 创建工厂实例
|
// NewFactory 创建工厂实例
|
||||||
@@ -774,7 +779,10 @@ func (f *Factory) GetMiddlewareChain() *middleware.Chain {
|
|||||||
middlewares = append(middlewares, middleware.CORS(corsConfig))
|
middlewares = append(middlewares, middleware.CORS(corsConfig))
|
||||||
}
|
}
|
||||||
|
|
||||||
// 5. Timezone 中间件(必需,处理时区)
|
// 5. Language 中间件(必需,处理语言)
|
||||||
|
middlewares = append(middlewares, middleware.Language)
|
||||||
|
|
||||||
|
// 6. Timezone 中间件(必需,处理时区)
|
||||||
middlewares = append(middlewares, middleware.Timezone)
|
middlewares = append(middlewares, middleware.Timezone)
|
||||||
|
|
||||||
return middleware.NewChain(middlewares...)
|
return middleware.NewChain(middlewares...)
|
||||||
@@ -911,10 +919,69 @@ func (f *Factory) SuccessPage(w http.ResponseWriter, list interface{}, total int
|
|||||||
|
|
||||||
// Error 错误响应(黑盒模式,推荐使用)
|
// Error 错误响应(黑盒模式,推荐使用)
|
||||||
// w: ResponseWriter
|
// w: ResponseWriter
|
||||||
// code: 业务错误码,非0表示业务错误
|
// r: HTTP请求(用于获取语言信息和i18n处理)
|
||||||
// message: 错误消息
|
// code: 业务错误码(如果message是消息代码,此参数会被语言文件中的code覆盖)
|
||||||
func (f *Factory) Error(w http.ResponseWriter, code int, message string) {
|
// message: 错误消息或消息代码(如果i18n已初始化且message是消息代码格式,会自动获取国际化消息和业务code)
|
||||||
commonhttp.Error(w, code, message)
|
// args: 可选参数,用于格式化消息(类似 fmt.Sprintf,仅在message是消息代码时使用)
|
||||||
|
//
|
||||||
|
// 使用逻辑:
|
||||||
|
// 1. 如果i18n已初始化,且message看起来是消息代码(包含点号,如 "user.not_found"),
|
||||||
|
// 则从请求context中获取语言,并尝试从语言文件中获取国际化消息和业务code
|
||||||
|
// 2. 如果获取到国际化消息,使用语言文件中的code作为响应code,使用国际化消息作为响应message
|
||||||
|
// 3. 如果未获取到或i18n未初始化,使用传入的code和message
|
||||||
|
//
|
||||||
|
// 示例:
|
||||||
|
//
|
||||||
|
// // 方式1:直接传入消息代码(推荐,自动国际化)
|
||||||
|
// fac.Error(w, r, 0, "user.not_found")
|
||||||
|
// // 如果请求语言是 zh-CN,且语言文件中 "user.not_found" 的 code 是 1001,
|
||||||
|
// // 返回: {"code": 1001, "message": "用户不存在"}
|
||||||
|
// // 如果请求语言是 en-US,返回: {"code": 1001, "message": "User not found"}
|
||||||
|
//
|
||||||
|
// // 方式2:带参数的消息代码
|
||||||
|
// fac.Error(w, r, 0, "user.welcome", "Alice")
|
||||||
|
// // 如果消息内容是 "欢迎,%s",返回: {"code": 0, "message": "欢迎,Alice"}
|
||||||
|
//
|
||||||
|
// // 方式3:直接传入消息文本(不使用国际化)
|
||||||
|
// fac.Error(w, r, 500, "系统错误")
|
||||||
|
// // 返回: {"code": 500, "message": "系统错误"}
|
||||||
|
func (f *Factory) Error(w http.ResponseWriter, r *http.Request, code int, message string, args ...interface{}) {
|
||||||
|
// 判断message是否是消息代码(简单判断:包含点号)
|
||||||
|
isMessageCode := strings.Contains(message, ".")
|
||||||
|
|
||||||
|
var finalCode int
|
||||||
|
var finalMessage string
|
||||||
|
|
||||||
|
if isMessageCode {
|
||||||
|
// 尝试从i18n获取国际化消息和业务code
|
||||||
|
if i, err := f.getI18n(); err == nil {
|
||||||
|
// i18n已初始化,获取语言并查找消息
|
||||||
|
lang := f.GetLanguage(r)
|
||||||
|
if lang == "" {
|
||||||
|
lang = i.GetDefaultLang()
|
||||||
|
}
|
||||||
|
msgInfo := i.GetMessageInfo(lang, message, args...)
|
||||||
|
// 如果获取到了国际化消息(不是返回code本身),使用国际化消息和业务code
|
||||||
|
if msgInfo.Message != message {
|
||||||
|
finalCode = msgInfo.Code
|
||||||
|
finalMessage = msgInfo.Message
|
||||||
|
} else {
|
||||||
|
// 消息代码不存在,使用传入的code和消息代码作为消息
|
||||||
|
finalCode = code
|
||||||
|
finalMessage = message
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// i18n未初始化,使用传入的code和消息代码作为消息
|
||||||
|
finalCode = code
|
||||||
|
finalMessage = message
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// 不是消息代码格式,使用传入的code和消息
|
||||||
|
finalCode = code
|
||||||
|
finalMessage = message
|
||||||
|
}
|
||||||
|
|
||||||
|
commonhttp.Error(w, finalCode, finalMessage)
|
||||||
}
|
}
|
||||||
|
|
||||||
// SystemError 系统错误响应(返回HTTP 500)(黑盒模式,推荐使用)
|
// SystemError 系统错误响应(返回HTTP 500)(黑盒模式,推荐使用)
|
||||||
@@ -927,7 +994,7 @@ func (f *Factory) SystemError(w http.ResponseWriter, message string) {
|
|||||||
// ========== HTTP请求解析方法(黑盒模式,推荐使用) ==========
|
// ========== HTTP请求解析方法(黑盒模式,推荐使用) ==========
|
||||||
//
|
//
|
||||||
// 这些方法直接调用 http 包的公共方法,保持低耦合。
|
// 这些方法直接调用 http 包的公共方法,保持低耦合。
|
||||||
// 推荐直接使用 factory.ParseJSON()、factory.GetQuery() 等方法。
|
// 推荐直接使用 factory.ParseJSON()、factory.ConvertInt() 等方法。
|
||||||
|
|
||||||
// ParseJSON 解析JSON请求体(黑盒模式,推荐使用)
|
// ParseJSON 解析JSON请求体(黑盒模式,推荐使用)
|
||||||
// r: HTTP请求
|
// r: HTTP请求
|
||||||
@@ -960,84 +1027,46 @@ func (f *Factory) ParsePaginationRequest(r *http.Request) *PaginationRequest {
|
|||||||
return commonhttp.ParsePaginationRequest(r)
|
return commonhttp.ParsePaginationRequest(r)
|
||||||
}
|
}
|
||||||
|
|
||||||
// GetQuery 获取查询参数(字符串)(黑盒模式,推荐使用)
|
// ConvertInt 将字符串转换为int类型(黑盒模式,推荐使用)
|
||||||
// r: HTTP请求
|
// value: 待转换的字符串
|
||||||
// key: 参数名
|
// defaultValue: 转换失败或字符串为空时返回的默认值
|
||||||
// defaultValue: 默认值
|
func (f *Factory) ConvertInt(value string, defaultValue int) int {
|
||||||
func (f *Factory) GetQuery(r *http.Request, key, defaultValue string) string {
|
return tools.ConvertInt(value, defaultValue)
|
||||||
return commonhttp.GetQuery(r, key, defaultValue)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// GetQueryInt 获取整数查询参数(黑盒模式,推荐使用)
|
// ConvertInt64 将字符串转换为int64类型(黑盒模式,推荐使用)
|
||||||
// r: HTTP请求
|
// value: 待转换的字符串
|
||||||
// key: 参数名
|
// defaultValue: 转换失败或字符串为空时返回的默认值
|
||||||
// defaultValue: 默认值
|
func (f *Factory) ConvertInt64(value string, defaultValue int64) int64 {
|
||||||
func (f *Factory) GetQueryInt(r *http.Request, key string, defaultValue int) int {
|
return tools.ConvertInt64(value, defaultValue)
|
||||||
return commonhttp.GetQueryInt(r, key, defaultValue)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// GetQueryInt64 获取int64查询参数(黑盒模式,推荐使用)
|
// ConvertUint64 将字符串转换为uint64类型(黑盒模式,推荐使用)
|
||||||
// r: HTTP请求
|
// value: 待转换的字符串
|
||||||
// key: 参数名
|
// defaultValue: 转换失败或字符串为空时返回的默认值
|
||||||
// defaultValue: 默认值
|
func (f *Factory) ConvertUint64(value string, defaultValue uint64) uint64 {
|
||||||
func (f *Factory) GetQueryInt64(r *http.Request, key string, defaultValue int64) int64 {
|
return tools.ConvertUint64(value, defaultValue)
|
||||||
return commonhttp.GetQueryInt64(r, key, defaultValue)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// GetQueryBool 获取布尔查询参数(黑盒模式,推荐使用)
|
// ConvertUint32 将字符串转换为uint32类型(黑盒模式,推荐使用)
|
||||||
// r: HTTP请求
|
// value: 待转换的字符串
|
||||||
// key: 参数名
|
// defaultValue: 转换失败或字符串为空时返回的默认值
|
||||||
// defaultValue: 默认值
|
func (f *Factory) ConvertUint32(value string, defaultValue uint32) uint32 {
|
||||||
func (f *Factory) GetQueryBool(r *http.Request, key string, defaultValue bool) bool {
|
return tools.ConvertUint32(value, defaultValue)
|
||||||
return commonhttp.GetQueryBool(r, key, defaultValue)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// GetQueryFloat64 获取float64查询参数(黑盒模式,推荐使用)
|
// ConvertBool 将字符串转换为bool类型(黑盒模式,推荐使用)
|
||||||
// r: HTTP请求
|
// value: 待转换的字符串
|
||||||
// key: 参数名
|
// defaultValue: 转换失败或字符串为空时返回的默认值
|
||||||
// defaultValue: 默认值
|
func (f *Factory) ConvertBool(value string, defaultValue bool) bool {
|
||||||
func (f *Factory) GetQueryFloat64(r *http.Request, key string, defaultValue float64) float64 {
|
return tools.ConvertBool(value, defaultValue)
|
||||||
return commonhttp.GetQueryFloat64(r, key, defaultValue)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// GetFormValue 获取表单值(字符串)(黑盒模式,推荐使用)
|
// ConvertFloat64 将字符串转换为float64类型(黑盒模式,推荐使用)
|
||||||
// r: HTTP请求
|
// value: 待转换的字符串
|
||||||
// key: 参数名
|
// defaultValue: 转换失败或字符串为空时返回的默认值
|
||||||
// defaultValue: 默认值
|
func (f *Factory) ConvertFloat64(value string, defaultValue float64) float64 {
|
||||||
func (f *Factory) GetFormValue(r *http.Request, key, defaultValue string) string {
|
return tools.ConvertFloat64(value, defaultValue)
|
||||||
return commonhttp.GetFormValue(r, key, defaultValue)
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetFormInt 获取表单整数(黑盒模式,推荐使用)
|
|
||||||
// r: HTTP请求
|
|
||||||
// key: 参数名
|
|
||||||
// defaultValue: 默认值
|
|
||||||
func (f *Factory) GetFormInt(r *http.Request, key string, defaultValue int) int {
|
|
||||||
return commonhttp.GetFormInt(r, key, defaultValue)
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetFormInt64 获取表单int64(黑盒模式,推荐使用)
|
|
||||||
// r: HTTP请求
|
|
||||||
// key: 参数名
|
|
||||||
// defaultValue: 默认值
|
|
||||||
func (f *Factory) GetFormInt64(r *http.Request, key string, defaultValue int64) int64 {
|
|
||||||
return commonhttp.GetFormInt64(r, key, defaultValue)
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetFormBool 获取表单布尔值(黑盒模式,推荐使用)
|
|
||||||
// r: HTTP请求
|
|
||||||
// key: 参数名
|
|
||||||
// defaultValue: 默认值
|
|
||||||
func (f *Factory) GetFormBool(r *http.Request, key string, defaultValue bool) bool {
|
|
||||||
return commonhttp.GetFormBool(r, key, defaultValue)
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetHeader 获取请求头(黑盒模式,推荐使用)
|
|
||||||
// r: HTTP请求
|
|
||||||
// key: 请求头名称
|
|
||||||
// defaultValue: 默认值
|
|
||||||
func (f *Factory) GetHeader(r *http.Request, key, defaultValue string) string {
|
|
||||||
return commonhttp.GetHeader(r, key, defaultValue)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// GetTimezone 从请求的context中获取时区(黑盒模式,推荐使用)
|
// GetTimezone 从请求的context中获取时区(黑盒模式,推荐使用)
|
||||||
@@ -1048,6 +1077,14 @@ func (f *Factory) GetTimezone(r *http.Request) string {
|
|||||||
return commonhttp.GetTimezone(r)
|
return commonhttp.GetTimezone(r)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// GetLanguage 从请求的context中获取语言(黑盒模式,推荐使用)
|
||||||
|
// r: HTTP请求
|
||||||
|
// 如果使用了middleware.Language中间件,可以从context中获取语言信息
|
||||||
|
// 如果未设置,返回默认语言 zh-CN
|
||||||
|
func (f *Factory) GetLanguage(r *http.Request) string {
|
||||||
|
return commonhttp.GetLanguage(r)
|
||||||
|
}
|
||||||
|
|
||||||
// ========== Tools工具方法(黑盒模式,推荐使用) ==========
|
// ========== Tools工具方法(黑盒模式,推荐使用) ==========
|
||||||
//
|
//
|
||||||
// 这些方法直接调用 tools 包的公共方法,保持低耦合。
|
// 这些方法直接调用 tools 包的公共方法,保持低耦合。
|
||||||
@@ -1393,3 +1430,234 @@ func (f *Factory) GenerateRefundNo() string {
|
|||||||
func (f *Factory) GenerateTransferNo() string {
|
func (f *Factory) GenerateTransferNo() string {
|
||||||
return tools.GenerateTransferNo()
|
return tools.GenerateTransferNo()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ========== I18n 国际化工具(黑盒模式,推荐使用) ==========
|
||||||
|
//
|
||||||
|
// 这些方法提供多语言内容管理功能,支持从文件加载语言内容,通过语言代码和消息代码获取对应语言的内容。
|
||||||
|
|
||||||
|
// getI18n 获取国际化工具实例(内部方法,延迟初始化)
|
||||||
|
func (f *Factory) getI18n() (*i18n.I18n, error) {
|
||||||
|
if f.i18n != nil {
|
||||||
|
return f.i18n, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// 如果没有配置,返回错误
|
||||||
|
return nil, fmt.Errorf("i18n not initialized, please call InitI18n first")
|
||||||
|
}
|
||||||
|
|
||||||
|
// InitI18n 初始化国际化工具(黑盒模式,推荐使用)
|
||||||
|
// defaultLang: 默认语言代码(如 "zh-CN", "en-US")
|
||||||
|
// 初始化后可以调用 LoadI18nFromDir 或 LoadI18nFromFile 加载语言文件
|
||||||
|
//
|
||||||
|
// 示例:
|
||||||
|
//
|
||||||
|
// fac, _ := factory.NewFactoryFromFile("config.json")
|
||||||
|
// fac.InitI18n("zh-CN")
|
||||||
|
// fac.LoadI18nFromDir("locales")
|
||||||
|
func (f *Factory) InitI18n(defaultLang string) {
|
||||||
|
f.i18n = i18n.NewI18n(defaultLang)
|
||||||
|
}
|
||||||
|
|
||||||
|
// LoadI18nFromDir 从目录加载多个语言文件(黑盒模式,推荐使用)
|
||||||
|
// dirPath: 语言文件目录路径
|
||||||
|
// 文件命名规则:{语言代码}.json(如 zh-CN.json, en-US.json)
|
||||||
|
//
|
||||||
|
// 文件格式示例(zh-CN.json):
|
||||||
|
//
|
||||||
|
// {
|
||||||
|
// "user.not_found": "用户不存在",
|
||||||
|
// "user.login_success": "登录成功",
|
||||||
|
// "user.welcome": "欢迎,%s"
|
||||||
|
// }
|
||||||
|
//
|
||||||
|
// 示例:
|
||||||
|
//
|
||||||
|
// fac.InitI18n("zh-CN")
|
||||||
|
// fac.LoadI18nFromDir("locales")
|
||||||
|
func (f *Factory) LoadI18nFromDir(dirPath string) error {
|
||||||
|
i, err := f.getI18n()
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return i.LoadFromDir(dirPath)
|
||||||
|
}
|
||||||
|
|
||||||
|
// LoadI18nFromFile 从单个语言文件加载内容(黑盒模式,推荐使用)
|
||||||
|
// filePath: 语言文件路径(JSON格式)
|
||||||
|
// lang: 语言代码(如 "zh-CN", "en-US")
|
||||||
|
//
|
||||||
|
// 示例:
|
||||||
|
//
|
||||||
|
// fac.InitI18n("zh-CN")
|
||||||
|
// fac.LoadI18nFromFile("locales/zh-CN.json", "zh-CN")
|
||||||
|
// fac.LoadI18nFromFile("locales/en-US.json", "en-US")
|
||||||
|
func (f *Factory) LoadI18nFromFile(filePath, lang string) error {
|
||||||
|
i, err := f.getI18n()
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return i.LoadFromFile(filePath, lang)
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetMessage 获取指定语言和代码的消息内容(黑盒模式,推荐使用)
|
||||||
|
// lang: 语言代码(如 "zh-CN", "en-US")
|
||||||
|
// code: 消息代码(如 "user.not_found")
|
||||||
|
// args: 可选参数,用于格式化消息(类似 fmt.Sprintf)
|
||||||
|
//
|
||||||
|
// 返回逻辑:
|
||||||
|
// 1. 如果指定语言存在该code,返回对应内容
|
||||||
|
// 2. 如果指定语言不存在,尝试使用默认语言
|
||||||
|
// 3. 如果默认语言也不存在,返回code本身(作为fallback)
|
||||||
|
//
|
||||||
|
// 示例:
|
||||||
|
//
|
||||||
|
// // 简单消息
|
||||||
|
// msg := fac.GetMessage("zh-CN", "user.not_found")
|
||||||
|
// // 返回: "用户不存在"
|
||||||
|
//
|
||||||
|
// // 带参数的消息
|
||||||
|
// msg := fac.GetMessage("zh-CN", "user.welcome", "Alice")
|
||||||
|
// // 如果消息内容是 "欢迎,%s",返回: "欢迎,Alice"
|
||||||
|
func (f *Factory) GetMessage(lang, code string, args ...interface{}) string {
|
||||||
|
i, err := f.getI18n()
|
||||||
|
if err != nil {
|
||||||
|
// 如果未初始化,返回code本身
|
||||||
|
return code
|
||||||
|
}
|
||||||
|
return i.GetMessage(lang, code, args...)
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetI18n 获取国际化工具对象(高级功能时使用)
|
||||||
|
// 返回已初始化的国际化工具对象
|
||||||
|
//
|
||||||
|
// ℹ️ 推荐使用黑盒方法:
|
||||||
|
// - GetMessage():获取消息内容
|
||||||
|
// - LoadI18nFromDir():加载语言文件目录
|
||||||
|
// - LoadI18nFromFile():加载单个语言文件
|
||||||
|
//
|
||||||
|
// 仅在需要使用高级功能时获取对象:
|
||||||
|
// - HasLang():检查语言是否存在
|
||||||
|
// - GetSupportedLangs():获取所有支持的语言
|
||||||
|
// - ReloadFromFile():重新加载语言文件
|
||||||
|
// - SetDefaultLang():动态设置默认语言
|
||||||
|
//
|
||||||
|
// 示例(常用操作,推荐):
|
||||||
|
//
|
||||||
|
// fac.InitI18n("zh-CN")
|
||||||
|
// fac.LoadI18nFromDir("locales")
|
||||||
|
// msg := fac.GetMessage("zh-CN", "user.not_found")
|
||||||
|
//
|
||||||
|
// 示例(高级功能):
|
||||||
|
//
|
||||||
|
// i18n, _ := fac.GetI18n()
|
||||||
|
// langs := i18n.GetSupportedLangs()
|
||||||
|
// hasLang := i18n.HasLang("en-US")
|
||||||
|
func (f *Factory) GetI18n() (*i18n.I18n, error) {
|
||||||
|
return f.getI18n()
|
||||||
|
}
|
||||||
|
|
||||||
|
// ========== Excel 导出工具(黑盒模式,推荐使用) ==========
|
||||||
|
//
|
||||||
|
// 这些方法提供数据导出到Excel的功能,支持结构体切片和自定义数据格式。
|
||||||
|
|
||||||
|
// getExcelClient 获取Excel导出器实例(内部方法,延迟初始化)
|
||||||
|
func (f *Factory) getExcelClient() (*excel.Excel, error) {
|
||||||
|
if f.excel != nil {
|
||||||
|
return f.excel, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
f.excel = excel.NewExcel()
|
||||||
|
return f.excel, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetExcel 获取Excel导出器对象(高级功能时使用)
|
||||||
|
// 返回已初始化的Excel导出器对象
|
||||||
|
//
|
||||||
|
// ℹ️ 推荐使用黑盒方法:
|
||||||
|
// - ExportToExcel():导出到Writer
|
||||||
|
// - ExportToExcelFile():导出到文件
|
||||||
|
//
|
||||||
|
// 仅在需要使用高级功能时获取对象:
|
||||||
|
// - 多工作表操作
|
||||||
|
// - 自定义样式
|
||||||
|
// - 图表、公式等高级功能
|
||||||
|
//
|
||||||
|
// 示例(常用操作,推荐):
|
||||||
|
//
|
||||||
|
// fac.ExportToExcel(w, "用户列表", columns, users)
|
||||||
|
//
|
||||||
|
// 示例(高级功能):
|
||||||
|
//
|
||||||
|
// excel, _ := fac.GetExcel()
|
||||||
|
// file := excel.GetFile()
|
||||||
|
// file.NewSheet("Sheet2")
|
||||||
|
func (f *Factory) GetExcel() (*excel.Excel, error) {
|
||||||
|
return f.getExcelClient()
|
||||||
|
}
|
||||||
|
|
||||||
|
// ExportColumn Excel导出列定义(暴露给外部项目使用)
|
||||||
|
// 外部项目可以直接使用 factory.ExportColumn 创建列定义
|
||||||
|
type ExportColumn = excel.ExportColumn
|
||||||
|
|
||||||
|
// ExportToExcel 导出数据到Writer(黑盒模式,推荐使用)
|
||||||
|
// w: Writer对象(如http.ResponseWriter)
|
||||||
|
// 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 := []factory.ExportColumn{
|
||||||
|
// {Header: "ID", Field: "ID"},
|
||||||
|
// {Header: "姓名", Field: "Name"},
|
||||||
|
// {Header: "邮箱", Field: "Email"},
|
||||||
|
// }
|
||||||
|
//
|
||||||
|
// fac.ExportToExcel(w, "用户列表", columns, users)
|
||||||
|
//
|
||||||
|
// 示例2:使用格式化函数
|
||||||
|
//
|
||||||
|
// columns := []factory.ExportColumn{
|
||||||
|
// {Header: "ID", Field: "ID"},
|
||||||
|
// {Header: "姓名", Field: "Name"},
|
||||||
|
// {Header: "创建时间", Field: "CreatedAt", Format: excel.FormatDateTimeDefault},
|
||||||
|
// }
|
||||||
|
//
|
||||||
|
// fac.ExportToExcel(w, "用户列表", columns, users)
|
||||||
|
func (f *Factory) ExportToExcel(w io.Writer, sheetName string, columns []ExportColumn, data interface{}) error {
|
||||||
|
e, err := f.getExcelClient()
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return e.ExportToWriter(w, sheetName, columns, data)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ExportToExcelFile 导出数据到文件(黑盒模式,推荐使用)
|
||||||
|
// filePath: 文件路径
|
||||||
|
// sheetName: 工作表名称(可选,默认为"Sheet1")
|
||||||
|
// columns: 列定义
|
||||||
|
// data: 数据列表
|
||||||
|
// 返回错误信息
|
||||||
|
//
|
||||||
|
// 示例:
|
||||||
|
//
|
||||||
|
// fac.ExportToExcelFile("users.xlsx", "用户列表", columns, users)
|
||||||
|
func (f *Factory) ExportToExcelFile(filePath string, sheetName string, columns []ExportColumn, data interface{}) error {
|
||||||
|
e, err := f.getExcelClient()
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return e.ExportToFile(filePath, sheetName, columns, data)
|
||||||
|
}
|
||||||
|
|||||||
18
go.mod
18
go.mod
@@ -1,12 +1,14 @@
|
|||||||
module git.toowon.com/jimmy/go-common
|
module git.toowon.com/jimmy/go-common
|
||||||
|
|
||||||
go 1.23.0
|
go 1.24.0
|
||||||
|
|
||||||
toolchain go1.24.10
|
toolchain go1.24.10
|
||||||
|
|
||||||
require (
|
require (
|
||||||
github.com/minio/minio-go/v7 v7.0.97
|
github.com/minio/minio-go/v7 v7.0.97
|
||||||
github.com/redis/go-redis/v9 v9.17.1
|
github.com/redis/go-redis/v9 v9.17.1
|
||||||
|
github.com/xuri/excelize/v2 v2.10.0
|
||||||
|
golang.org/x/crypto v0.43.0
|
||||||
gorm.io/driver/mysql v1.5.2
|
gorm.io/driver/mysql v1.5.2
|
||||||
gorm.io/driver/postgres v1.6.0
|
gorm.io/driver/postgres v1.6.0
|
||||||
gorm.io/driver/sqlite v1.6.0
|
gorm.io/driver/sqlite v1.6.0
|
||||||
@@ -34,13 +36,17 @@ require (
|
|||||||
github.com/minio/crc64nvme v1.1.0 // indirect
|
github.com/minio/crc64nvme v1.1.0 // indirect
|
||||||
github.com/minio/md5-simd v1.1.2 // indirect
|
github.com/minio/md5-simd v1.1.2 // indirect
|
||||||
github.com/philhofer/fwd v1.2.0 // indirect
|
github.com/philhofer/fwd v1.2.0 // indirect
|
||||||
|
github.com/richardlehane/mscfb v1.0.4 // indirect
|
||||||
|
github.com/richardlehane/msoleps v1.0.4 // indirect
|
||||||
github.com/rogpeppe/go-internal v1.14.1 // indirect
|
github.com/rogpeppe/go-internal v1.14.1 // indirect
|
||||||
github.com/rs/xid v1.6.0 // indirect
|
github.com/rs/xid v1.6.0 // indirect
|
||||||
|
github.com/tiendc/go-deepcopy v1.7.1 // indirect
|
||||||
github.com/tinylib/msgp v1.3.0 // indirect
|
github.com/tinylib/msgp v1.3.0 // indirect
|
||||||
golang.org/x/crypto v0.36.0 // indirect
|
github.com/xuri/efp v0.0.1 // indirect
|
||||||
golang.org/x/net v0.38.0 // indirect
|
github.com/xuri/nfp v0.0.2-0.20250530014748-2ddeb826f9a9 // indirect
|
||||||
golang.org/x/sync v0.15.0 // indirect
|
golang.org/x/net v0.46.0 // indirect
|
||||||
golang.org/x/sys v0.34.0 // indirect
|
golang.org/x/sync v0.17.0 // indirect
|
||||||
golang.org/x/text v0.26.0 // indirect
|
golang.org/x/sys v0.37.0 // indirect
|
||||||
|
golang.org/x/text v0.30.0 // indirect
|
||||||
gopkg.in/yaml.v3 v3.0.1 // indirect
|
gopkg.in/yaml.v3 v3.0.1 // indirect
|
||||||
)
|
)
|
||||||
|
|||||||
39
go.sum
39
go.sum
@@ -56,6 +56,11 @@ github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZb
|
|||||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||||
github.com/redis/go-redis/v9 v9.17.1 h1:7tl732FjYPRT9H9aNfyTwKg9iTETjWjGKEJ2t/5iWTs=
|
github.com/redis/go-redis/v9 v9.17.1 h1:7tl732FjYPRT9H9aNfyTwKg9iTETjWjGKEJ2t/5iWTs=
|
||||||
github.com/redis/go-redis/v9 v9.17.1/go.mod h1:u410H11HMLoB+TP67dz8rL9s6QW2j76l0//kSOd3370=
|
github.com/redis/go-redis/v9 v9.17.1/go.mod h1:u410H11HMLoB+TP67dz8rL9s6QW2j76l0//kSOd3370=
|
||||||
|
github.com/richardlehane/mscfb v1.0.4 h1:WULscsljNPConisD5hR0+OyZjwK46Pfyr6mPu5ZawpM=
|
||||||
|
github.com/richardlehane/mscfb v1.0.4/go.mod h1:YzVpcZg9czvAuhk9T+a3avCpcFPMUWm7gK3DypaEsUk=
|
||||||
|
github.com/richardlehane/msoleps v1.0.1/go.mod h1:BWev5JBpU9Ko2WAgmZEuiz4/u3ZYTKbjLycmwiWUfWg=
|
||||||
|
github.com/richardlehane/msoleps v1.0.4 h1:WuESlvhX3gH2IHcd8UqyCuFY5yiq/GR/yqaSM/9/g00=
|
||||||
|
github.com/richardlehane/msoleps v1.0.4/go.mod h1:BWev5JBpU9Ko2WAgmZEuiz4/u3ZYTKbjLycmwiWUfWg=
|
||||||
github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ=
|
github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ=
|
||||||
github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc=
|
github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc=
|
||||||
github.com/rs/xid v1.6.0 h1:fV591PaemRlL6JfRxGDEPl69wICngIQ3shQtzfy2gxU=
|
github.com/rs/xid v1.6.0 h1:fV591PaemRlL6JfRxGDEPl69wICngIQ3shQtzfy2gxU=
|
||||||
@@ -63,20 +68,30 @@ github.com/rs/xid v1.6.0/go.mod h1:7XoLgs4eV+QndskICGsho+ADou8ySMSjJKDIan90Nz0=
|
|||||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||||
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
|
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
|
||||||
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||||
github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg=
|
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
|
||||||
github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
|
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
|
||||||
|
github.com/tiendc/go-deepcopy v1.7.1 h1:LnubftI6nYaaMOcaz0LphzwraqN8jiWTwm416sitff4=
|
||||||
|
github.com/tiendc/go-deepcopy v1.7.1/go.mod h1:4bKjNC2r7boYOkD2IOuZpYjmlDdzjbpTRyCx+goBCJQ=
|
||||||
github.com/tinylib/msgp v1.3.0 h1:ULuf7GPooDaIlbyvgAxBV/FI7ynli6LZ1/nVUNu+0ww=
|
github.com/tinylib/msgp v1.3.0 h1:ULuf7GPooDaIlbyvgAxBV/FI7ynli6LZ1/nVUNu+0ww=
|
||||||
github.com/tinylib/msgp v1.3.0/go.mod h1:ykjzy2wzgrlvpDCRc4LA8UXy6D8bzMSuAF3WD57Gok0=
|
github.com/tinylib/msgp v1.3.0/go.mod h1:ykjzy2wzgrlvpDCRc4LA8UXy6D8bzMSuAF3WD57Gok0=
|
||||||
golang.org/x/crypto v0.36.0 h1:AnAEvhDddvBdpY+uR+MyHmuZzzNqXSe/GvuDeob5L34=
|
github.com/xuri/efp v0.0.1 h1:fws5Rv3myXyYni8uwj2qKjVaRP30PdjeYe2Y6FDsCL8=
|
||||||
golang.org/x/crypto v0.36.0/go.mod h1:Y4J0ReaxCR1IMaabaSMugxJES1EpwhBHhv2bDHklZvc=
|
github.com/xuri/efp v0.0.1/go.mod h1:ybY/Jr0T0GTCnYjKqmdwxyxn2BQf2RcQIIvex5QldPI=
|
||||||
golang.org/x/net v0.38.0 h1:vRMAPTMaeGqVhG5QyLJHqNDwecKTomGeqbnfZyKlBI8=
|
github.com/xuri/excelize/v2 v2.10.0 h1:8aKsP7JD39iKLc6dH5Tw3dgV3sPRh8uRVXu/fMstfW4=
|
||||||
golang.org/x/net v0.38.0/go.mod h1:ivrbrMbzFq5J41QOQh0siUuly180yBYtLp+CKbEaFx8=
|
github.com/xuri/excelize/v2 v2.10.0/go.mod h1:SC5TzhQkaOsTWpANfm+7bJCldzcnU/jrhqkTi/iBHBU=
|
||||||
golang.org/x/sync v0.15.0 h1:KWH3jNZsfyT6xfAfKiz6MRNmd46ByHDYaZ7KSkCtdW8=
|
github.com/xuri/nfp v0.0.2-0.20250530014748-2ddeb826f9a9 h1:+C0TIdyyYmzadGaL/HBLbf3WdLgC29pgyhTjAT/0nuE=
|
||||||
golang.org/x/sync v0.15.0/go.mod h1:1dzgHSNfp02xaA81J2MS99Qcpr2w7fw1gpm99rleRqA=
|
github.com/xuri/nfp v0.0.2-0.20250530014748-2ddeb826f9a9/go.mod h1:WwHg+CVyzlv/TX9xqBFXEZAuxOPxn2k1GNHwG41IIUQ=
|
||||||
golang.org/x/sys v0.34.0 h1:H5Y5sJ2L2JRdyv7ROF1he/lPdvFsd0mJHFw2ThKHxLA=
|
golang.org/x/crypto v0.43.0 h1:dduJYIi3A3KOfdGOHX8AVZ/jGiyPa3IbBozJ5kNuE04=
|
||||||
golang.org/x/sys v0.34.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=
|
golang.org/x/crypto v0.43.0/go.mod h1:BFbav4mRNlXJL4wNeejLpWxB7wMbc79PdRGhWKncxR0=
|
||||||
golang.org/x/text v0.26.0 h1:P42AVeLghgTYr4+xUnTRKDMqpar+PtX7KWuNQL21L8M=
|
golang.org/x/image v0.25.0 h1:Y6uW6rH1y5y/LK1J8BPWZtr6yZ7hrsy6hFrXjgsc2fQ=
|
||||||
golang.org/x/text v0.26.0/go.mod h1:QK15LZJUUQVJxhz7wXgxSy/CJaTFjd0G+YLonydOVQA=
|
golang.org/x/image v0.25.0/go.mod h1:tCAmOEGthTtkalusGp1g3xa2gke8J6c2N565dTyl9Rs=
|
||||||
|
golang.org/x/net v0.46.0 h1:giFlY12I07fugqwPuWJi68oOnpfqFnJIJzaIIm2JVV4=
|
||||||
|
golang.org/x/net v0.46.0/go.mod h1:Q9BGdFy1y4nkUwiLvT5qtyhAnEHgnQ/zd8PfU6nc210=
|
||||||
|
golang.org/x/sync v0.17.0 h1:l60nONMj9l5drqw6jlhIELNv9I0A4OFgRsG9k2oT9Ug=
|
||||||
|
golang.org/x/sync v0.17.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI=
|
||||||
|
golang.org/x/sys v0.37.0 h1:fdNQudmxPjkdUTPnLn5mdQv7Zwvbvpaxqs831goi9kQ=
|
||||||
|
golang.org/x/sys v0.37.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
|
||||||
|
golang.org/x/text v0.30.0 h1:yznKA/E9zq54KzlzBEAWn1NXSQ8DIp/NYMy88xJjl4k=
|
||||||
|
golang.org/x/text v0.30.0/go.mod h1:yDdHFIX9t+tORqspjENWgzaCVXgk0yYnYuSZ8UzzBVM=
|
||||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||||
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
|
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
|
||||||
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=
|
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=
|
||||||
|
|||||||
241
http/request.go
241
http/request.go
@@ -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/middleware"
|
||||||
|
"git.toowon.com/jimmy/go-common/tools"
|
||||||
)
|
)
|
||||||
|
|
||||||
// getQueryInt 获取整数查询参数(内部方法,供ParsePaginationRequest使用)
|
|
||||||
func getQueryInt(r *http.Request, key string, defaultValue int) int {
|
|
||||||
value := r.URL.Query().Get(key)
|
|
||||||
if value == "" {
|
|
||||||
return defaultValue
|
|
||||||
}
|
|
||||||
|
|
||||||
intValue, err := strconv.Atoi(value)
|
|
||||||
if err != nil {
|
|
||||||
return defaultValue
|
|
||||||
}
|
|
||||||
|
|
||||||
return intValue
|
|
||||||
}
|
|
||||||
|
|
||||||
// getFormInt 获取表单整数(内部方法,供ParsePaginationRequest使用)
|
|
||||||
func getFormInt(r *http.Request, key string, defaultValue int) int {
|
|
||||||
value := r.FormValue(key)
|
|
||||||
if value == "" {
|
|
||||||
return defaultValue
|
|
||||||
}
|
|
||||||
|
|
||||||
intValue, err := strconv.Atoi(value)
|
|
||||||
if err != nil {
|
|
||||||
return defaultValue
|
|
||||||
}
|
|
||||||
|
|
||||||
return intValue
|
|
||||||
}
|
|
||||||
|
|
||||||
// PaginationRequest 分页请求结构
|
// PaginationRequest 分页请求结构
|
||||||
// 支持从JSON和form中解析分页参数
|
// 支持从JSON和form中解析分页参数
|
||||||
type PaginationRequest struct {
|
type PaginationRequest struct {
|
||||||
Page int `json:"page" form:"page"` // 页码,默认1
|
Page int `json:"page" form:"page"` // 页码,默认1
|
||||||
Size int `json:"size" form:"size"` // 每页数量(兼容旧版本)
|
PageSize int `json:"page_size" form:"page_size"` // 每页数量
|
||||||
PageSize int `json:"page_size" form:"page_size"` // 每页数量(推荐使用)
|
Keyword string `json:"keyword" form:"keyword"` // 关键字
|
||||||
}
|
}
|
||||||
|
|
||||||
// GetPage 获取页码,如果未设置则返回默认值1
|
// GetPage 获取页码,如果未设置则返回默认值1
|
||||||
@@ -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,168 +97,6 @@ func ParseJSON(r *http.Request, v interface{}) error {
|
|||||||
return json.Unmarshal(body, v)
|
return json.Unmarshal(body, v)
|
||||||
}
|
}
|
||||||
|
|
||||||
// GetQuery 获取查询参数(公共方法)
|
|
||||||
// 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中获取时区(公共方法)
|
// GetTimezone 从请求的context中获取时区(公共方法)
|
||||||
// r: HTTP请求
|
// r: HTTP请求
|
||||||
// 如果使用了middleware.Timezone中间件,可以从context中获取时区信息
|
// 如果使用了middleware.Timezone中间件,可以从context中获取时区信息
|
||||||
@@ -307,3 +104,11 @@ func GetHeader(r *http.Request, key, defaultValue string) string {
|
|||||||
func GetTimezone(r *http.Request) string {
|
func GetTimezone(r *http.Request) string {
|
||||||
return middleware.GetTimezoneFromContext(r.Context())
|
return middleware.GetTimezoneFromContext(r.Context())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// GetLanguage 从请求的context中获取语言(公共方法)
|
||||||
|
// r: HTTP请求
|
||||||
|
// 如果使用了middleware.Language中间件,可以从context中获取语言信息
|
||||||
|
// 如果未设置,返回默认语言 zh-CN
|
||||||
|
func GetLanguage(r *http.Request) string {
|
||||||
|
return middleware.GetLanguageFromContext(r.Context())
|
||||||
|
}
|
||||||
|
|||||||
286
i18n/i18n.go
Normal file
286
i18n/i18n.go
Normal file
@@ -0,0 +1,286 @@
|
|||||||
|
package i18n
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
|
)
|
||||||
|
|
||||||
|
// MessageInfo 消息信息结构
|
||||||
|
// 包含业务错误码和消息内容
|
||||||
|
type MessageInfo struct {
|
||||||
|
Code int `json:"code"` // 业务错误码
|
||||||
|
Message string `json:"message"` // 消息内容
|
||||||
|
}
|
||||||
|
|
||||||
|
// I18n 国际化工具
|
||||||
|
// 支持多语言内容管理,通过语言代码和消息代码获取对应语言的内容
|
||||||
|
type I18n struct {
|
||||||
|
messages map[string]map[string]MessageInfo // 存储格式:messages[语言][code] = MessageInfo
|
||||||
|
defaultLang string // 默认语言代码
|
||||||
|
mu sync.RWMutex // 读写锁,保证并发安全
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewI18n 创建国际化工具实例
|
||||||
|
// defaultLang: 默认语言代码(如 "zh-CN", "en-US"),当指定语言不存在时使用
|
||||||
|
func NewI18n(defaultLang string) *I18n {
|
||||||
|
return &I18n{
|
||||||
|
messages: make(map[string]map[string]MessageInfo),
|
||||||
|
defaultLang: defaultLang,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// LoadFromFile 从单个语言文件加载内容
|
||||||
|
// filePath: 语言文件路径(JSON格式)
|
||||||
|
// lang: 语言代码(如 "zh-CN", "en-US")
|
||||||
|
//
|
||||||
|
// 文件格式示例(zh-CN.json):
|
||||||
|
//
|
||||||
|
// {
|
||||||
|
// "user.not_found": {
|
||||||
|
// "code": 1001,
|
||||||
|
// "message": "用户不存在"
|
||||||
|
// },
|
||||||
|
// "user.login_success": {
|
||||||
|
// "code": 0,
|
||||||
|
// "message": "登录成功"
|
||||||
|
// },
|
||||||
|
// "user.welcome": {
|
||||||
|
// "code": 0,
|
||||||
|
// "message": "欢迎,%s"
|
||||||
|
// }
|
||||||
|
// }
|
||||||
|
func (i *I18n) LoadFromFile(filePath, lang string) error {
|
||||||
|
data, err := os.ReadFile(filePath)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("failed to read file %s: %w", filePath, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
var messages map[string]MessageInfo
|
||||||
|
if err := json.Unmarshal(data, &messages); err != nil {
|
||||||
|
return fmt.Errorf("failed to parse JSON file %s: %w", filePath, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
i.mu.Lock()
|
||||||
|
defer i.mu.Unlock()
|
||||||
|
|
||||||
|
if i.messages[lang] == nil {
|
||||||
|
i.messages[lang] = make(map[string]MessageInfo)
|
||||||
|
}
|
||||||
|
|
||||||
|
// 合并到现有消息中(如果key已存在会被覆盖)
|
||||||
|
for k, v := range messages {
|
||||||
|
i.messages[lang][k] = v
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// LoadFromDir 从目录加载多个语言文件
|
||||||
|
// dirPath: 语言文件目录路径
|
||||||
|
// 文件命名规则:{语言代码}.json(如 zh-CN.json, en-US.json)
|
||||||
|
//
|
||||||
|
// 示例目录结构:
|
||||||
|
//
|
||||||
|
// locales/
|
||||||
|
// zh-CN.json
|
||||||
|
// en-US.json
|
||||||
|
// ja-JP.json
|
||||||
|
func (i *I18n) LoadFromDir(dirPath string) error {
|
||||||
|
entries, err := os.ReadDir(dirPath)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("failed to read directory %s: %w", dirPath, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, entry := range entries {
|
||||||
|
if entry.IsDir() {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
// 只处理 .json 文件
|
||||||
|
if !strings.HasSuffix(entry.Name(), ".json") {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
// 从文件名提取语言代码(去掉 .json 后缀)
|
||||||
|
lang := strings.TrimSuffix(entry.Name(), ".json")
|
||||||
|
filePath := filepath.Join(dirPath, entry.Name())
|
||||||
|
|
||||||
|
if err := i.LoadFromFile(filePath, lang); err != nil {
|
||||||
|
return fmt.Errorf("failed to load language file %s: %w", filePath, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// LoadFromMap 从map加载语言内容(用于测试或动态加载)
|
||||||
|
// lang: 语言代码
|
||||||
|
// messages: 消息map,key为消息代码,value为消息信息
|
||||||
|
//
|
||||||
|
// 示例:
|
||||||
|
//
|
||||||
|
// i18n.LoadFromMap("zh-CN", map[string]MessageInfo{
|
||||||
|
// "user.not_found": {Code: 1001, Message: "用户不存在"},
|
||||||
|
// "user.login_success": {Code: 0, Message: "登录成功"},
|
||||||
|
// })
|
||||||
|
func (i *I18n) LoadFromMap(lang string, messages map[string]MessageInfo) {
|
||||||
|
i.mu.Lock()
|
||||||
|
defer i.mu.Unlock()
|
||||||
|
|
||||||
|
if i.messages[lang] == nil {
|
||||||
|
i.messages[lang] = make(map[string]MessageInfo)
|
||||||
|
}
|
||||||
|
|
||||||
|
// 合并到现有消息中
|
||||||
|
for k, v := range messages {
|
||||||
|
i.messages[lang][k] = v
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetMessage 获取指定语言和代码的消息内容
|
||||||
|
// lang: 语言代码(如 "zh-CN", "en-US")
|
||||||
|
// code: 消息代码(如 "user.not_found")
|
||||||
|
// args: 可选参数,用于格式化消息(类似 fmt.Sprintf)
|
||||||
|
//
|
||||||
|
// 返回逻辑:
|
||||||
|
// 1. 如果指定语言存在该code,返回对应内容
|
||||||
|
// 2. 如果指定语言不存在,尝试使用默认语言
|
||||||
|
// 3. 如果默认语言也不存在,返回code本身(作为fallback)
|
||||||
|
//
|
||||||
|
// 示例:
|
||||||
|
//
|
||||||
|
// msg := i18n.GetMessage("zh-CN", "user.not_found")
|
||||||
|
// // 返回: "用户不存在"
|
||||||
|
//
|
||||||
|
// msg := i18n.GetMessage("zh-CN", "user.welcome", "Alice")
|
||||||
|
// // 如果消息内容是 "欢迎,%s",返回: "欢迎,Alice"
|
||||||
|
func (i *I18n) GetMessage(lang, code string, args ...interface{}) string {
|
||||||
|
info := i.GetMessageInfo(lang, code, args...)
|
||||||
|
return info.Message
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetMessageInfo 获取指定语言和代码的完整消息信息(包含业务code)
|
||||||
|
// lang: 语言代码(如 "zh-CN", "en-US")
|
||||||
|
// code: 消息代码(如 "user.not_found")
|
||||||
|
// args: 可选参数,用于格式化消息(类似 fmt.Sprintf)
|
||||||
|
//
|
||||||
|
// 返回逻辑:
|
||||||
|
// 1. 如果指定语言存在该code,返回对应的MessageInfo
|
||||||
|
// 2. 如果指定语言不存在,尝试使用默认语言
|
||||||
|
// 3. 如果默认语言也不存在,返回code本身作为message,code为0
|
||||||
|
//
|
||||||
|
// 示例:
|
||||||
|
//
|
||||||
|
// info := i18n.GetMessageInfo("zh-CN", "user.not_found")
|
||||||
|
// // 返回: MessageInfo{Code: 1001, Message: "用户不存在"}
|
||||||
|
func (i *I18n) GetMessageInfo(lang, code string, args ...interface{}) MessageInfo {
|
||||||
|
i.mu.RLock()
|
||||||
|
defer i.mu.RUnlock()
|
||||||
|
|
||||||
|
// 尝试从指定语言获取
|
||||||
|
if messages, ok := i.messages[lang]; ok {
|
||||||
|
if msgInfo, ok := messages[code]; ok {
|
||||||
|
// 格式化消息内容
|
||||||
|
msgInfo.Message = i.formatMessage(msgInfo.Message, args...)
|
||||||
|
return msgInfo
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 如果指定语言不存在该code,尝试使用默认语言
|
||||||
|
if i.defaultLang != "" && i.defaultLang != lang {
|
||||||
|
if messages, ok := i.messages[i.defaultLang]; ok {
|
||||||
|
if msgInfo, ok := messages[code]; ok {
|
||||||
|
// 格式化消息内容
|
||||||
|
msgInfo.Message = i.formatMessage(msgInfo.Message, args...)
|
||||||
|
return msgInfo
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 如果都不存在,返回code本身作为message,code为0(作为fallback)
|
||||||
|
return MessageInfo{
|
||||||
|
Code: 0,
|
||||||
|
Message: code,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// formatMessage 格式化消息(支持参数替换)
|
||||||
|
// 如果消息中包含 %s, %d 等格式化占位符,使用 args 进行替换
|
||||||
|
func (i *I18n) formatMessage(msg string, args ...interface{}) string {
|
||||||
|
if len(args) == 0 {
|
||||||
|
return msg
|
||||||
|
}
|
||||||
|
|
||||||
|
// 检查消息中是否包含格式化占位符
|
||||||
|
if strings.Contains(msg, "%") {
|
||||||
|
return fmt.Sprintf(msg, args...)
|
||||||
|
}
|
||||||
|
|
||||||
|
return msg
|
||||||
|
}
|
||||||
|
|
||||||
|
// SetDefaultLang 设置默认语言
|
||||||
|
// lang: 默认语言代码
|
||||||
|
func (i *I18n) SetDefaultLang(lang string) {
|
||||||
|
i.mu.Lock()
|
||||||
|
defer i.mu.Unlock()
|
||||||
|
i.defaultLang = lang
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetDefaultLang 获取默认语言代码
|
||||||
|
func (i *I18n) GetDefaultLang() string {
|
||||||
|
i.mu.RLock()
|
||||||
|
defer i.mu.RUnlock()
|
||||||
|
return i.defaultLang
|
||||||
|
}
|
||||||
|
|
||||||
|
// HasLang 检查是否已加载指定语言
|
||||||
|
// lang: 语言代码
|
||||||
|
func (i *I18n) HasLang(lang string) bool {
|
||||||
|
i.mu.RLock()
|
||||||
|
defer i.mu.RUnlock()
|
||||||
|
_, ok := i.messages[lang]
|
||||||
|
return ok
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetSupportedLangs 获取所有已加载的语言代码列表
|
||||||
|
func (i *I18n) GetSupportedLangs() []string {
|
||||||
|
i.mu.RLock()
|
||||||
|
defer i.mu.RUnlock()
|
||||||
|
|
||||||
|
langs := make([]string, 0, len(i.messages))
|
||||||
|
for lang := range i.messages {
|
||||||
|
langs = append(langs, lang)
|
||||||
|
}
|
||||||
|
|
||||||
|
return langs
|
||||||
|
}
|
||||||
|
|
||||||
|
// ReloadFromFile 重新加载指定语言文件
|
||||||
|
// filePath: 语言文件路径
|
||||||
|
// lang: 语言代码
|
||||||
|
func (i *I18n) ReloadFromFile(filePath, lang string) error {
|
||||||
|
// 先清除该语言的所有消息
|
||||||
|
i.mu.Lock()
|
||||||
|
delete(i.messages, lang)
|
||||||
|
i.mu.Unlock()
|
||||||
|
|
||||||
|
// 重新加载
|
||||||
|
return i.LoadFromFile(filePath, lang)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ReloadFromDir 重新加载目录中的所有语言文件
|
||||||
|
// dirPath: 语言文件目录路径
|
||||||
|
func (i *I18n) ReloadFromDir(dirPath string) error {
|
||||||
|
// 先清除所有消息
|
||||||
|
i.mu.Lock()
|
||||||
|
i.messages = make(map[string]map[string]MessageInfo)
|
||||||
|
i.mu.Unlock()
|
||||||
|
|
||||||
|
// 重新加载
|
||||||
|
return i.LoadFromDir(dirPath)
|
||||||
|
}
|
||||||
102
middleware/language.go
Normal file
102
middleware/language.go
Normal file
@@ -0,0 +1,102 @@
|
|||||||
|
package middleware
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"net/http"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
// LanguageKey context中存储语言的key
|
||||||
|
type languageKey struct{}
|
||||||
|
|
||||||
|
// LanguageHeaderName 语言请求头名称
|
||||||
|
const LanguageHeaderName = "X-Language"
|
||||||
|
|
||||||
|
// AcceptLanguageHeaderName Accept-Language 请求头名称
|
||||||
|
const AcceptLanguageHeaderName = "Accept-Language"
|
||||||
|
|
||||||
|
// DefaultLanguage 默认语言
|
||||||
|
const DefaultLanguage = "zh-CN"
|
||||||
|
|
||||||
|
// GetLanguageFromContext 从context中获取语言
|
||||||
|
func GetLanguageFromContext(ctx context.Context) string {
|
||||||
|
if lang, ok := ctx.Value(languageKey{}).(string); ok && lang != "" {
|
||||||
|
return lang
|
||||||
|
}
|
||||||
|
return DefaultLanguage
|
||||||
|
}
|
||||||
|
|
||||||
|
// Language 语言处理中间件
|
||||||
|
// 从请求头 X-Language 或 Accept-Language 读取语言信息,如果未传递则使用默认语言 zh-CN
|
||||||
|
// 语言信息会存储到context中,可以通过 GetLanguageFromContext 获取
|
||||||
|
func Language(next http.Handler) http.Handler {
|
||||||
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
// 1. 优先从 X-Language 请求头获取(显式指定)
|
||||||
|
lang := r.Header.Get(LanguageHeaderName)
|
||||||
|
|
||||||
|
// 2. 如果未设置,从 Accept-Language 请求头解析
|
||||||
|
if lang == "" {
|
||||||
|
acceptLang := r.Header.Get(AcceptLanguageHeaderName)
|
||||||
|
if acceptLang != "" {
|
||||||
|
lang = parseAcceptLanguage(acceptLang)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 3. 如果都未设置,使用默认语言
|
||||||
|
if lang == "" {
|
||||||
|
lang = DefaultLanguage
|
||||||
|
}
|
||||||
|
|
||||||
|
// 将语言存储到context中
|
||||||
|
ctx := context.WithValue(r.Context(), languageKey{}, lang)
|
||||||
|
next.ServeHTTP(w, r.WithContext(ctx))
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// LanguageWithDefault 语言处理中间件(可自定义默认语言)
|
||||||
|
// defaultLanguage: 默认语言,如果未指定则使用 zh-CN
|
||||||
|
func LanguageWithDefault(defaultLanguage string) func(http.Handler) http.Handler {
|
||||||
|
return func(next http.Handler) http.Handler {
|
||||||
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
// 1. 优先从 X-Language 请求头获取(显式指定)
|
||||||
|
lang := r.Header.Get(LanguageHeaderName)
|
||||||
|
|
||||||
|
// 2. 如果未设置,从 Accept-Language 请求头解析
|
||||||
|
if lang == "" {
|
||||||
|
acceptLang := r.Header.Get(AcceptLanguageHeaderName)
|
||||||
|
if acceptLang != "" {
|
||||||
|
lang = parseAcceptLanguage(acceptLang)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 3. 如果都未设置,使用指定的默认语言
|
||||||
|
if lang == "" {
|
||||||
|
lang = defaultLanguage
|
||||||
|
}
|
||||||
|
|
||||||
|
// 将语言存储到context中
|
||||||
|
ctx := context.WithValue(r.Context(), languageKey{}, lang)
|
||||||
|
next.ServeHTTP(w, r.WithContext(ctx))
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// parseAcceptLanguage 解析 Accept-Language 请求头
|
||||||
|
// 返回第一个语言代码(去掉权重信息)
|
||||||
|
func parseAcceptLanguage(acceptLang string) string {
|
||||||
|
if acceptLang == "" {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
|
||||||
|
// 分割语言列表
|
||||||
|
parts := strings.Split(acceptLang, ",")
|
||||||
|
if len(parts) == 0 {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
|
||||||
|
// 取第一个语言代码,去掉权重信息(如 ";q=0.9")
|
||||||
|
firstLang := strings.Split(parts[0], ";")[0]
|
||||||
|
firstLang = strings.TrimSpace(firstLang)
|
||||||
|
|
||||||
|
return firstLang
|
||||||
|
}
|
||||||
99
tools/convertor.go
Normal file
99
tools/convertor.go
Normal file
@@ -0,0 +1,99 @@
|
|||||||
|
package tools
|
||||||
|
|
||||||
|
import "strconv"
|
||||||
|
|
||||||
|
// ConvertInt 将字符串转换为int类型
|
||||||
|
// value: 待转换的字符串
|
||||||
|
// defaultValue: 转换失败或字符串为空时返回的默认值
|
||||||
|
func ConvertInt(value string, defaultValue int) int {
|
||||||
|
if value == "" {
|
||||||
|
return defaultValue
|
||||||
|
}
|
||||||
|
|
||||||
|
intValue, err := strconv.Atoi(value)
|
||||||
|
if err != nil {
|
||||||
|
return defaultValue
|
||||||
|
}
|
||||||
|
|
||||||
|
return intValue
|
||||||
|
}
|
||||||
|
|
||||||
|
// ConvertInt64 将字符串转换为int64类型
|
||||||
|
// value: 待转换的字符串
|
||||||
|
// defaultValue: 转换失败或字符串为空时返回的默认值
|
||||||
|
func ConvertInt64(value string, defaultValue int64) int64 {
|
||||||
|
if value == "" {
|
||||||
|
return defaultValue
|
||||||
|
}
|
||||||
|
|
||||||
|
intValue, err := strconv.ParseInt(value, 10, 64)
|
||||||
|
if err != nil {
|
||||||
|
return defaultValue
|
||||||
|
}
|
||||||
|
|
||||||
|
return intValue
|
||||||
|
}
|
||||||
|
|
||||||
|
// ConvertUint64 将字符串转换为uint64类型
|
||||||
|
// value: 待转换的字符串
|
||||||
|
// defaultValue: 转换失败或字符串为空时返回的默认值
|
||||||
|
func ConvertUint64(value string, defaultValue uint64) uint64 {
|
||||||
|
if value == "" {
|
||||||
|
return defaultValue
|
||||||
|
}
|
||||||
|
|
||||||
|
uintValue, err := strconv.ParseUint(value, 10, 64)
|
||||||
|
if err != nil {
|
||||||
|
return defaultValue
|
||||||
|
}
|
||||||
|
|
||||||
|
return uintValue
|
||||||
|
}
|
||||||
|
|
||||||
|
// ConvertUint32 将字符串转换为uint32类型
|
||||||
|
// value: 待转换的字符串
|
||||||
|
// defaultValue: 转换失败或字符串为空时返回的默认值
|
||||||
|
func ConvertUint32(value string, defaultValue uint32) uint32 {
|
||||||
|
if value == "" {
|
||||||
|
return defaultValue
|
||||||
|
}
|
||||||
|
|
||||||
|
uintValue, err := strconv.ParseUint(value, 10, 32)
|
||||||
|
if err != nil {
|
||||||
|
return defaultValue
|
||||||
|
}
|
||||||
|
|
||||||
|
return uint32(uintValue)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ConvertBool 将字符串转换为bool类型
|
||||||
|
// value: 待转换的字符串
|
||||||
|
// defaultValue: 转换失败或字符串为空时返回的默认值
|
||||||
|
func ConvertBool(value string, defaultValue bool) bool {
|
||||||
|
if value == "" {
|
||||||
|
return defaultValue
|
||||||
|
}
|
||||||
|
|
||||||
|
boolValue, err := strconv.ParseBool(value)
|
||||||
|
if err != nil {
|
||||||
|
return defaultValue
|
||||||
|
}
|
||||||
|
|
||||||
|
return boolValue
|
||||||
|
}
|
||||||
|
|
||||||
|
// ConvertFloat64 将字符串转换为float64类型
|
||||||
|
// value: 待转换的字符串
|
||||||
|
// defaultValue: 转换失败或字符串为空时返回的默认值
|
||||||
|
func ConvertFloat64(value string, defaultValue float64) float64 {
|
||||||
|
if value == "" {
|
||||||
|
return defaultValue
|
||||||
|
}
|
||||||
|
|
||||||
|
floatValue, err := strconv.ParseFloat(value, 64)
|
||||||
|
if err != nil {
|
||||||
|
return defaultValue
|
||||||
|
}
|
||||||
|
|
||||||
|
return floatValue
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user