storage

package
v0.5.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 31, 2026 License: MIT Imports: 16 Imported by: 0

README

pkg/storage - 文件存储服务

强大的通用文件服务工具库,集成多个主流开源库,提供统一的文件操作接口。

API 分类

  • 定位:[CONFIRMED] 公共基础设施 API。
  • 稳定边界:Storage、Config、New、文件读写、复制、监听和 MIME/媒体辅助能力。
  • 当前风险:[CONFIRMED] 复制、MIME、Excel、图片和禁用监听路径已有最小包级测试;真实文件监听事件仍属于后续可扩展测试。
  • 非目标:[CONFIRMED] 本包不定义业务文件目录、权限模型或上传 API。

功能特性

🎯 核心能力
  • 抽象文件系统 - 基于 afero,支持 OS、内存、只读等多种文件系统
  • 文件监听 - 基于 fsnotify,实时监控文件变化
  • 高效复制 - 基于 otiai10/copy,快速复制文件和目录
  • MIME检测 - 基于 mimetype,精准识别文件类型
  • Excel处理 - 基于 excelize,读写和操作 Excel 文件
  • 图片处理 - 基于 imaging,调整大小、裁剪、转码等
✨ 设计优势
  • ✅ 统一接口,屏蔽底层实现细节
  • ✅ 并发安全,所有方法支持并发调用
  • ✅ 灵活配置,支持多种文件系统类型
  • ✅ 易于测试,支持内存文件系统 mock
  • ✅ 功能丰富,一站式文件处理解决方案

安装

go get github.com/rei0721/go-scaffold/pkg/storage

快速开始

package main

import (
    "fmt"
    "log"

    "github.com/rei0721/go-scaffold/pkg/storage"
)

func main() {
    // 创建文件服务实例
    cfg := &storage.Config{
        FSType:   storage.FSTypeOS,
        BasePath: "./data",
    }

    fs, err := storage.New(cfg)
    if err != nil {
        log.Fatal(err)
    }
    defer fs.Close()

    // 写入文件
    err = fs.WriteFile("hello.txt", []byte("Hello, World!"), 0644)
    if err != nil {
        log.Fatal(err)
    }

    // 读取文件
    data, err := fs.ReadFile("hello.txt")
    if err != nil {
        log.Fatal(err)
    }

    fmt.Println(string(data)) // 输出: Hello, World!
}

使用示例

基础文件操作
// 检查文件是否存在
exists, err := fs.Exists("test.txt")

// 创建目录
err = fs.MkdirAll("path/to/dir", 0755)

// 列出目录
files, err := fs.ListDir("path/to/dir")

// 获取文件大小
size, err := fs.FileSize("test.txt")

// 删除文件
err = fs.Remove("test.txt")

// 递归删除目录
err = fs.RemoveAll("path/to/dir")
文件复制
// 复制单个文件
err = fs.Copy("source.txt", "dest.txt")

// 带选项复制
err = fs.Copy("source.txt", "dest.txt",
    storage.WithPreserveTimes(true),
    storage.WithSync(true),
)

// 复制目录
err = fs.CopyDir("./source_dir", "./dest_dir")

// 跳过特定文件
err = fs.CopyDir("./source", "./dest",
    storage.WithSkip(func(path string) bool {
        return strings.HasSuffix(path, ".tmp")
    }),
)
MIME 类型检测
// 从文件检测
mimeType, err := fs.DetectMIME("image.jpg")
fmt.Println(mimeType) // "image/jpeg"

// 从字节数据检测
data, _ := fs.ReadFile("document.pdf")
mimeType, err := fs.DetectMIMEFromBytes(data)
fmt.Println(mimeType) // "application/pdf"
文件监听
// 启动监听
err = fs.Watch("./watch_dir", func(event storage.WatchEvent) {
    fmt.Printf("[%s] %s: %s (IsDir: %v)\n",
        event.Time.Format("15:04:05"),
        event.Op,
        event.Path,
        event.IsDir,
    )
})

// 监听单个文件
err = fs.Watch("config.yaml", func(event storage.WatchEvent) {
    if event.Op == storage.WatchEventWrite {
        fmt.Println("配置文件已更新,重新加载...")
    }
})

