Compare commits
4 Commits
f8f4df4073
...
v0.6.5
| Author | SHA1 | Date | |
|---|---|---|---|
| a6e8101e09 | |||
| 38ebe73e45 | |||
| e3d9bbbcc5 | |||
| 47cbdbb2de |
1
.gitignore
vendored
1
.gitignore
vendored
@@ -1 +1,2 @@
|
||||
.cursor
|
||||
.DS_Store
|
||||
28
README.md
28
README.md
@@ -59,7 +59,7 @@
|
||||
提供从外部文件加载配置的功能,支持数据库、OSS、Redis、CORS、MinIO等配置。
|
||||
|
||||
### 6. 存储工具 (storage)
|
||||
提供文件上传和查看功能,支持OSS和MinIO两种存储方式,并提供HTTP处理器。
|
||||
提供文件上传和查看功能,支持本地文件夹(Local)、OSS 和 MinIO 三种存储方式,并提供HTTP处理器。
|
||||
|
||||
### 7. 邮件工具 (email)
|
||||
提供SMTP邮件发送功能,支持纯文本和HTML邮件,使用Go标准库实现。
|
||||
@@ -67,10 +67,20 @@
|
||||
### 8. 短信工具 (sms)
|
||||
提供阿里云短信发送功能,支持模板短信和批量发送,使用Go标准库实现。
|
||||
|
||||
### 9. 工厂工具 (factory)
|
||||
提供从配置文件直接创建已初始化客户端对象的功能,包括数据库、Redis、邮件、短信、日志等,避免调用方重复实现创建逻辑。
|
||||
### 9. Excel导出工具 (excel)
|
||||
提供数据导出到Excel文件的功能,支持结构体切片、自定义格式化、多工作表等特性。
|
||||
|
||||
### 10. 日志工具 (logger)
|
||||
**功能特性**:
|
||||
- 支持结构体切片自动导出
|
||||
- 支持嵌套字段访问(如 "User.Name")
|
||||
- 支持自定义格式化函数
|
||||
- 自动调整列宽和表头样式
|
||||
- 支持导出到文件或HTTP响应
|
||||
|
||||
### 10. 工厂工具 (factory)
|
||||
提供从配置文件直接创建已初始化客户端对象的功能,包括数据库、Redis、邮件、短信、日志、Excel等,避免调用方重复实现创建逻辑。
|
||||
|
||||
### 11. 日志工具 (logger)
|
||||
提供统一的日志记录功能,支持多种日志级别和输出方式,使用Go标准库实现。
|
||||
|
||||
---
|
||||
@@ -90,10 +100,12 @@
|
||||
| 邮件 | `SendEmail()` | 直接调用 | ⭐⭐⭐ |
|
||||
| 短信 | `SendSMS()` | 直接调用 | ⭐⭐⭐ |
|
||||
| 存储 | `UploadFile()`, `GetFileURL()` | 直接调用 | ⭐⭐⭐ |
|
||||
| Excel导出 | `ExportToExcel()`, `ExportToExcelFile()` | 直接调用 | ⭐⭐⭐ |
|
||||
| **Get方法(高级功能)** | | | |
|
||||
| 数据库 | `GetDatabase()` | 返回GORM对象,用于复杂查询 | ⭐⭐ |
|
||||
| Redis高级 | `GetRedisClient()` | 返回Redis客户端,用于Hash/List/Set等 | ⭐ |
|
||||
| Logger高级 | `GetLogger()` | 返回Logger对象,用于Close等 | ⭐ |
|
||||
| 存储高级 | `GetStorage()` | 返回Storage对象,用于Delete/Exists/GetObject等 | ⭐ |
|
||||
|
||||
### 使用示例
|
||||
|
||||
@@ -277,6 +289,14 @@ fac.SendSMS([]string{"13800138000"}, map[string]string{"code": "123456"})
|
||||
// 文件上传
|
||||
url, _ := fac.UploadFile(ctx, "images/test.jpg", file, "image/jpeg")
|
||||
|
||||
// Excel导出
|
||||
columns := []factory.ExportColumn{
|
||||
{Header: "ID", Field: "ID", Width: 10},
|
||||
{Header: "姓名", Field: "Name", Width: 20},
|
||||
{Header: "邮箱", Field: "Email", Width: 30},
|
||||
}
|
||||
fac.ExportToExcelFile("users.xlsx", "用户列表", columns, users)
|
||||
|
||||
// 数据库(高级功能)
|
||||
db, _ := fac.GetDatabase()
|
||||
db.Find(&users)
|
||||
|
||||
@@ -129,3 +129,8 @@ go get -u=minor git.toowon.com/jimmy/go-common
|
||||
- 初始版本
|
||||
- 包含所有基础工具类:migration、datetime、http、middleware、config、storage、email、sms、factory、logger
|
||||
|
||||
- **v1.1.0** (未发布)
|
||||
- storage:新增本地文件夹存储(LocalStorage),支持将文件/图片上传到本地目录
|
||||
- config:新增 `localStorage` 配置段(`baseDir` / `publicURL`)
|
||||
- factory:新增 `GetStorage()`,并支持 Local/MinIO/OSS 自动选择(优先级:Local > MinIO > OSS)
|
||||
|
||||
|
||||
@@ -14,12 +14,28 @@ type Config struct {
|
||||
Redis *RedisConfig `json:"redis"`
|
||||
CORS *CORSConfig `json:"cors"`
|
||||
MinIO *MinIOConfig `json:"minio"`
|
||||
Local *LocalStorageConfig `json:"localStorage"`
|
||||
Email *EmailConfig `json:"email"`
|
||||
SMS *SMSConfig `json:"sms"`
|
||||
Logger *LoggerConfig `json:"logger"`
|
||||
RateLimit *RateLimitConfig `json:"rateLimit"`
|
||||
}
|
||||
|
||||
// LocalStorageConfig 本地存储配置
|
||||
// 用于将文件保存到本地文件夹(适合开发环境、单机部署等场景)
|
||||
type LocalStorageConfig struct {
|
||||
// BaseDir 本地文件保存根目录(必填)
|
||||
// 示例: "./uploads" 或 "/var/app/uploads"
|
||||
BaseDir string `json:"baseDir"`
|
||||
|
||||
// PublicURL 对外访问URL(可选)
|
||||
// 1) 若包含 "{objectKey}" 占位符,则会替换为 url.QueryEscape(objectKey)
|
||||
// 示例: "http://localhost:8080/file?key={objectKey}" (配合 ProxyHandler 使用)
|
||||
// 2) 若不包含占位符,则作为URL前缀,自动拼接 objectKey
|
||||
// 示例: "http://localhost:8080/static/" => "http://localhost:8080/static/<objectKey>"
|
||||
PublicURL string `json:"publicURL"`
|
||||
}
|
||||
|
||||
// DatabaseConfig 数据库配置
|
||||
type DatabaseConfig struct {
|
||||
// Type 数据库类型: mysql, postgres, sqlite
|
||||
@@ -439,6 +455,11 @@ func (c *Config) GetMinIO() *MinIOConfig {
|
||||
return c.MinIO
|
||||
}
|
||||
|
||||
// GetLocalStorage 获取本地存储配置
|
||||
func (c *Config) GetLocalStorage() *LocalStorageConfig {
|
||||
return c.Local
|
||||
}
|
||||
|
||||
// GetEmail 获取邮件配置
|
||||
func (c *Config) GetEmail() *EmailConfig {
|
||||
return c.Email
|
||||
|
||||
@@ -50,6 +50,10 @@
|
||||
"region": "us-east-1",
|
||||
"domain": "http://localhost:9000"
|
||||
},
|
||||
"localStorage": {
|
||||
"baseDir": "./uploads",
|
||||
"publicURL": "http://localhost:8080/file?key={objectKey}"
|
||||
},
|
||||
"email": {
|
||||
"host": "smtp.example.com",
|
||||
"port": 587,
|
||||
|
||||
@@ -11,6 +11,7 @@
|
||||
- [存储工具](./storage.md) - 文件上传和查看(OSS、MinIO)
|
||||
- [邮件工具](./email.md) - SMTP邮件发送
|
||||
- [短信工具](./sms.md) - 阿里云短信发送
|
||||
- [Excel导出工具](./excel.md) - 数据导出到Excel文件
|
||||
- [工厂工具](./factory.md) - 从配置直接创建已初始化客户端对象
|
||||
- [日志工具](./logger.md) - 统一的日志记录功能
|
||||
- [国际化工具](./i18n.md) - 多语言内容管理和国际化支持
|
||||
|
||||
@@ -2,12 +2,13 @@
|
||||
|
||||
## 概述
|
||||
|
||||
配置工具提供了从外部文件加载和管理应用配置的功能,支持数据库、OSS、Redis、CORS、MinIO、邮件、短信等常用服务的配置。
|
||||
配置工具提供了从外部文件加载和管理应用配置的功能,支持数据库、LocalStorage、OSS、Redis、CORS、MinIO、邮件、短信等常用服务的配置。
|
||||
|
||||
## 功能特性
|
||||
|
||||
- 支持从外部JSON文件加载配置
|
||||
- 支持数据库配置(MySQL、PostgreSQL、SQLite)
|
||||
- 支持本地存储配置(LocalStorage,文件上传保存到本地文件夹)
|
||||
- 支持OSS对象存储配置(阿里云、腾讯云、AWS、七牛云等)
|
||||
- 支持Redis配置
|
||||
- 支持CORS配置(与middleware包集成)
|
||||
@@ -75,6 +76,10 @@
|
||||
"region": "us-east-1",
|
||||
"domain": "http://localhost:9000"
|
||||
},
|
||||
"localStorage": {
|
||||
"baseDir": "./uploads",
|
||||
"publicURL": "http://localhost:8080/file?key={objectKey}"
|
||||
},
|
||||
"email": {
|
||||
"host": "smtp.example.com",
|
||||
"port": 587,
|
||||
@@ -196,6 +201,16 @@ if minioConfig != nil {
|
||||
}
|
||||
```
|
||||
|
||||
### 6.1 获取本地存储配置(LocalStorage)
|
||||
|
||||
```go
|
||||
localCfg := config.GetLocalStorage()
|
||||
if localCfg != nil {
|
||||
fmt.Printf("Local baseDir: %s\n", localCfg.BaseDir)
|
||||
fmt.Printf("Local publicURL: %s\n", localCfg.PublicURL)
|
||||
}
|
||||
```
|
||||
|
||||
## 配置项说明
|
||||
|
||||
### DatabaseConfig 数据库配置
|
||||
@@ -266,6 +281,13 @@ if minioConfig != nil {
|
||||
| Region | string | 区域 |
|
||||
| Domain | string | 自定义域名 |
|
||||
|
||||
### LocalStorageConfig 本地存储配置
|
||||
|
||||
| 字段 | 类型 | 说明 |
|
||||
|------|------|------|
|
||||
| BaseDir | string | 本地文件保存根目录(必填) |
|
||||
| PublicURL | string | 对外访问 URL(可选)。包含 `{objectKey}` 占位符时会替换为 `url.QueryEscape(objectKey)`;不包含时作为 URL 前缀拼接 |
|
||||
|
||||
### EmailConfig 邮件配置
|
||||
|
||||
| 字段 | 类型 | 说明 | 默认值 |
|
||||
|
||||
447
docs/excel.md
Normal file
447
docs/excel.md
Normal file
@@ -0,0 +1,447 @@
|
||||
# Excel导出工具文档
|
||||
|
||||
## 概述
|
||||
|
||||
Excel导出工具提供了将数据导出到Excel文件的功能,支持结构体切片、自定义格式化、多工作表等特性。通过工厂模式,外部项目可以方便地使用Excel导出功能。
|
||||
|
||||
## 功能特性
|
||||
|
||||
- **黑盒模式**:提供直接调用的方法,无需获取Excel对象
|
||||
- **延迟初始化**:Excel导出器在首次使用时才创建
|
||||
- **支持结构体切片**:自动将结构体切片转换为Excel行数据
|
||||
- **支持嵌套字段**:支持访问嵌套结构体字段(如 "User.Name")
|
||||
- **自定义格式化**:支持自定义字段值的格式化函数
|
||||
- **自动列宽**:自动调整列宽以适应内容
|
||||
- **表头样式**:自动应用表头样式(加粗、背景色等)
|
||||
- **智能工作表管理**:自动处理工作表的创建和删除,避免产生空sheet
|
||||
- **ExportData接口**:支持实现ExportData接口进行高级定制
|
||||
- **空数据处理**:即使数据为空(nil或空切片),也会正常生成表头
|
||||
- **统一接口**:只暴露 `ExportToWriter` 一个核心方法
|
||||
|
||||
## 使用方法
|
||||
|
||||
### 1. 创建工厂
|
||||
|
||||
```go
|
||||
import "git.toowon.com/jimmy/go-common/factory"
|
||||
|
||||
// 从配置文件创建
|
||||
fac, err := factory.NewFactoryFromFile("./config.json")
|
||||
|
||||
// 或Excel导出不需要配置,可以传nil
|
||||
fac := factory.NewFactory(nil)
|
||||
```
|
||||
|
||||
### 2. 导出结构体切片到文件
|
||||
|
||||
```go
|
||||
// 定义结构体
|
||||
type User struct {
|
||||
ID int `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Email string `json:"email"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
Status int `json:"status"`
|
||||
}
|
||||
|
||||
// 准备数据
|
||||
users := []User{
|
||||
{ID: 1, Name: "Alice", Email: "alice@example.com", CreatedAt: time.Now(), Status: 1},
|
||||
{ID: 2, Name: "Bob", Email: "bob@example.com", CreatedAt: time.Now(), Status: 1},
|
||||
}
|
||||
|
||||
// 定义导出列
|
||||
columns := []factory.ExportColumn{
|
||||
{Header: "ID", Field: "ID", Width: 10},
|
||||
{Header: "姓名", Field: "Name", Width: 20},
|
||||
{Header: "邮箱", Field: "Email", Width: 30},
|
||||
{Header: "创建时间", Field: "CreatedAt", Width: 20},
|
||||
{Header: "状态", Field: "Status", Width: 10},
|
||||
}
|
||||
|
||||
// 导出到文件
|
||||
err := fac.ExportToExcelFile("users.xlsx", "用户列表", columns, users)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
```
|
||||
|
||||
### 3. 导出到HTTP响应
|
||||
|
||||
```go
|
||||
import "net/http"
|
||||
|
||||
func exportUsersHandler(w http.ResponseWriter, r *http.Request) {
|
||||
fac, _ := factory.NewFactoryFromFile("./config.json")
|
||||
|
||||
users := []User{
|
||||
{ID: 1, Name: "Alice", Email: "alice@example.com", CreatedAt: time.Now(), Status: 1},
|
||||
{ID: 2, Name: "Bob", Email: "bob@example.com", CreatedAt: time.Now(), Status: 1},
|
||||
}
|
||||
|
||||
columns := []factory.ExportColumn{
|
||||
{Header: "ID", Field: "ID"},
|
||||
{Header: "姓名", Field: "Name"},
|
||||
{Header: "邮箱", Field: "Email"},
|
||||
}
|
||||
|
||||
// 设置HTTP响应头
|
||||
w.Header().Set("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
|
||||
w.Header().Set("Content-Disposition", "attachment; filename=users.xlsx")
|
||||
|
||||
// 导出到响应
|
||||
err := fac.ExportToExcel(w, "用户列表", columns, users)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 4. 使用格式化函数
|
||||
|
||||
```go
|
||||
import "git.toowon.com/jimmy/go-common/excel"
|
||||
|
||||
columns := []factory.ExportColumn{
|
||||
{Header: "ID", Field: "ID", Width: 10},
|
||||
{Header: "姓名", Field: "Name", Width: 20},
|
||||
{
|
||||
Header: "创建时间",
|
||||
Field: "CreatedAt",
|
||||
Width: 20,
|
||||
Format: excel.AdaptTimeFormatter(tools.FormatDateTime), // 使用适配器直接调用tools函数
|
||||
},
|
||||
{
|
||||
Header: "状态",
|
||||
Field: "Status",
|
||||
Width: 10,
|
||||
Format: func(value interface{}) string {
|
||||
// 自定义格式化函数
|
||||
if status, ok := value.(int); ok {
|
||||
if status == 1 {
|
||||
return "启用"
|
||||
}
|
||||
return "禁用"
|
||||
}
|
||||
return ""
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
err := fac.ExportToExcelFile("users.xlsx", "用户列表", columns, users)
|
||||
```
|
||||
|
||||
### 5. 使用ExportData接口(高级功能)
|
||||
|
||||
```go
|
||||
// 实现ExportData接口
|
||||
type UserExportData struct {
|
||||
users []User
|
||||
}
|
||||
|
||||
// GetExportColumns 获取导出列定义
|
||||
func (d *UserExportData) GetExportColumns() []excel.ExportColumn {
|
||||
return []excel.ExportColumn{
|
||||
{Header: "ID", Field: "ID", Width: 10},
|
||||
{Header: "姓名", Field: "Name", Width: 20},
|
||||
{Header: "邮箱", Field: "Email", Width: 30},
|
||||
}
|
||||
}
|
||||
|
||||
// GetExportRows 获取导出数据行
|
||||
func (d *UserExportData) GetExportRows() [][]interface{} {
|
||||
rows := make([][]interface{}, 0, len(d.users))
|
||||
for _, user := range d.users {
|
||||
row := []interface{}{
|
||||
user.ID,
|
||||
user.Name,
|
||||
user.Email,
|
||||
}
|
||||
rows = append(rows, row)
|
||||
}
|
||||
return rows
|
||||
}
|
||||
|
||||
// 使用
|
||||
exportData := &UserExportData{users: users}
|
||||
columns := exportData.GetExportColumns()
|
||||
err := fac.ExportToExcelFile("users.xlsx", "用户列表", columns, exportData)
|
||||
```
|
||||
|
||||
### 6. 获取Excel对象(高级功能)
|
||||
|
||||
```go
|
||||
// 获取Excel导出器对象(仅在需要高级功能时使用)
|
||||
excel, err := fac.GetExcel()
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
// 获取excelize.File对象,用于高级操作
|
||||
file := excel.GetFile()
|
||||
|
||||
// 创建多个工作表
|
||||
file.NewSheet("Sheet2")
|
||||
file.SetCellValue("Sheet2", "A1", "数据")
|
||||
|
||||
// 自定义样式
|
||||
style, _ := file.NewStyle(&excelize.Style{
|
||||
Font: &excelize.Font{
|
||||
Bold: true,
|
||||
Size: 14,
|
||||
},
|
||||
})
|
||||
file.SetCellStyle("Sheet2", "A1", "A1", style)
|
||||
```
|
||||
|
||||
## API 参考
|
||||
|
||||
### 工厂方法
|
||||
|
||||
#### ExportToExcel(w io.Writer, sheetName string, columns []ExportColumn, data interface{}) error
|
||||
|
||||
导出数据到Writer。
|
||||
|
||||
**参数:**
|
||||
- `w`: Writer对象(如http.ResponseWriter)
|
||||
- `sheetName`: 工作表名称(可选,默认为"Sheet1")
|
||||
- `columns`: 列定义
|
||||
- `data`: 数据列表(可以是结构体切片或实现了ExportData接口的对象)
|
||||
|
||||
**返回:** 错误信息
|
||||
|
||||
**数据为空处理:**
|
||||
- 支持 `nil`、空切片、指针类型等空数据情况
|
||||
- 即使数据为空,表头也会正常生成
|
||||
|
||||
**工作表处理逻辑:**
|
||||
- 如果 `sheetName` 为空,默认使用 "Sheet1"
|
||||
- 如果指定的工作表不存在,会自动创建
|
||||
- 使用自定义名称时会自动删除默认的"Sheet1",避免产生空sheet
|
||||
|
||||
**示例:**
|
||||
```go
|
||||
fac.ExportToExcel(w, "用户列表", columns, users)
|
||||
fac.ExportToExcel(w, "空数据", columns, []User{}) // 空数据也会生成表头
|
||||
```
|
||||
|
||||
#### ExportToExcelFile(filePath string, sheetName string, columns []ExportColumn, data interface{}) error
|
||||
|
||||
导出数据到文件。
|
||||
|
||||
**参数:**
|
||||
- `filePath`: 文件路径
|
||||
- `sheetName`: 工作表名称(可选,默认为"Sheet1")
|
||||
- `columns`: 列定义
|
||||
- `data`: 数据列表(可以是结构体切片或实现了ExportData接口的对象)
|
||||
|
||||
**返回:** 错误信息
|
||||
|
||||
**实现说明:**
|
||||
- 此方法内部创建文件并调用 `ExportToWriter`
|
||||
- 文件相关的封装由工厂方法处理
|
||||
|
||||
**工作表处理逻辑:**
|
||||
- 如果 `sheetName` 为空,默认使用 "Sheet1"
|
||||
- 如果指定的工作表不存在,会自动创建
|
||||
- 使用自定义名称时会自动删除默认的"Sheet1",避免产生空sheet
|
||||
|
||||
**示例:**
|
||||
```go
|
||||
fac.ExportToExcelFile("users.xlsx", "用户列表", columns, users)
|
||||
fac.ExportToExcelFile("empty.xlsx", "空数据", columns, []User{}) // 空数据也会生成表头
|
||||
```
|
||||
|
||||
### 高级方法
|
||||
|
||||
#### GetExcel() (*excel.Excel, error)
|
||||
|
||||
获取Excel导出器对象。
|
||||
|
||||
**返回:** Excel导出器对象和错误信息
|
||||
|
||||
**说明:** 仅在需要使用高级功能时使用,推荐使用黑盒方法
|
||||
|
||||
### 结构体类型
|
||||
|
||||
#### ExportColumn
|
||||
|
||||
导出列定义。
|
||||
|
||||
```go
|
||||
type ExportColumn struct {
|
||||
Header string // 表头名称
|
||||
Field string // 数据字段名(支持嵌套字段,如 "User.Name")
|
||||
Width float64 // 列宽(可选,0表示自动)
|
||||
Format func(interface{}) string // 格式化函数(可选)
|
||||
}
|
||||
```
|
||||
|
||||
**字段说明:**
|
||||
- `Header`: 表头显示的名称
|
||||
- `Field`: 数据字段名,支持嵌套字段(如 "User.Name")
|
||||
- `Width`: 列宽,0表示自动调整
|
||||
- `Format`: 格式化函数,用于自定义字段值的显示格式
|
||||
|
||||
### 格式化函数适配器
|
||||
|
||||
#### excel.AdaptTimeFormatter(fn func(time.Time, ...string) string) func(interface{}) string
|
||||
|
||||
适配器函数:将tools包的格式化函数转换为Excel Format字段需要的函数类型。
|
||||
|
||||
**参数:**
|
||||
- `fn`: tools包的格式化函数(如 `tools.FormatDate`、`tools.FormatDateTime` 等)
|
||||
|
||||
**返回:** Excel Format字段需要的格式化函数
|
||||
|
||||
**说明:**
|
||||
- 允许直接使用tools包的任何格式化函数
|
||||
|
||||
**示例:**
|
||||
```go
|
||||
import (
|
||||
"git.toowon.com/jimmy/go-common/excel"
|
||||
"git.toowon.com/jimmy/go-common/tools"
|
||||
)
|
||||
|
||||
// 使用tools.FormatDate
|
||||
Format: excel.AdaptTimeFormatter(tools.FormatDate)
|
||||
|
||||
// 使用tools.FormatDateTime
|
||||
Format: excel.AdaptTimeFormatter(tools.FormatDateTime)
|
||||
|
||||
// 使用tools.FormatTime
|
||||
Format: excel.AdaptTimeFormatter(tools.FormatTime)
|
||||
|
||||
// 使用自定义格式化函数
|
||||
Format: excel.AdaptTimeFormatter(func(t time.Time) string {
|
||||
return tools.Format(t, "2006-01-02 15:04:05", "Asia/Shanghai")
|
||||
})
|
||||
```
|
||||
|
||||
### ExportData接口
|
||||
|
||||
实现此接口的结构体可以直接导出。
|
||||
|
||||
```go
|
||||
type ExportData interface {
|
||||
// GetExportColumns 获取导出列定义
|
||||
GetExportColumns() []ExportColumn
|
||||
// GetExportRows 获取导出数据行
|
||||
GetExportRows() [][]interface{}
|
||||
}
|
||||
```
|
||||
|
||||
## 完整示例
|
||||
|
||||
```go
|
||||
package main
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"git.toowon.com/jimmy/go-common/excel"
|
||||
"git.toowon.com/jimmy/go-common/factory"
|
||||
)
|
||||
|
||||
type User struct {
|
||||
ID int `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Email string `json:"email"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
Status int `json:"status"`
|
||||
}
|
||||
|
||||
func exportUsersHandler(w http.ResponseWriter, r *http.Request) {
|
||||
fac, _ := factory.NewFactoryFromFile("./config.json")
|
||||
|
||||
// 从数据库或其他数据源获取数据
|
||||
users := []User{
|
||||
{ID: 1, Name: "Alice", Email: "alice@example.com", CreatedAt: time.Now(), Status: 1},
|
||||
{ID: 2, Name: "Bob", Email: "bob@example.com", CreatedAt: time.Now(), Status: 1},
|
||||
}
|
||||
|
||||
// 定义导出列
|
||||
columns := []factory.ExportColumn{
|
||||
{Header: "ID", Field: "ID", Width: 10},
|
||||
{Header: "姓名", Field: "Name", Width: 20},
|
||||
{Header: "邮箱", Field: "Email", Width: 30},
|
||||
{
|
||||
Header: "创建时间",
|
||||
Field: "CreatedAt",
|
||||
Width: 20,
|
||||
Format: excel.AdaptTimeFormatter(tools.FormatDateTime),
|
||||
},
|
||||
{
|
||||
Header: "状态",
|
||||
Field: "Status",
|
||||
Width: 10,
|
||||
Format: func(value interface{}) string {
|
||||
if status, ok := value.(int); ok {
|
||||
if status == 1 {
|
||||
return "启用"
|
||||
}
|
||||
return "禁用"
|
||||
}
|
||||
return ""
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
// 设置HTTP响应头
|
||||
w.Header().Set("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
|
||||
w.Header().Set("Content-Disposition", "attachment; filename=users.xlsx")
|
||||
|
||||
// 导出到响应
|
||||
err := fac.ExportToExcel(w, "用户列表", columns, users)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
func main() {
|
||||
http.HandleFunc("/export/users", exportUsersHandler)
|
||||
http.ListenAndServe(":8080", nil)
|
||||
}
|
||||
```
|
||||
|
||||
## 设计优势
|
||||
|
||||
1. **降低复杂度**:调用方无需关心Excel文件对象的创建和管理
|
||||
2. **延迟初始化**:Excel导出器在首次使用时才创建
|
||||
3. **统一接口**:所有操作通过工厂方法调用
|
||||
4. **灵活扩展**:支持结构体切片、自定义格式化、ExportData接口等多种方式
|
||||
5. **自动优化**:自动调整列宽、应用表头样式等
|
||||
|
||||
## 注意事项
|
||||
|
||||
1. **配置**:Excel导出不需要配置,可以传nil创建工厂
|
||||
2. **错误处理**:所有方法都可能返回错误,需要正确处理
|
||||
3. **延迟初始化**:Excel导出器在首次使用时才创建,首次调用可能稍慢
|
||||
4. **字段名匹配**:Field字段名必须与结构体字段名匹配(区分大小写)
|
||||
5. **嵌套字段**:支持嵌套字段访问(如 "User.Name"),但需要确保字段路径正确
|
||||
6. **格式化函数**:格式化函数返回的字符串会直接写入Excel单元格
|
||||
7. **列宽设置**:Width为0时会自动调整列宽,但可能影响性能(大数据量时建议设置固定宽度)
|
||||
8. **工作表处理**:工具会自动处理工作表的创建和删除,确保不会产生空sheet
|
||||
9. **空数据处理**:即使数据为 `nil` 或空切片,表头也会正常生成
|
||||
10. **方法设计**:
|
||||
- `excel` 包只暴露 `ExportToWriter` 一个核心方法
|
||||
- 文件相关的封装由工厂方法 `ExportToExcelFile` 处理
|
||||
|
||||
## 最佳实践
|
||||
|
||||
1. **使用工厂方法**:推荐使用 `ExportToExcel()` 和 `ExportToExcelFile()`
|
||||
2. **设置列宽**:对于大数据量,建议设置固定列宽以提高性能
|
||||
3. **使用格式化函数**:对于日期时间、状态等字段,使用格式化函数提高可读性
|
||||
4. **错误处理**:始终检查导出方法的返回值
|
||||
5. **HTTP响应**:导出到HTTP响应时,记得设置正确的Content-Type和Content-Disposition头
|
||||
6. **工作表命名**:推荐使用有意义的工作表名称,工具会自动处理工作表的创建和删除
|
||||
7. **空数据场景**:即使查询结果为空,也可以导出包含表头的Excel文件
|
||||
|
||||
## 示例
|
||||
|
||||
完整示例请参考 `examples/excel_example.go`
|
||||
|
||||
113
docs/factory.md
113
docs/factory.md
@@ -26,6 +26,7 @@
|
||||
| **邮件** | `SendEmail()` | `fac.SendEmail(to, subject, body)` |
|
||||
| **短信** | `SendSMS()` | `fac.SendSMS(phones, params)` |
|
||||
| **存储** | `UploadFile()`, `GetFileURL()` | `fac.UploadFile(ctx, key, file)` |
|
||||
| **Excel导出** | `ExportToExcel()`, `ExportToExcelFile()` | `fac.ExportToExcelFile("users.xlsx", "用户列表", columns, users)` |
|
||||
| **日期时间** | `Now()`, `ParseDateTime()`, `FormatDateTime()` 等 | `fac.Now("Asia/Shanghai")` |
|
||||
| **时间工具** | `GetTimestamp()`, `IsToday()`, `GetBeginOfWeek()` 等 | `fac.GetTimestamp()` |
|
||||
| **加密工具** | `HashPassword()`, `MD5()`, `SHA256()`, `GenerateSMSCode()` 等 | `fac.HashPassword("password")` |
|
||||
@@ -42,6 +43,7 @@
|
||||
|------|----------|----------|
|
||||
| `GetDatabase()` | `*gorm.DB` | 数据库复杂查询、事务、关联查询等 |
|
||||
| `GetRedisClient()` | `*redis.Client` | Hash、List、Set、ZSet、Pub/Sub等高级操作 |
|
||||
| `GetExcel()` | `*excel.Excel` | 多工作表、自定义样式、图表等高级操作 |
|
||||
| `GetLogger()` | `*logger.Logger` | Close()、设置全局logger等 |
|
||||
|
||||
## 使用方法
|
||||
@@ -145,7 +147,54 @@ url, _ := fac.GetFileURL("images/test.jpg", 0)
|
||||
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
|
||||
import "context"
|
||||
@@ -168,7 +217,7 @@ err := fac.RedisDelete(ctx, "user:123", "user:456")
|
||||
exists, err := fac.RedisExists(ctx, "user:123")
|
||||
```
|
||||
|
||||
### 7. 数据库操作(黑盒模式)
|
||||
### 8. 数据库操作(黑盒模式)
|
||||
|
||||
```go
|
||||
// 获取数据库对象(已初始化,黑盒模式)
|
||||
@@ -183,7 +232,7 @@ db.Find(&users)
|
||||
db.Create(&user)
|
||||
```
|
||||
|
||||
### 8. 日期时间操作(黑盒模式)
|
||||
### 9. 日期时间操作(黑盒模式)
|
||||
|
||||
```go
|
||||
// 获取当前时间
|
||||
@@ -205,7 +254,7 @@ unix := fac.ToUnix(now)
|
||||
t2 := fac.FromUnix(unix, "Asia/Shanghai")
|
||||
```
|
||||
|
||||
### 9. 时间操作(黑盒模式)
|
||||
### 10. 时间操作(黑盒模式)
|
||||
|
||||
```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)
|
||||
```
|
||||
|
||||
### 10. 金额计算(黑盒模式)
|
||||
### 11. 金额计算(黑盒模式)
|
||||
|
||||
```go
|
||||
// 元转分
|
||||
@@ -260,7 +309,7 @@ version := fac.GetVersion()
|
||||
fmt.Println("当前版本:", version)
|
||||
```
|
||||
|
||||
### 13. HTTP响应(黑盒模式)
|
||||
### 13. HTTP响应(黑盒模式,推荐)
|
||||
|
||||
```go
|
||||
import "net/http"
|
||||
@@ -277,7 +326,7 @@ fac.Error(w, 1001, "用户不存在")
|
||||
fac.SystemError(w, "系统错误")
|
||||
```
|
||||
|
||||
### 14. HTTP请求解析(黑盒模式)
|
||||
### 14. HTTP请求解析(黑盒模式,推荐)
|
||||
|
||||
```go
|
||||
import "net/http"
|
||||
@@ -300,7 +349,7 @@ isActive := fac.ConvertBool(r.FormValue("is_active"), false)
|
||||
timezone := fac.GetTimezone(r)
|
||||
```
|
||||
|
||||
### 15. Redis操作(获取客户端对象)
|
||||
### 15. Redis操作(获取客户端对象,高级功能)
|
||||
|
||||
```go
|
||||
import (
|
||||
@@ -525,6 +574,54 @@ func main() {
|
||||
|
||||
**返回:** 文件访问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方法(黑盒模式)
|
||||
|
||||
#### RedisGet(ctx context.Context, key string) (string, error)
|
||||
|
||||
@@ -2,10 +2,11 @@
|
||||
|
||||
## 概述
|
||||
|
||||
存储工具提供了文件上传和查看功能,支持OSS和MinIO两种存储方式,并提供HTTP处理器用于文件上传和代理查看。
|
||||
存储工具提供了文件上传和查看功能,支持 **本地文件夹(Local)**、OSS 和 MinIO 三种存储方式,并提供HTTP处理器用于文件上传和代理查看。
|
||||
|
||||
## 功能特性
|
||||
|
||||
- 支持本地文件夹存储(Local)
|
||||
- 支持OSS对象存储(阿里云、腾讯云、AWS、七牛云等)
|
||||
- 支持MinIO对象存储
|
||||
- 提供统一的存储接口
|
||||
@@ -17,6 +18,32 @@
|
||||
|
||||
## 使用方法
|
||||
|
||||
### 0. 工厂调用方式(推荐)
|
||||
|
||||
当你使用 `factory` 黑盒模式时,外部项目无需关心底层是 Local/MinIO/OSS:
|
||||
|
||||
```go
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
|
||||
"git.toowon.com/jimmy/go-common/factory"
|
||||
"git.toowon.com/jimmy/go-common/storage"
|
||||
)
|
||||
|
||||
fac, _ := factory.NewFactoryFromFile("./config.json")
|
||||
|
||||
f, _ := os.Open("test.jpg")
|
||||
defer f.Close()
|
||||
|
||||
objectKey := storage.GenerateObjectKeyWithDate("uploads/images", "test.jpg")
|
||||
url, err := fac.UploadFile(context.Background(), objectKey, f, "image/jpeg")
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
_ = url
|
||||
```
|
||||
|
||||
### 1. 创建存储实例
|
||||
|
||||
```go
|
||||
@@ -42,6 +69,12 @@ minioStorage, err := storage.NewStorage(storage.StorageTypeMinIO, cfg)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
// 创建本地存储实例
|
||||
localStorage, err := storage.NewStorage(storage.StorageTypeLocal, cfg)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
```
|
||||
|
||||
### 2. 上传文件
|
||||
@@ -76,6 +109,25 @@ if err != nil {
|
||||
fmt.Printf("File URL: %s\n", url)
|
||||
```
|
||||
|
||||
### 2.1 本地存储配置示例
|
||||
|
||||
`config.json` 增加 `localStorage` 配置段:
|
||||
|
||||
```json
|
||||
{
|
||||
"localStorage": {
|
||||
"baseDir": "./uploads",
|
||||
"publicURL": "http://localhost:8080/file?key={objectKey}"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
说明:
|
||||
- **baseDir**:文件保存根目录
|
||||
- **publicURL**:用于 `GetURL()` 返回对外可访问的 URL
|
||||
- 推荐配合本文的 `ProxyHandler`,示例 `http://localhost:8080/file?key={objectKey}`
|
||||
- `{objectKey}` 会自动做 `url.QueryEscape` 处理
|
||||
|
||||
### 3. 使用HTTP处理器上传文件
|
||||
|
||||
```go
|
||||
@@ -136,6 +188,10 @@ http.Handle("/file", proxyHandler)
|
||||
http.ListenAndServe(":8080", nil)
|
||||
```
|
||||
|
||||
**本地存储建议搭配:**
|
||||
- `POST /upload` 上传文件(返回 `url`)
|
||||
- `GET /file?key=...` 通过代理读取本地文件并返回二进制内容
|
||||
|
||||
**查看请求示例:**
|
||||
```
|
||||
GET /file?key=images/test.jpg
|
||||
|
||||
@@ -1,3 +1,6 @@
|
||||
//go:build example
|
||||
// +build example
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
|
||||
8
examples/doc.go
Normal file
8
examples/doc.go
Normal file
@@ -0,0 +1,8 @@
|
||||
// Package examples contains build-tagged example programs.
|
||||
//
|
||||
// 所有示例程序默认不参与 `go test ./...` 编译,避免多个 main 冲突。
|
||||
//
|
||||
// 运行示例:
|
||||
// go run -tags example ./examples/storage_example.go
|
||||
package examples
|
||||
|
||||
@@ -1,3 +1,6 @@
|
||||
//go:build example
|
||||
// +build example
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
|
||||
236
examples/excel_example.go
Normal file
236
examples/excel_example.go
Normal file
@@ -0,0 +1,236 @@
|
||||
//go:build example
|
||||
// +build example
|
||||
|
||||
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) {
|
||||
// 模拟实现
|
||||
}
|
||||
@@ -1,3 +1,6 @@
|
||||
//go:build example
|
||||
// +build example
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
@@ -16,24 +19,20 @@ func main() {
|
||||
log.Fatal("Failed to load config:", err)
|
||||
}
|
||||
|
||||
// 创建存储实例(使用OSS)
|
||||
// 注意:需要先实现OSS SDK集成
|
||||
ossStorage, err := storage.NewStorage(storage.StorageTypeOSS, cfg)
|
||||
// 优先演示本地存储(可直接运行)
|
||||
localStorage, err := storage.NewStorage(storage.StorageTypeLocal, cfg)
|
||||
if err != nil {
|
||||
log.Printf("Failed to create OSS storage: %v", err)
|
||||
log.Println("Note: OSS SDK integration is required")
|
||||
// 继续演示其他功能
|
||||
} else {
|
||||
// 创建上传处理器
|
||||
log.Fatal("Failed to create Local storage:", err)
|
||||
}
|
||||
|
||||
uploadHandler := storage.NewUploadHandler(storage.UploadHandlerConfig{
|
||||
Storage: ossStorage,
|
||||
Storage: localStorage,
|
||||
MaxFileSize: 10 * 1024 * 1024, // 10MB
|
||||
AllowedExts: []string{".jpg", ".jpeg", ".png", ".gif", ".pdf"},
|
||||
ObjectPrefix: "uploads/",
|
||||
})
|
||||
|
||||
// 创建代理查看处理器
|
||||
proxyHandler := storage.NewProxyHandler(ossStorage)
|
||||
proxyHandler := storage.NewProxyHandler(localStorage)
|
||||
|
||||
// 创建中间件链
|
||||
var corsConfig *middleware.CORSConfig
|
||||
@@ -58,10 +57,13 @@ func main() {
|
||||
mux.Handle("/upload", chain.Then(uploadHandler))
|
||||
mux.Handle("/file", chain.Then(proxyHandler))
|
||||
|
||||
log.Println("Storage server started on :8080")
|
||||
log.Println("Local storage server started on :8080")
|
||||
log.Println("Upload: POST /upload")
|
||||
log.Println("View: GET /file?key=images/test.jpg")
|
||||
log.Fatal(http.ListenAndServe(":8080", mux))
|
||||
log.Println("View: GET /file?key=uploads/xxx.jpg")
|
||||
|
||||
// 提示:OSS 需要你自行集成对应 SDK(当前 go-common 中仅提供接口框架)
|
||||
if _, err := storage.NewStorage(storage.StorageTypeOSS, cfg); err != nil {
|
||||
log.Printf("OSS storage not ready: %v", err)
|
||||
}
|
||||
|
||||
// 演示MinIO存储
|
||||
@@ -79,5 +81,6 @@ func main() {
|
||||
|
||||
objectKey2 := storage.GenerateObjectKeyWithDate("images", "test.jpg")
|
||||
log.Printf("Object key 2: %s", objectKey2)
|
||||
}
|
||||
|
||||
log.Fatal(http.ListenAndServe(":8080", mux))
|
||||
}
|
||||
|
||||
432
excel/excel.go
Normal file
432
excel/excel.go
Normal file
@@ -0,0 +1,432 @@
|
||||
package excel
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"reflect"
|
||||
"time"
|
||||
|
||||
"git.toowon.com/jimmy/go-common/tools"
|
||||
"github.com/xuri/excelize/v2"
|
||||
)
|
||||
|
||||
// Excel Excel导出器
|
||||
type Excel struct {
|
||||
file *excelize.File
|
||||
}
|
||||
|
||||
// NewExcel 创建Excel导出器
|
||||
func NewExcel() *Excel {
|
||||
return &Excel{
|
||||
file: excelize.NewFile(),
|
||||
}
|
||||
}
|
||||
|
||||
// ExportColumn 导出列定义
|
||||
type ExportColumn struct {
|
||||
// Header 表头名称
|
||||
Header string
|
||||
// Field 数据字段名(支持嵌套字段,如 "User.Name")
|
||||
Field string
|
||||
// Width 列宽(可选,0表示自动)
|
||||
Width float64
|
||||
// Format 格式化函数(可选,用于自定义字段值的格式化)
|
||||
Format func(value interface{}) string
|
||||
}
|
||||
|
||||
// ExportData 导出数据接口
|
||||
// 实现此接口的结构体可以直接导出
|
||||
type ExportData interface {
|
||||
// GetExportColumns 获取导出列定义
|
||||
GetExportColumns() []ExportColumn
|
||||
// GetExportRows 获取导出数据行
|
||||
GetExportRows() [][]interface{}
|
||||
}
|
||||
|
||||
// ExportToWriter 导出数据到Writer(黑盒模式,推荐使用)
|
||||
// sheetName: 工作表名称(可选,默认为"Sheet1")
|
||||
// columns: 列定义
|
||||
// data: 数据列表(可以是结构体切片或实现了ExportData接口的对象)
|
||||
// 返回错误信息
|
||||
//
|
||||
// 示例1:导出结构体切片
|
||||
//
|
||||
// type User struct {
|
||||
// ID int `json:"id"`
|
||||
// Name string `json:"name"`
|
||||
// Email string `json:"email"`
|
||||
// }
|
||||
//
|
||||
// users := []User{
|
||||
// {ID: 1, Name: "Alice", Email: "alice@example.com"},
|
||||
// {ID: 2, Name: "Bob", Email: "bob@example.com"},
|
||||
// }
|
||||
//
|
||||
// columns := []ExportColumn{
|
||||
// {Header: "ID", Field: "ID"},
|
||||
// {Header: "姓名", Field: "Name"},
|
||||
// {Header: "邮箱", Field: "Email"},
|
||||
// }
|
||||
//
|
||||
// excel := excel.NewExcel()
|
||||
// err := excel.ExportToWriter(w, "用户列表", columns, users)
|
||||
//
|
||||
// 示例2:使用格式化函数
|
||||
//
|
||||
// columns := []ExportColumn{
|
||||
// {Header: "ID", Field: "ID"},
|
||||
// {Header: "姓名", Field: "Name"},
|
||||
// {Header: "创建时间", Field: "CreatedAt", Format: func(v interface{}) string {
|
||||
// if t, ok := v.(time.Time); ok {
|
||||
// return t.Format("2006-01-02 15:04:05")
|
||||
// }
|
||||
// return ""
|
||||
// }},
|
||||
// }
|
||||
//
|
||||
// excel.ExportToWriter(w, "用户列表", columns, users)
|
||||
func (e *Excel) ExportToWriter(w io.Writer, sheetName string, columns []ExportColumn, data interface{}) error {
|
||||
if e.file == nil {
|
||||
e.file = excelize.NewFile()
|
||||
}
|
||||
|
||||
// 设置工作表名称
|
||||
if sheetName == "" {
|
||||
sheetName = "Sheet1"
|
||||
}
|
||||
|
||||
// 检查工作表是否已存在
|
||||
sheetIndex, err := e.file.GetSheetIndex(sheetName)
|
||||
if err != nil || sheetIndex == 0 {
|
||||
// 工作表不存在,需要创建
|
||||
// 如果sheetName不是"Sheet1",且默认"Sheet1"存在,则删除它
|
||||
if sheetName != "Sheet1" {
|
||||
defaultIndex, _ := e.file.GetSheetIndex("Sheet1")
|
||||
if defaultIndex > 0 {
|
||||
e.file.DeleteSheet("Sheet1")
|
||||
}
|
||||
}
|
||||
|
||||
// 创建新工作表
|
||||
_, err = e.file.NewSheet(sheetName)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to create sheet: %w", err)
|
||||
}
|
||||
|
||||
// 重新获取工作表索引
|
||||
sheetIndex, err = e.file.GetSheetIndex(sheetName)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to get sheet index: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
// 设置活动工作表
|
||||
if sheetIndex > 0 {
|
||||
e.file.SetActiveSheet(sheetIndex)
|
||||
}
|
||||
|
||||
// 写入表头
|
||||
headerStyle, _ := e.file.NewStyle(&excelize.Style{
|
||||
Font: &excelize.Font{
|
||||
Bold: true,
|
||||
Size: 12,
|
||||
},
|
||||
Fill: excelize.Fill{
|
||||
Type: "pattern",
|
||||
Color: []string{"#E0E0E0"},
|
||||
Pattern: 1,
|
||||
},
|
||||
Alignment: &excelize.Alignment{
|
||||
Horizontal: "center",
|
||||
Vertical: "center",
|
||||
},
|
||||
})
|
||||
|
||||
for i, col := range columns {
|
||||
cell := fmt.Sprintf("%c1", 'A'+i)
|
||||
e.file.SetCellValue(sheetName, cell, col.Header)
|
||||
|
||||
// 设置表头样式
|
||||
e.file.SetCellStyle(sheetName, cell, cell, headerStyle)
|
||||
|
||||
// 设置列宽
|
||||
if col.Width > 0 {
|
||||
colName, _ := excelize.ColumnNumberToName(i + 1)
|
||||
e.file.SetColWidth(sheetName, colName, colName, col.Width)
|
||||
}
|
||||
}
|
||||
|
||||
// 处理数据
|
||||
var rows [][]interface{}
|
||||
|
||||
// 检查数据是否实现了ExportData接口
|
||||
if exportData, ok := data.(ExportData); ok {
|
||||
// 使用接口方法获取数据
|
||||
rows = exportData.GetExportRows()
|
||||
// 如果接口返回nil,初始化为空切片
|
||||
if rows == nil {
|
||||
rows = [][]interface{}{}
|
||||
}
|
||||
} else {
|
||||
// 处理结构体切片(包括nil和空切片的情况)
|
||||
rows, err = e.convertDataToRows(data, columns)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to convert data to rows: %w", err)
|
||||
}
|
||||
// 确保rows不为nil
|
||||
if rows == nil {
|
||||
rows = [][]interface{}{}
|
||||
}
|
||||
}
|
||||
|
||||
// 写入数据行
|
||||
for rowIndex, row := range rows {
|
||||
for colIndex, value := range row {
|
||||
cell := fmt.Sprintf("%c%d", 'A'+colIndex, rowIndex+2) // +2 因为第一行是表头
|
||||
|
||||
// 应用格式化函数
|
||||
var cellValue interface{} = value
|
||||
if colIndex < len(columns) && columns[colIndex].Format != nil {
|
||||
cellValue = columns[colIndex].Format(value)
|
||||
}
|
||||
|
||||
e.file.SetCellValue(sheetName, cell, cellValue)
|
||||
}
|
||||
}
|
||||
|
||||
// 自动调整列宽(如果未设置宽度)
|
||||
for i, col := range columns {
|
||||
if col.Width == 0 {
|
||||
colName, _ := excelize.ColumnNumberToName(i + 1)
|
||||
// 获取列的最大宽度
|
||||
maxWidth := e.getColumnMaxWidth(sheetName, i+1, len(rows)+1)
|
||||
if maxWidth > 0 {
|
||||
e.file.SetColWidth(sheetName, colName, colName, maxWidth)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 写入到Writer
|
||||
return e.file.Write(w)
|
||||
}
|
||||
|
||||
// GetFile 获取Excel文件对象(高级功能时使用)
|
||||
// 返回excelize.File对象,可用于高级操作
|
||||
//
|
||||
// ℹ️ 推荐使用黑盒方法:
|
||||
// - ExportToWriter():导出到Writer(可用于文件、HTTP响应等)
|
||||
//
|
||||
// 仅在需要使用高级功能时获取对象:
|
||||
// - 多工作表操作
|
||||
// - 自定义样式
|
||||
// - 图表、公式等高级功能
|
||||
//
|
||||
// 示例(常用操作,推荐):
|
||||
//
|
||||
// excel := excel.NewExcel()
|
||||
// file, _ := os.Create("users.xlsx")
|
||||
// defer file.Close()
|
||||
// excel.ExportToWriter(file, "用户列表", columns, users)
|
||||
//
|
||||
// 示例(高级功能):
|
||||
//
|
||||
// file := excel.GetFile()
|
||||
// file.NewSheet("Sheet2")
|
||||
// file.SetCellValue("Sheet2", "A1", "数据")
|
||||
func (e *Excel) GetFile() *excelize.File {
|
||||
if e.file == nil {
|
||||
e.file = excelize.NewFile()
|
||||
}
|
||||
return e.file
|
||||
}
|
||||
|
||||
// convertDataToRows 将数据转换为行数据
|
||||
// 支持nil、空切片等情况,返回空切片而不是错误
|
||||
func (e *Excel) convertDataToRows(data interface{}, columns []ExportColumn) ([][]interface{}, error) {
|
||||
// 如果data为nil,返回空切片
|
||||
if data == nil {
|
||||
return [][]interface{}{}, nil
|
||||
}
|
||||
|
||||
// 使用反射处理数据
|
||||
val := reflect.ValueOf(data)
|
||||
if val.Kind() == reflect.Ptr {
|
||||
// 如果是指针且指向nil,返回空切片
|
||||
if val.IsNil() {
|
||||
return [][]interface{}{}, nil
|
||||
}
|
||||
val = val.Elem()
|
||||
}
|
||||
|
||||
// 如果解引用后仍然是无效值,返回空切片
|
||||
if !val.IsValid() {
|
||||
return [][]interface{}{}, nil
|
||||
}
|
||||
|
||||
// 必须是切片类型
|
||||
if val.Kind() != reflect.Slice {
|
||||
return nil, fmt.Errorf("data must be a slice, got %v", val.Kind())
|
||||
}
|
||||
|
||||
// 如果是空切片,返回空切片(不返回错误)
|
||||
if val.Len() == 0 {
|
||||
return [][]interface{}{}, nil
|
||||
}
|
||||
|
||||
rows := make([][]interface{}, 0, val.Len())
|
||||
|
||||
for i := 0; i < val.Len(); i++ {
|
||||
item := val.Index(i)
|
||||
if item.Kind() == reflect.Ptr {
|
||||
// 如果指针指向nil,跳过该行或使用空值
|
||||
if item.IsNil() {
|
||||
row := make([]interface{}, len(columns))
|
||||
rows = append(rows, row)
|
||||
continue
|
||||
}
|
||||
item = item.Elem()
|
||||
}
|
||||
|
||||
row := make([]interface{}, len(columns))
|
||||
for j, col := range columns {
|
||||
value := e.getFieldValue(item, col.Field)
|
||||
row[j] = value
|
||||
}
|
||||
rows = append(rows, row)
|
||||
}
|
||||
|
||||
return rows, nil
|
||||
}
|
||||
|
||||
// getFieldValue 获取字段值(支持嵌套字段)
|
||||
func (e *Excel) getFieldValue(v reflect.Value, fieldPath string) interface{} {
|
||||
if v.Kind() == reflect.Ptr {
|
||||
v = v.Elem()
|
||||
}
|
||||
|
||||
if v.Kind() != reflect.Struct {
|
||||
return nil
|
||||
}
|
||||
|
||||
// 处理嵌套字段(如 "User.Name")
|
||||
fields := splitFieldPath(fieldPath)
|
||||
current := v
|
||||
|
||||
for i, fieldName := range fields {
|
||||
if current.Kind() == reflect.Ptr {
|
||||
current = current.Elem()
|
||||
}
|
||||
|
||||
if current.Kind() != reflect.Struct {
|
||||
return nil
|
||||
}
|
||||
|
||||
field := current.FieldByName(fieldName)
|
||||
if !field.IsValid() {
|
||||
return nil
|
||||
}
|
||||
|
||||
// 如果是最后一个字段,返回值
|
||||
if i == len(fields)-1 {
|
||||
if field.CanInterface() {
|
||||
return field.Interface()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// 继续嵌套查找
|
||||
current = field
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// splitFieldPath 分割字段路径(如 "User.Name" -> ["User", "Name"])
|
||||
func splitFieldPath(path string) []string {
|
||||
result := make([]string, 0)
|
||||
current := ""
|
||||
for _, char := range path {
|
||||
if char == '.' {
|
||||
if current != "" {
|
||||
result = append(result, current)
|
||||
current = ""
|
||||
}
|
||||
} else {
|
||||
current += string(char)
|
||||
}
|
||||
}
|
||||
if current != "" {
|
||||
result = append(result, current)
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
// getColumnMaxWidth 获取列的最大宽度(用于自动调整列宽)
|
||||
func (e *Excel) getColumnMaxWidth(sheetName string, colIndex int, maxRow int) float64 {
|
||||
maxWidth := 10.0 // 默认最小宽度
|
||||
|
||||
for row := 1; row <= maxRow; row++ {
|
||||
cell, _ := excelize.CoordinatesToCellName(colIndex, row)
|
||||
value, err := e.file.GetCellValue(sheetName, cell)
|
||||
if err == nil {
|
||||
width := float64(len(value)) + 2 // 加2作为边距
|
||||
if width > maxWidth {
|
||||
maxWidth = width
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 限制最大宽度
|
||||
if maxWidth > 50 {
|
||||
maxWidth = 50
|
||||
}
|
||||
|
||||
return maxWidth
|
||||
}
|
||||
|
||||
// AdaptTimeFormatter 适配器函数:将tools包的格式化函数转换为Excel Format字段需要的函数类型
|
||||
// 允许直接使用tools包的任何格式化函数
|
||||
//
|
||||
// 示例:
|
||||
//
|
||||
// // 直接使用tools.FormatDate
|
||||
// Format: excel.AdaptTimeFormatter(tools.FormatDate)
|
||||
//
|
||||
// // 使用自定义格式化函数
|
||||
// Format: excel.AdaptTimeFormatter(func(t time.Time) string {
|
||||
// return tools.Format(t, "2006-01-02 15:04:05", "Asia/Shanghai")
|
||||
// })
|
||||
func AdaptTimeFormatter(fn func(time.Time, ...string) string) func(interface{}) string {
|
||||
return func(value interface{}) string {
|
||||
if t, ok := value.(time.Time); ok {
|
||||
return fn(t)
|
||||
}
|
||||
return ""
|
||||
}
|
||||
}
|
||||
|
||||
// formatDateTime 格式化日期时间(内部便捷函数)
|
||||
// 用于ExportColumn的Format字段
|
||||
// layout: 时间格式,如 "2006-01-02 15:04:05"
|
||||
// timezone: 可选时区,如果为空则使用时间对象本身的时区
|
||||
// 直接调用 tools.Format() 方法
|
||||
func formatDateTime(layout string, timezone ...string) func(interface{}) string {
|
||||
return AdaptTimeFormatter(func(t time.Time, _ ...string) string {
|
||||
return tools.Format(t, layout, timezone...)
|
||||
})
|
||||
}
|
||||
|
||||
// formatDate 格式化日期(内部便捷函数)
|
||||
// 用于ExportColumn的Format字段,格式:2006-01-02
|
||||
// 直接调用 tools.FormatDate() 方法
|
||||
var formatDate = AdaptTimeFormatter(tools.FormatDate)
|
||||
|
||||
// formatDateTimeDefault 格式化日期时间(内部便捷函数)
|
||||
// 用于ExportColumn的Format字段,格式:2006-01-02 15:04:05
|
||||
// 直接调用 tools.FormatDateTime() 方法
|
||||
var formatDateTimeDefault = AdaptTimeFormatter(tools.FormatDateTime)
|
||||
|
||||
// formatTime 格式化时间(内部便捷函数)
|
||||
// 用于ExportColumn的Format字段,格式:15:04:05
|
||||
// 直接调用 tools.FormatTime() 方法
|
||||
var formatTime = AdaptTimeFormatter(tools.FormatTime)
|
||||
@@ -5,11 +5,13 @@ import (
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"git.toowon.com/jimmy/go-common/config"
|
||||
"git.toowon.com/jimmy/go-common/email"
|
||||
"git.toowon.com/jimmy/go-common/excel"
|
||||
commonhttp "git.toowon.com/jimmy/go-common/http"
|
||||
"git.toowon.com/jimmy/go-common/i18n"
|
||||
"git.toowon.com/jimmy/go-common/logger"
|
||||
@@ -121,6 +123,7 @@ type Factory struct {
|
||||
db *gorm.DB // 数据库连接(延迟初始化)
|
||||
redis *redis.Client // Redis客户端(延迟初始化)
|
||||
i18n *i18n.I18n // 国际化工具(延迟初始化)
|
||||
excel *excel.Excel // Excel导出器(延迟初始化)
|
||||
}
|
||||
|
||||
// NewFactory 创建工厂实例
|
||||
@@ -650,14 +653,16 @@ func (f *Factory) getStorage() (storage.Storage, error) {
|
||||
}
|
||||
|
||||
// 根据配置自动选择存储类型
|
||||
// 优先级:MinIO > OSS
|
||||
// 优先级:Local > MinIO > OSS
|
||||
var storageType storage.StorageType
|
||||
if f.cfg.MinIO != nil {
|
||||
if f.cfg.GetLocalStorage() != nil {
|
||||
storageType = storage.StorageTypeLocal
|
||||
} else if f.cfg.MinIO != nil {
|
||||
storageType = storage.StorageTypeMinIO
|
||||
} else if f.cfg.OSS != nil {
|
||||
storageType = storage.StorageTypeOSS
|
||||
} else {
|
||||
return nil, fmt.Errorf("no storage config found (OSS or MinIO)")
|
||||
return nil, fmt.Errorf("no storage config found (LocalStorage, OSS or MinIO)")
|
||||
}
|
||||
|
||||
// 创建存储实例
|
||||
@@ -670,6 +675,16 @@ func (f *Factory) getStorage() (storage.Storage, error) {
|
||||
return s, nil
|
||||
}
|
||||
|
||||
// GetStorage 获取存储实例对象(高级功能时使用)
|
||||
// 通常推荐使用黑盒方法:
|
||||
// - UploadFile()
|
||||
// - GetFileURL()
|
||||
//
|
||||
// 如需自定义上传/查看行为(例如 Delete/Exists/GetObject),可使用此方法获取底层存储对象。
|
||||
func (f *Factory) GetStorage() (storage.Storage, error) {
|
||||
return f.getStorage()
|
||||
}
|
||||
|
||||
// UploadFile 上传文件(黑盒模式,推荐使用)
|
||||
// 自动根据配置选择存储类型(OSS 或 MinIO),无需关心内部实现
|
||||
// ctx: 上下文
|
||||
@@ -1553,3 +1568,120 @@ func (f *Factory) GetMessage(lang, code string, args ...interface{}) string {
|
||||
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: 数据列表(可以是结构体切片或实现了ExportData接口的对象)
|
||||
// 返回错误信息
|
||||
//
|
||||
// 示例:
|
||||
//
|
||||
// fac.ExportToExcelFile("users.xlsx", "用户列表", columns, users)
|
||||
//
|
||||
// 注意:此方法内部创建文件并调用 ExportToWriter,确保行为与 ExportToExcel 一致
|
||||
func (f *Factory) ExportToExcelFile(filePath string, sheetName string, columns []ExportColumn, data interface{}) error {
|
||||
e, err := f.getExcelClient()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// 创建文件
|
||||
file, err := os.Create(filePath)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to create file: %w", err)
|
||||
}
|
||||
defer file.Close()
|
||||
|
||||
// 调用 ExportToWriter,复用核心逻辑
|
||||
return e.ExportToWriter(file, sheetName, columns, data)
|
||||
}
|
||||
|
||||
18
go.mod
18
go.mod
@@ -1,12 +1,14 @@
|
||||
module git.toowon.com/jimmy/go-common
|
||||
|
||||
go 1.23.0
|
||||
go 1.24.0
|
||||
|
||||
toolchain go1.24.10
|
||||
|
||||
require (
|
||||
github.com/minio/minio-go/v7 v7.0.97
|
||||
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/postgres 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/md5-simd v1.1.2 // 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/rs/xid v1.6.0 // indirect
|
||||
github.com/tiendc/go-deepcopy v1.7.1 // indirect
|
||||
github.com/tinylib/msgp v1.3.0 // indirect
|
||||
golang.org/x/crypto v0.36.0 // indirect
|
||||
golang.org/x/net v0.38.0 // indirect
|
||||
golang.org/x/sync v0.15.0 // indirect
|
||||
golang.org/x/sys v0.34.0 // indirect
|
||||
golang.org/x/text v0.26.0 // indirect
|
||||
github.com/xuri/efp v0.0.1 // indirect
|
||||
github.com/xuri/nfp v0.0.2-0.20250530014748-2ddeb826f9a9 // indirect
|
||||
golang.org/x/net v0.46.0 // indirect
|
||||
golang.org/x/sync v0.17.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
|
||||
)
|
||||
|
||||
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/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/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/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc=
|
||||
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/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.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg=
|
||||
github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
|
||||
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
|
||||
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/go.mod h1:ykjzy2wzgrlvpDCRc4LA8UXy6D8bzMSuAF3WD57Gok0=
|
||||
golang.org/x/crypto v0.36.0 h1:AnAEvhDddvBdpY+uR+MyHmuZzzNqXSe/GvuDeob5L34=
|
||||
golang.org/x/crypto v0.36.0/go.mod h1:Y4J0ReaxCR1IMaabaSMugxJES1EpwhBHhv2bDHklZvc=
|
||||
golang.org/x/net v0.38.0 h1:vRMAPTMaeGqVhG5QyLJHqNDwecKTomGeqbnfZyKlBI8=
|
||||
golang.org/x/net v0.38.0/go.mod h1:ivrbrMbzFq5J41QOQh0siUuly180yBYtLp+CKbEaFx8=
|
||||
golang.org/x/sync v0.15.0 h1:KWH3jNZsfyT6xfAfKiz6MRNmd46ByHDYaZ7KSkCtdW8=
|
||||
golang.org/x/sync v0.15.0/go.mod h1:1dzgHSNfp02xaA81J2MS99Qcpr2w7fw1gpm99rleRqA=
|
||||
golang.org/x/sys v0.34.0 h1:H5Y5sJ2L2JRdyv7ROF1he/lPdvFsd0mJHFw2ThKHxLA=
|
||||
golang.org/x/sys v0.34.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=
|
||||
golang.org/x/text v0.26.0 h1:P42AVeLghgTYr4+xUnTRKDMqpar+PtX7KWuNQL21L8M=
|
||||
golang.org/x/text v0.26.0/go.mod h1:QK15LZJUUQVJxhz7wXgxSy/CJaTFjd0G+YLonydOVQA=
|
||||
github.com/xuri/efp v0.0.1 h1:fws5Rv3myXyYni8uwj2qKjVaRP30PdjeYe2Y6FDsCL8=
|
||||
github.com/xuri/efp v0.0.1/go.mod h1:ybY/Jr0T0GTCnYjKqmdwxyxn2BQf2RcQIIvex5QldPI=
|
||||
github.com/xuri/excelize/v2 v2.10.0 h1:8aKsP7JD39iKLc6dH5Tw3dgV3sPRh8uRVXu/fMstfW4=
|
||||
github.com/xuri/excelize/v2 v2.10.0/go.mod h1:SC5TzhQkaOsTWpANfm+7bJCldzcnU/jrhqkTi/iBHBU=
|
||||
github.com/xuri/nfp v0.0.2-0.20250530014748-2ddeb826f9a9 h1:+C0TIdyyYmzadGaL/HBLbf3WdLgC29pgyhTjAT/0nuE=
|
||||
github.com/xuri/nfp v0.0.2-0.20250530014748-2ddeb826f9a9/go.mod h1:WwHg+CVyzlv/TX9xqBFXEZAuxOPxn2k1GNHwG41IIUQ=
|
||||
golang.org/x/crypto v0.43.0 h1:dduJYIi3A3KOfdGOHX8AVZ/jGiyPa3IbBozJ5kNuE04=
|
||||
golang.org/x/crypto v0.43.0/go.mod h1:BFbav4mRNlXJL4wNeejLpWxB7wMbc79PdRGhWKncxR0=
|
||||
golang.org/x/image v0.25.0 h1:Y6uW6rH1y5y/LK1J8BPWZtr6yZ7hrsy6hFrXjgsc2fQ=
|
||||
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 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
|
||||
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=
|
||||
|
||||
222
storage/local.go
Normal file
222
storage/local.go
Normal file
@@ -0,0 +1,222 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/url"
|
||||
"os"
|
||||
"path"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"git.toowon.com/jimmy/go-common/config"
|
||||
)
|
||||
|
||||
// LocalStorage 本地存储实现
|
||||
// 将对象写入本地文件夹(BaseDir),对象键 objectKey 作为相对路径使用。
|
||||
//
|
||||
// 典型用法:
|
||||
// - 上传:Upload(ctx, "uploads/2026/01/01/a.png", reader)
|
||||
// - 查看:配合 ProxyHandler 或 http.FileServer 对外提供访问
|
||||
type LocalStorage struct {
|
||||
baseDir string
|
||||
publicURL string
|
||||
}
|
||||
|
||||
// NewLocalStorage 创建本地存储实例
|
||||
func NewLocalStorage(cfg *config.LocalStorageConfig) (*LocalStorage, error) {
|
||||
if cfg == nil {
|
||||
return nil, fmt.Errorf("LocalStorage config is nil")
|
||||
}
|
||||
if strings.TrimSpace(cfg.BaseDir) == "" {
|
||||
return nil, fmt.Errorf("LocalStorage baseDir is empty")
|
||||
}
|
||||
|
||||
absBase, err := filepath.Abs(cfg.BaseDir)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to get absolute baseDir: %w", err)
|
||||
}
|
||||
|
||||
// 确保根目录存在
|
||||
if err := os.MkdirAll(absBase, 0o755); err != nil {
|
||||
return nil, fmt.Errorf("failed to create baseDir: %w", err)
|
||||
}
|
||||
|
||||
return &LocalStorage{
|
||||
baseDir: absBase,
|
||||
publicURL: strings.TrimSpace(cfg.PublicURL),
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Upload 上传文件到本地文件夹
|
||||
func (s *LocalStorage) Upload(ctx context.Context, objectKey string, reader io.Reader, contentType ...string) error {
|
||||
_ = ctx
|
||||
_ = contentType // 本地写文件不依赖 contentType;可由上层自行记录
|
||||
|
||||
dstPath, err := s.resolvePath(objectKey)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// 确保目录存在
|
||||
if err := os.MkdirAll(filepath.Dir(dstPath), 0o755); err != nil {
|
||||
return fmt.Errorf("failed to create directory: %w", err)
|
||||
}
|
||||
|
||||
// 原子写入:先写临时文件,再 rename
|
||||
tmp, err := os.CreateTemp(filepath.Dir(dstPath), ".upload-*")
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to create temp file: %w", err)
|
||||
}
|
||||
|
||||
tmpName := tmp.Name()
|
||||
defer func() {
|
||||
_ = tmp.Close()
|
||||
_ = os.Remove(tmpName)
|
||||
}()
|
||||
|
||||
if _, err := io.Copy(tmp, reader); err != nil {
|
||||
return fmt.Errorf("failed to write temp file: %w", err)
|
||||
}
|
||||
if err := tmp.Close(); err != nil {
|
||||
return fmt.Errorf("failed to close temp file: %w", err)
|
||||
}
|
||||
|
||||
// 如果目标文件已存在,先删除(保证跨平台兼容 rename 行为)
|
||||
_ = os.Remove(dstPath)
|
||||
|
||||
if err := os.Rename(tmpName, dstPath); err != nil {
|
||||
return fmt.Errorf("failed to move temp file to destination: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetURL 获取本地文件访问URL
|
||||
// - 若配置了 publicURL:
|
||||
// - 包含 "{objectKey}" 占位符:替换为 url.QueryEscape(objectKey)
|
||||
// - 否则认为是 URL 前缀:自动拼接 objectKey(用 path.Join 处理斜杠)
|
||||
//
|
||||
// - 未配置 publicURL:返回 objectKey(相对路径)
|
||||
func (s *LocalStorage) GetURL(objectKey string, expires int64) (string, error) {
|
||||
_ = expires // 本地存储不提供签名URL,忽略 expires
|
||||
|
||||
cleanKey, err := normalizeObjectKey(objectKey)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
if s.publicURL == "" {
|
||||
return cleanKey, nil
|
||||
}
|
||||
|
||||
if strings.Contains(s.publicURL, "{objectKey}") {
|
||||
return strings.ReplaceAll(s.publicURL, "{objectKey}", url.QueryEscape(cleanKey)), nil
|
||||
}
|
||||
|
||||
// 作为前缀拼接
|
||||
trimmed := strings.TrimRight(s.publicURL, "/")
|
||||
return trimmed + "/" + path.Clean("/" + cleanKey)[1:], nil
|
||||
}
|
||||
|
||||
// Delete 删除本地文件
|
||||
func (s *LocalStorage) Delete(ctx context.Context, objectKey string) error {
|
||||
_ = ctx
|
||||
|
||||
dstPath, err := s.resolvePath(objectKey)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := os.Remove(dstPath); err != nil {
|
||||
if os.IsNotExist(err) {
|
||||
return nil
|
||||
}
|
||||
return fmt.Errorf("failed to delete file: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Exists 检查本地文件是否存在
|
||||
func (s *LocalStorage) Exists(ctx context.Context, objectKey string) (bool, error) {
|
||||
_ = ctx
|
||||
|
||||
dstPath, err := s.resolvePath(objectKey)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
|
||||
info, err := os.Stat(dstPath)
|
||||
if err != nil {
|
||||
if os.IsNotExist(err) {
|
||||
return false, nil
|
||||
}
|
||||
return false, fmt.Errorf("failed to stat file: %w", err)
|
||||
}
|
||||
if info.IsDir() {
|
||||
return false, nil
|
||||
}
|
||||
return true, nil
|
||||
}
|
||||
|
||||
// GetObject 获取本地文件内容
|
||||
func (s *LocalStorage) GetObject(ctx context.Context, objectKey string) (io.ReadCloser, error) {
|
||||
_ = ctx
|
||||
|
||||
dstPath, err := s.resolvePath(objectKey)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
f, err := os.Open(dstPath)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to open file: %w", err)
|
||||
}
|
||||
return f, nil
|
||||
}
|
||||
|
||||
func (s *LocalStorage) resolvePath(objectKey string) (string, error) {
|
||||
cleanKey, err := normalizeObjectKey(objectKey)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
// 将 URL 风格路径转换为 OS 路径
|
||||
full := filepath.Join(s.baseDir, filepath.FromSlash(cleanKey))
|
||||
|
||||
// 防御:确保仍在 baseDir 下
|
||||
rel, err := filepath.Rel(s.baseDir, full)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("failed to resolve path: %w", err)
|
||||
}
|
||||
if rel == "." || strings.HasPrefix(rel, ".."+string(os.PathSeparator)) || rel == ".." {
|
||||
return "", fmt.Errorf("invalid objectKey: %s", objectKey)
|
||||
}
|
||||
|
||||
return full, nil
|
||||
}
|
||||
|
||||
func normalizeObjectKey(objectKey string) (string, error) {
|
||||
key := strings.TrimSpace(objectKey)
|
||||
if key == "" {
|
||||
return "", fmt.Errorf("objectKey is empty")
|
||||
}
|
||||
|
||||
// 兼容 Windows 风格路径,统一为 URL 风格
|
||||
key = strings.ReplaceAll(key, "\\", "/")
|
||||
|
||||
// 清洗路径,去除多余的 . / ..
|
||||
// 加前缀 "/" 让 Clean 以绝对路径方式处理,避免出现空结果
|
||||
clean := path.Clean("/" + key)
|
||||
clean = strings.TrimPrefix(clean, "/")
|
||||
if clean == "" || clean == "." {
|
||||
return "", fmt.Errorf("invalid objectKey: %s", objectKey)
|
||||
}
|
||||
|
||||
// 不允许以 "/" 结尾(必须指向文件)
|
||||
if strings.HasSuffix(clean, "/") {
|
||||
return "", fmt.Errorf("objectKey cannot be a directory: %s", objectKey)
|
||||
}
|
||||
|
||||
return clean, nil
|
||||
}
|
||||
102
storage/local_test.go
Normal file
102
storage/local_test.go
Normal file
@@ -0,0 +1,102 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"io"
|
||||
"testing"
|
||||
|
||||
"git.toowon.com/jimmy/go-common/config"
|
||||
)
|
||||
|
||||
func TestLocalStorage_UploadGetExistsDelete(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
cfg := &config.LocalStorageConfig{
|
||||
BaseDir: t.TempDir(),
|
||||
PublicURL: "http://localhost:8080/file?key={objectKey}",
|
||||
}
|
||||
s, err := NewLocalStorage(cfg)
|
||||
if err != nil {
|
||||
t.Fatalf("NewLocalStorage error: %v", err)
|
||||
}
|
||||
|
||||
ctx := context.Background()
|
||||
objectKey := "uploads/2026/01/30/hello.txt"
|
||||
body := []byte("hello local storage")
|
||||
|
||||
if err := s.Upload(ctx, objectKey, bytes.NewReader(body), "text/plain"); err != nil {
|
||||
t.Fatalf("Upload error: %v", err)
|
||||
}
|
||||
|
||||
exists, err := s.Exists(ctx, objectKey)
|
||||
if err != nil {
|
||||
t.Fatalf("Exists error: %v", err)
|
||||
}
|
||||
if !exists {
|
||||
t.Fatalf("expected exists=true")
|
||||
}
|
||||
|
||||
rc, err := s.GetObject(ctx, objectKey)
|
||||
if err != nil {
|
||||
t.Fatalf("GetObject error: %v", err)
|
||||
}
|
||||
defer rc.Close()
|
||||
|
||||
got, err := io.ReadAll(rc)
|
||||
if err != nil {
|
||||
t.Fatalf("ReadAll error: %v", err)
|
||||
}
|
||||
if !bytes.Equal(got, body) {
|
||||
t.Fatalf("content mismatch: got=%q want=%q", string(got), string(body))
|
||||
}
|
||||
|
||||
u, err := s.GetURL(objectKey, 0)
|
||||
if err != nil {
|
||||
t.Fatalf("GetURL error: %v", err)
|
||||
}
|
||||
if u == "" {
|
||||
t.Fatalf("expected non-empty url")
|
||||
}
|
||||
|
||||
if err := s.Delete(ctx, objectKey); err != nil {
|
||||
t.Fatalf("Delete error: %v", err)
|
||||
}
|
||||
|
||||
exists, err = s.Exists(ctx, objectKey)
|
||||
if err != nil {
|
||||
t.Fatalf("Exists error: %v", err)
|
||||
}
|
||||
if exists {
|
||||
t.Fatalf("expected exists=false after delete")
|
||||
}
|
||||
}
|
||||
|
||||
func TestNormalizeObjectKey(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
if _, err := normalizeObjectKey(""); err == nil {
|
||||
t.Fatalf("expected error for empty objectKey")
|
||||
}
|
||||
if _, err := normalizeObjectKey(" "); err == nil {
|
||||
t.Fatalf("expected error for blank objectKey")
|
||||
}
|
||||
if _, err := normalizeObjectKey("."); err == nil {
|
||||
t.Fatalf("expected error for '.'")
|
||||
}
|
||||
clean1, err := normalizeObjectKey("a/b/")
|
||||
if err != nil {
|
||||
t.Fatalf("normalizeObjectKey error: %v", err)
|
||||
}
|
||||
if clean1 != "a/b" {
|
||||
t.Fatalf("unexpected clean key: %q", clean1)
|
||||
}
|
||||
|
||||
clean, err := normalizeObjectKey(`\a\..\b\c.txt`)
|
||||
if err != nil {
|
||||
t.Fatalf("normalizeObjectKey error: %v", err)
|
||||
}
|
||||
if clean != "b/c.txt" {
|
||||
t.Fatalf("unexpected clean key: %q", clean)
|
||||
}
|
||||
}
|
||||
@@ -39,10 +39,11 @@ type StorageType string
|
||||
const (
|
||||
StorageTypeOSS StorageType = "oss"
|
||||
StorageTypeMinIO StorageType = "minio"
|
||||
StorageTypeLocal StorageType = "local"
|
||||
)
|
||||
|
||||
// NewStorage 创建存储实例
|
||||
// storageType: 存储类型(oss或minio)
|
||||
// storageType: 存储类型(oss/minio/local)
|
||||
// cfg: 配置对象
|
||||
func NewStorage(storageType StorageType, cfg *config.Config) (Storage, error) {
|
||||
switch storageType {
|
||||
@@ -58,6 +59,12 @@ func NewStorage(storageType StorageType, cfg *config.Config) (Storage, error) {
|
||||
return nil, fmt.Errorf("MinIO config is nil")
|
||||
}
|
||||
return NewMinIOStorage(minioConfig)
|
||||
case StorageTypeLocal:
|
||||
localCfg := cfg.GetLocalStorage()
|
||||
if localCfg == nil {
|
||||
return nil, fmt.Errorf("LocalStorage config is nil")
|
||||
}
|
||||
return NewLocalStorage(localCfg)
|
||||
default:
|
||||
return nil, fmt.Errorf("unsupported storage type: %s", storageType)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user