// 停止监听
err = fs.StopWatch("./watch_dir")

// 停止所有监听
fs.StopAllWatch()
Excel 文件处理
// 读取 Excel
rows, err := fs.ReadExcelSheet("data.xlsx", "Sheet1")
for i, row := range rows {
    fmt.Printf("Row %d: %v\n", i, row)
}

// 创建 Excel
file := fs.CreateExcel()
file.SetCellValue("Sheet1", "A1", "姓名")
file.SetCellValue("Sheet1", "B1", "年龄")
file.SetCellValue("Sheet1", "A2", "张三")
file.SetCellValue("Sheet1", "B2", 25)

// 保存 Excel
err = fs.SaveExcel(file, "output.xlsx")

// 高级操作
file, err := fs.OpenExcel("template.xlsx")
if err != nil {
    log.Fatal(err)
}
defer file.Close()

// 设置样式
style, _ := file.NewStyle(&excelize.Style{
    Font: &excelize.Font{Bold: true, Size: 14},
    Fill: excelize.Fill{Type: "pattern", Color: []string{"#E0EBF5"}, Pattern: 1},
})
file.SetCellStyle("Sheet1", "A1", "B1", style)

err = fs.SaveExcel(file, "styled.xlsx")
图片处理
// 调整图片大小
err = fs.ResizeImage(
    "input.jpg",
    "output.jpg",
    800,  // 宽度 (0=按比例)
    600,  // 高度 (0=按比例)
    imaging.JPEG,
)

// 裁剪图片
rect := image.Rect(100, 100, 500, 500)
err = fs.CropImage(
    "input.jpg",
    "cropped.jpg",
    rect,
    imaging.PNG,
)

// 高级图片处理
img, err := fs.OpenImage("photo.jpg")
if err != nil {
    log.Fatal(err)
}

// 使用 imaging 库进行更多操作
img = imaging.Blur(img, 2.0)
img = imaging.Sharpen(img, 1.5)
img = imaging.AdjustBrightness(img, 10)

// 保存处理后的图片
err = fs.SaveImage(img, "processed.jpg", imaging.JPEG)

配置说明

字段 类型 默认值 说明
FSType FSType FSTypeOS 文件系统类型
BasePath string . 基础路径 (basepath 类型使用)
EnableWatch bool true 是否启用文件监听
WatchBufferSize int 100 监听事件缓冲区大小
文件系统类型
  • FSTypeOS - 操作系统原生文件系统
  • FSTypeMemory - 内存文件系统 (用于测试)
  • FSTypeReadOnly - 只读文件系统
  • FSTypeBasePathFS - 带基础路径的文件系统
环境变量

可通过环境变量覆盖配置:

export STORAGE_FS_TYPE=os
export STORAGE_BASE_PATH=/var/data
export STORAGE_ENABLE_WATCH=true
export STORAGE_WATCH_BUFFER_SIZE=200

接口文档

FileService 接口

主接口,提供所有文件操作方法。

基础操作:

  • FileSystem() afero.Fs - 获取底层文件系统
  • ReadFile(path string) ([]byte, error) - 读取文件
  • WriteFile(path, data, perm) error - 写入文件
  • Remove(path string) error - 删除文件
  • RemoveAll(path string) error - 删除目录
  • Exists(path string) (bool, error) - 检查存在
  • MkdirAll(path, perm) error - 创建目录
  • IsDir(path string) (bool, error) - 判断是否目录
  • IsFile(path string) (bool, error) - 判断是否文件
  • FileSize(path string) (int64, error) - 获取文件大小
  • ListDir(path string) ([]os.FileInfo, error) - 列出目录

文件复制:

  • Copy(src, dst, ...opts) error - 复制文件
  • CopyDir(src, dst, ...opts) error - 复制目录

MIME检测:

  • DetectMIME(path string) (string, error) - 检测 MIME 类型
  • DetectMIMEFromBytes(data []byte) (string, error) - 从字节检测

文件监听:

  • Watch(path, handler) error - 监听文件/目录
  • StopWatch(path string) error - 停止监听
  • StopAllWatch() - 停止所有监听

Excel操作:

  • OpenExcel(path) (*excelize.File, error) - 打开 Excel
  • CreateExcel() *excelize.File - 创建 Excel
  • SaveExcel(file, path) error - 保存 Excel
  • ReadExcelSheet(path, sheet) ([][]string, error) - 读取工作表

图片操作:

  • OpenImage(path) (image.Image, error) - 打开图片
  • SaveImage(img, path, format) error - 保存图片
  • ResizeImage(src, dst, w, h, format) error - 调整大小
  • CropImage(src, dst, rect, format) error - 裁剪图片

生命周期:

  • Close() error - 关闭服务
  • Reload(ctx, config) error - 重载配置

最佳实践

1. 使用 defer 关闭资源
fs, err := fileservice.New(cfg)
if err != nil {
    return err
}
defer fs.Close()
2. 错误处理
exists, err := fs.Exists("file.txt")
if err != nil {
    // 处理错误
    return fmt.Errorf("failed to check file: %w", err)
}
if !exists {
    // 文件不存在
    return storage.ErrPathNotFound
}
3. 测试时使用内存文件系统
func TestMyFunction(t *testing.T) {
    cfg := &storage.Config{
        FSType: storage.FSTypeMemory,
    }
    fs, _ := storage.New(cfg)
    defer fs.Close()

    // 进行测试...
}
4. 文件监听的资源管理
// 确保停止监听
defer fs.StopWatch("./watch_dir")

// 或使用 context 控制
ctx, cancel := context.WithCancel(context.Background())
defer cancel()

go func() {
    <-ctx.Done()
    fs.StopAllWatch()
}()

线程安全

所有 FileService 方法都是并发安全的,内部使用 sync.RWMutex 保护并发访问。

// 可以安全地在多个 goroutine 中使用
for i := 0; i < 10; i++ {
    go func(n int) {
        data := fmt.Sprintf("data-%d", n)
        fs.WriteFile(fmt.Sprintf("file-%d.txt", n), []byte(data), 0644)
    }(i)
}

依赖库

许可证

本项目使用 MIT 许可证。

Documentation

Overview

Package storage 提供强大的通用文件服务工具库

设计目标

  • 提供统一的文件操作接口,屏蔽底层实现细节
  • 集成多个主流开源库,提供丰富的文件处理能力
  • 支持多种文件系统类型(OS、内存、只读等)
  • 提供文件监听、复制、MIME检测、Excel处理、图片处理等功能

集成的开源库

  • github.com/spf13/afero - 抽象文件系统
  • github.com/fsnotify/fsnotify - 文件监听
  • github.com/otiai10/copy - 高性能文件复制
  • github.com/gabriel-vasile/mimetype - MIME类型检测
  • github.com/xuri/excelize/v2 - Excel文件处理
  • github.com/disintegration/imaging - 图片处理

使用示例

基础文件操作:

cfg := &storage.Config{
    FSType: storage.FSTypeOS,
    BasePath: "./data",
}
fs, err := storage.New(cfg)
if err != nil {
    log.Fatal(err)
}
defer fs.Close()

// 读写文件
err = fs.WriteFile("test.txt", []byte("hello"), 0644)
data, err := fs.ReadFile("test.txt")

文件复制:

// 复制单个文件
err = fs.Copy("source.txt", "dest.txt")

// 复制目录
err = fs.CopyDir("./source_dir", "./dest_dir",
    storage.WithPreserveTimes(true))

MIME检测:

mimeType, err := fs.DetectMIME("image.jpg")
fmt.Println(mimeType) // "image/jpeg"

文件监听:

err = fs.Watch("./watch_dir", func(event storage.WatchEvent) {
    fmt.Printf("File %s: %s\n", event.Op, event.Path)
})
defer fs.StopWatch("./watch_dir")

Excel处理:

// 读取Excel
rows, err := fs.ReadExcelSheet("data.xlsx", "Sheet1")

// 创建Excel
file := fs.CreateExcel()
file.SetCellValue("Sheet1", "A1", "Hello")
err = fs.SaveExcel(file, "output.xlsx")

图片处理:

// 调整图片大小
err = fs.ResizeImage("input.jpg", "output.jpg", 800, 600, imaging.JPEG)

// 裁剪图片
rect := image.Rect(0, 0, 200, 200)
err = fs.CropImage("input.jpg", "cropped.jpg", rect, imaging.PNG)

接口设计

  • Storage: 主接口,提供所有文件操作方法
  • WatchHandler: 文件监听事件处理函数
  • CopyOption: 文件复制选项接口

线程安全

所有方法都是并发安全的,使用 sync.RWMutex 保护内部状态。

Index

Constants

View Source
const (
	// DefaultBasePath 默认基础路径
	DefaultBasePath = "."

	// DefaultFSType 默认文件系统类型
	DefaultFSType = FSTypeOS
)

默认配置值

View Source
const (
	// WatchEventCreate 文件创建事件
	WatchEventCreate = "CREATE"

	// WatchEventWrite 文件写入事件
	WatchEventWrite = "WRITE"

	// WatchEventRemove 文件删除事件
	WatchEventRemove = "REMOVE"

	// WatchEventRename 文件重命名事件
	WatchEventRename = "RENAME"

	// WatchEventChmod 文件权限变更事件
	WatchEventChmod = "CHMOD"
)

文件监听事件类型

Variables

View Source
var (
	// ErrInvalidConfig 无效配置错误
	ErrInvalidConfig = errors.New("Storage: invalid configuration")

	// ErrPathNotFound 路径不存在错误
	ErrPathNotFound = errors.New("Storage: path not found")

	// ErrNotDirectory 非目录错误
	ErrNotDirectory = errors.New("Storage: not a directory")

	// ErrNotFile 非文件错误
	ErrNotFile = errors.New("Storage: not a file")

	// ErrWatcherNotFound 监听器不存在错误
	ErrWatcherNotFound = errors.New("Storage: watcher not found")

	// ErrInvalidFSType 无效的文件系统类型
	ErrInvalidFSType = errors.New("Storage: invalid filesystem type")

	// ErrWatcherAlreadyExists 监听器已存在错误
	ErrWatcherAlreadyExists = errors.New("Storage: watcher already exists for this path")
)

Functions

This section is empty.

Types

type Config

type Config struct {
	// FSType 文件系统类型 (os, memory, readonly, basepath)
	FSType FSType `mapstructure:"fs_type"`

	// BasePath 基础路径,用于 basepath 文件系统类型
	BasePath string `mapstructure:"base_path"`

	// EnableWatch 是否启用文件监听功能
	EnableWatch bool `mapstructure:"enable_watch"`

	// WatchBufferSize 文件监听事件缓冲区大小
	WatchBufferSize int `mapstructure:"watch_buffer_size"`
}

Config 保存文件服务配置

func (*Config) DefaultConfig

func (c *Config) DefaultConfig()

DefaultConfig 返回默认配置

func (*Config) OverrideConfig

func (c *Config) OverrideConfig()

OverrideConfig 从环境变量覆盖配置

func (*Config) Validate

func (c *Config) Validate() error

Validate 验证配置有效性

func (*Config) ValidateName

func (c *Config) ValidateName() string

ValidateName 返回配置名称

type CopyOption

type CopyOption interface {
	// contains filtered or unexported methods
}

CopyOption 文件复制选项接口

func WithPreserveTimes

func WithPreserveTimes(preserve bool) CopyOption

WithPreserveTimes 设置保留时间戳

func WithSkip

func WithSkip(skip func(string) bool) CopyOption

WithSkip 设置跳过函数

func WithSync

func WithSync(sync bool) CopyOption

WithSync 设置同步到磁盘

type FSType

type FSType string

FSType 定义文件系统类型

const (
	// FSTypeOS 使用操作系统原生文件系统
	FSTypeOS FSType = "os"

	// FSTypeMemory 使用内存文件系统(用于测试)
	FSTypeMemory FSType = "memory"

	// FSTypeReadOnly 使用只读文件系统
	FSTypeReadOnly FSType = "readonly"

	// FSTypeBasePathFS 使用带基础路径的文件系统
	FSTypeBasePathFS FSType = "basepath"
)

type Storage

type Storage interface {

	// FileSystem 返回底层的 afero 文件系统实例
	// 用于执行 afero 提供的高级操作
	FileSystem() afero.Fs

	// ReadFile 读取文件内容
	// 参数:
	//   path: 文件路径
	// 返回:
	//   []byte: 文件内容
	//   error: 读取失败时的错误
	ReadFile(path string) ([]byte, error)

	// WriteFile 写入文件内容
	// 参数:
	//   path: 文件路径
	//   data: 要写入的数据
	//   perm: 文件权限
	// 返回:
	//   error: 写入失败时的错误
	WriteFile(path string, data []byte, perm os.FileMode) error

	// Remove 删除文件或空目录
	// 参数:
	//   path: 路径
	// 返回:
	//   error: 删除失败时的错误
	Remove(path string) error

	// RemoveAll 递归删除目录及其内容
	// 参数:
	//   path: 目录路径
	// 返回:
	//   error: 删除失败时的错误
	RemoveAll(path string) error

	// Exists 检查路径是否存在
	// 参数:
	//   path: 路径
	// 返回:
	//   bool: 是否存在
	//   error: 检查失败时的错误
	Exists(path string) (bool, error)

	// MkdirAll 递归创建目录
	// 参数:
	//   path: 目录路径
	//   perm: 目录权限
	// 返回:
	//   error: 创建失败时的错误
	MkdirAll(path string, perm os.FileMode) error

	// IsDir 判断路径是否为目录
	// 参数:
	//   path: 路径
	// 返回:
	//   bool: 是否为目录
	//   error: 检查失败时的错误
	IsDir(path string) (bool, error)

	// IsFile 判断路径是否为文件
	// 参数:
	//   path: 路径
	// 返回:
	//   bool: 是否为文件
	//   error: 检查失败时的错误
	IsFile(path string) (bool, error)

	// FileSize 获取文件大小
	// 参数:
	//   path: 文件路径
	// 返回:
	//   int64: 文件大小(字节)
	//   error: 获取失败时的错误
	FileSize(path string) (int64, error)

	// ListDir 列出目录内容
	// 参数:
	//   path: 目录路径
	// 返回:
	//   []os.FileInfo: 文件信息列表
	//   error: 列出失败时的错误
	ListDir(path string) ([]os.FileInfo, error)

	// Copy 复制单个文件
	// 参数:
	//   src: 源文件路径
	//   dst: 目标文件路径
	//   opts: 复制选项
	// 返回:
	//   error: 复制失败时的错误
	Copy(src, dst string, opts ...CopyOption) error

	// CopyDir 递归复制目录
	// 参数:
	//   src: 源目录路径
	//   dst: 目标目录路径
	//   opts: 复制选项
	// 返回:
	//   error: 复制失败时的错误
	CopyDir(src, dst string, opts ...CopyOption) error

	// DetectMIME 从文件路径检测MIME类型
	// 参数:
	//   path: 文件路径
	// 返回:
	//   string: MIME类型 (如 "image/jpeg")
	//   error: 检测失败时的错误
	DetectMIME(path string) (string, error)

	// DetectMIMEFromBytes 从字节数据检测MIME类型
	// 参数:
	//   data: 文件数据
	// 返回:
	//   string: MIME类型
	//   error: 检测失败时的错误
	DetectMIMEFromBytes(data []byte) (string, error)

	// Watch 监听文件或目录的变化
	// 参数:
	//   path: 要监听的路径
	//   handler: 事件处理函数
	// 返回:
	//   error: 监听失败时的错误
	// 注意:
	//   - 如果路径已被监听,返回 ErrWatcherAlreadyExists
	//   - handler 在独立的 goroutine 中执行
	Watch(path string, handler WatchHandler) error

	// StopWatch 停止监听指定路径
	// 参数:
	//   path: 路径
	// 返回:
	//   error: 停止失败时的错误(如路径未被监听)
	StopWatch(path string) error

	// StopAllWatch 停止所有监听
	StopAllWatch()

	// OpenExcel 打开 Excel 文件
	// 参数:
	//   path: Excel 文件路径
	// 返回:
	//   *excelize.File: Excel 文件对象
	//   error: 打开失败时的错误
	OpenExcel(path string) (*excelize.File, error)

	// CreateExcel 创建新的 Excel 文件
	// 返回:
	//   *excelize.File: Excel 文件对象
	CreateExcel() *excelize.File

	// SaveExcel 保存 Excel 文件
	// 参数:
	//   file: Excel 文件对象
	//   path: 保存路径
	// 返回:
	//   error: 保存失败时的错误
	SaveExcel(file *excelize.File, path string) error

	// ReadExcelSheet 读取 Excel 工作表数据
	// 参数:
	//   path: Excel 文件路径
	//   sheet: 工作表名称
	// 返回:
	//   [][]string: 二维字符串数组(行x列)
	//   error: 读取失败时的错误
	ReadExcelSheet(path, sheet string) ([][]string, error)

	// OpenImage 打开图片文件
	// 参数:
	//   path: 图片文件路径
	// 返回:
	//   image.Image: 图片对象
	//   error: 打开失败时的错误
	OpenImage(path string) (image.Image, error)

	// SaveImage 保存图片文件
	// 参数:
	//   img: 图片对象
	//   path: 保存路径
	//   format: 图片格式 (如 imaging.JPEG, imaging.PNG)
	// 返回:
	//   error: 保存失败时的错误
	SaveImage(img image.Image, path string, format imaging.Format) error

	// ResizeImage 调整图片大小
	// 参数:
	//   src: 源图片路径
	//   dst: 目标图片路径
	//   width: 目标宽度 (0表示按比例)
	//   height: 目标高度 (0表示按比例)
	//   format: 输出格式
	// 返回:
	//   error: 处理失败时的错误
	ResizeImage(src, dst string, width, height int, format imaging.Format) error

	// CropImage 裁剪图片
	// 参数:
	//   src: 源图片路径
	//   dst: 目标图片路径
	//   rect: 裁剪区域
	//   format: 输出格式
	// 返回:
	//   error: 处理失败时的错误
	CropImage(src, dst string, rect image.Rectangle, format imaging.Format) error

	// Close 关闭文件服务,释放资源
	// 返回:
	//   error: 关闭失败时的错误
	Close() error

	// Reload 重新加载配置
	// 参数:
	//   ctx: 上下文
	//   config: 新配置
	// 返回:
	//   error: 重载失败时的错误
	Reload(ctx context.Context, config *Config) error
}

Storage 定义文件服务的接口 提供统一的文件操作API,集成多个开源库提供强大的文件处理能力

设计目标:

  • 抽象文件系统操作,支持多种文件系统类型
  • 集成文件监听、复制、MIME检测等功能
  • 支持 Excel 和图片文件的专业处理
  • 提供统一、易用的接口

使用示例:

cfg := &Storage.Config{
    FSType: Storage.FSTypeOS,
    BasePath: "./data",
}
fs, err := Storage.New(cfg)
if err != nil {
    log.Fatal(err)
}
defer fs.Close()

// 读写文件
err = fs.WriteFile("test.txt", []byte("hello"), 0644)
data, err := fs.ReadFile("test.txt")

func New

func New(cfg *Config) (Storage, error)

New 创建新的 Storage 实例

type SymlinkAction

type SymlinkAction int

SymlinkAction 符号链接处理动作

const (
	// SymlinkShallow 浅复制符号链接
	SymlinkShallow SymlinkAction = iota

	// SymlinkDeep 深复制符号链接指向的内容
	SymlinkDeep

	// SymlinkSkip 跳过符号链接
	SymlinkSkip
)

type WatchEvent

type WatchEvent struct {
	// Path 发生变化的文件路径
	Path string

	// Op 操作类型 (CREATE, WRITE, REMOVE, RENAME, CHMOD)
	Op string

	// Time 事件时间
	Time time.Time

	// IsDir 是否为目录
	IsDir bool
}

WatchEvent 文件监听事件

type WatchHandler

type WatchHandler func(event WatchEvent)

WatchHandler 文件监听事件处理函数

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL
⌂ 换网址