virefs

package module
v0.1.4 Latest Latest
Warning

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

Go to latest
Published: Apr 2, 2026 License: Apache-2.0 Imports: 19 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

VireFS

CI Go Reference GitHub Release License

VireFS 是一个极简的 Go 文件系统抽象库。

它将本地文件系统和 S3 兼容的对象存储统一到同一套接口之下——你的业务代码只跟 key 打交道,不关心文件存在磁盘上还是云端。


定位

一句话:用 key 管理文件,后端透明。

典型使用场景:你的项目既有本地文件(用户上传暂存、导出报表等),又有对象存储里的文件(图片、视频、备份等),文件的 key 存在你的数据库里,通过 VireFS 用同一套 API 操作它们。

你的业务代码 ──key──▶ VireFS ──▶ 本地磁盘 / S3 / MinIO / R2 / ...

架构

flowchart TB
    app["业务代码"]
    app -->|"key"| hooks["WithHooks\n可选拦截层"]
    hooks --> fsInterface["virefs.FS 接口"]

    subgraph backends [存储后端]
        localFS["LocalFS\n本地目录"]
        objectFS["ObjectFS\nS3 兼容对象存储"]
    end

    fsInterface --> localFS
    fsInterface --> objectFS

    localFS -->|"root + key"| disk["本地磁盘"]
    objectFS -->|"prefix + key"| s3["S3 / MinIO / R2"]

    subgraph optional [可选能力]
        presigner["Presigner\n预签名 URL"]
        copier["Copier\n高效复制"]
        accessFn["AccessFunc\nCDN / 自定义 URL"]
    end

    objectFS -.-> presigner
    objectFS -.-> copier
    localFS -.-> copier
    objectFS -.-> accessFn
    localFS -.-> accessFn

核心概念

Key

所有操作以 key 为寻址核心。key 是以 / 分隔的路径,例如 photos/2026/cat.jpg。

  • 自动清理首尾 /、合并重复 /、解析 .
  • 禁止 .. 跳出,保证安全
FS 接口
type FS interface {
    Get(ctx, key)                        // 读取文件内容
    Put(ctx, key, reader, ...PutOption)  // 写入(支持 ContentType、Metadata)
    Delete(ctx, key)                     // 删除
    List(ctx, prefix)                    // 按前缀列举
    Stat(ctx, key)                       // 获取元信息
    Access(ctx, key)                     // 获取外部访问路径/URL
    Exists(ctx, key)                     // 检查 key 是否存在
}
后端
后端 构造函数 root 概念
LocalFS NewLocalFS(rootDir, ...LocalOption) (*LocalFS, error) 指定的本地目录
ObjectFS NewObjectFS(s3Client, bucket, ...ObjectOption) endpoint + bucket
可选能力(类型断言)
接口 说明 实现者
Presigner 生成预签名上传/下载 URL ObjectFS
Copier 同后端高效复制 LocalFS, ObjectFS, MountTable
BatchDeleter 批量删除 ObjectFS(S3 DeleteObjects)
错误模型
哨兵错误 含义
ErrNotFound key 不存在
ErrInvalidKey key 包含非法模式(如 ..)
ErrAlreadyExist 资源已存在(保留)
ErrNotSupported 当前后端不支持此操作
ErrPermission 权限不足

所有后端错误都被包装为 *OpError{Op, Key, Err},方便定位问题。

快速上手

安装
go get github.com/lin-snow/VireFS@latest

建议在生产项目中锁定到具体版本:

go get github.com/lin-snow/VireFS@v0.1.0

所有可用版本请查看 Releases。

本地文件系统
package main

import (
    "context"
    "fmt"
    "io"
    "log"
    "strings"

    virefs "github.com/lin-snow/VireFS"
)

func main() {
    ctx := context.Background()
    fs, err := virefs.NewLocalFS("/tmp/mydata", virefs.WithCreateRoot())
    if err != nil {
        log.Fatal(err)
    }

    // 写入
    if err := fs.Put(ctx, "hello.txt", strings.NewReader("world")); err != nil {
        log.Fatal(err)
    }

    // 读取
    rc, err := fs.Get(ctx, "hello.txt")
    if err != nil {
        log.Fatal(err)
    }
    defer rc.Close()
    data, _ := io.ReadAll(rc)
    fmt.Println(string(data)) // "world"

    // 获取本地路径
    info, err := fs.Access(ctx, "hello.txt")
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println(info.Path) // "/tmp/mydata/hello.txt"
}
对象存储(S3 / MinIO / R2)

推荐:一步到位的便捷构造器

fs, err := virefs.NewObjectFSFromConfig(ctx, &virefs.S3Config{
    Provider:  virefs.ProviderMinIO,
    Endpoint:  "http://localhost:9000",
    Region:    "us-east-1",
    AccessKey: "minioadmin",
    SecretKey: "minioadmin",
    Bucket:    "my-bucket",
}, virefs.WithPrefix("uploads/"))

内置 Provider 预设自动处理各平台怪癖:

Provider 行为
ProviderAWS 默认配置,虚拟主机风格,默认 region us-east-1
ProviderMinIO 自动启用 UsePathStyle
ProviderR2 自动启用 UsePathStyle,默认 region auto

也可以自行构建 *s3.Client(完全控制):

client, err := virefs.NewS3Client(ctx, &virefs.S3Config{
    Provider:  virefs.ProviderR2,
    Endpoint:  "https://<account-id>.r2.cloudflarestorage.com",
    AccessKey: os.Getenv("R2_ACCESS_KEY"),
    SecretKey: os.Getenv("R2_SECRET_KEY"),
})

fs := virefs.NewObjectFS(client, "my-bucket", virefs.WithPrefix("uploads/"))

上传并指定 ContentType:

if err := fs.Put(ctx, "photo.jpg", file,
    virefs.WithContentType("image/jpeg"),
    virefs.WithMetadata(map[string]string{"user": "alice"}),
); err != nil {
    log.Fatal(err)
}

功能详解

Put 选项:ContentType 和 Metadata

ObjectFS 会将这些信息传递给 S3 PutObject;LocalFS 会忽略它们(本地文件系统无此概念)。

err := fs.Put(ctx, "report.pdf", file,
    virefs.WithContentType("application/pdf"),
    virefs.WithMetadata(map[string]string{"version": "2"}),
)
Exists — 检查 key 是否存在

Exists 是 FS 接口方法,各后端有最优实现(S3 用 HeadObject,本地用 os.Stat)。 也保留了包级别便捷函数:

// 接口方法
ok, err := fs.Exists(ctx, "maybe.txt")

// 包级别函数(等价)
ok, err = virefs.Exists(ctx, fs, "maybe.txt")
Copy — 文件复制

同后端复制走原生高效路径(S3 CopyObject、本地文件复制),跨后端自动退化为 Get + Put。

// 同后端(S3 内部复制,无需下载再上传)
err := virefs.Copy(ctx, objFS, "src.txt", objFS, "dst.txt")

// 跨后端(本地 → S3)
err = virefs.Copy(ctx, localFS, "export.csv", objFS, "imports/export.csv",
    virefs.WithContentType("text/csv"),
)
Access — 获取外部访问信息

核心 FS 接口方法,根据后端返回不同内容。Path 和 URL 可以同时存在。

后端 AccessInfo.Path AccessInfo.URL
LocalFS(无 AccessFunc) 绝对文件路径 空
LocalFS(有 AccessFunc) 绝对文件路径 AccessFunc 生成的 URL
ObjectFS 空 预签名/公开/CDN URL
// LocalFS — 同时获取磁盘路径和 HTTP URL
localFS, _ := virefs.NewLocalFS("/data/files",
    virefs.WithLocalAccessFunc(func(key string) *virefs.AccessInfo {
        return &virefs.AccessInfo{URL: "https://cdn.example.com/files/" + key}
    }),
)
info, _ := localFS.Access(ctx, "images/logo.png")
fmt.Println(info.Path) // "/data/files/images/logo.png"
fmt.Println(info.URL)  // "https://cdn.example.com/files/images/logo.png"

// ObjectFS(自动选择:AccessFunc > Presign > BaseURL)
info, err = objFS.Access(ctx, "doc.pdf")
fmt.Println(info.URL)

ObjectFS 自定义 CDN 域名:

fs := virefs.NewObjectFS(client, "bucket",
    virefs.WithPrefix("assets/"),
    virefs.WithAccessFunc(func(key string) *virefs.AccessInfo {
        return &virefs.AccessInfo{URL: "https://cdn.example.com/" + key}
    }),
)
// Access("img/logo.png") → "https://cdn.example.com/assets/img/logo.png"
预签名 URL

通过 Presigner 可选接口,使用类型断言获取预签名能力:

fs := virefs.NewObjectFS(client, "bucket",
    virefs.WithPresignClient(s3.NewPresignClient(client)),
)

if p, ok := fs.(virefs.Presigner); ok {
    get, err := p.PresignGet(ctx, "secret.pdf", 15*time.Minute)
    put, err := p.PresignPut(ctx, "upload.zip", 30*time.Minute)
    fmt.Println(get.URL, put.URL, err)
}
原子写入(LocalFS)

启用后 Put 先写临时文件,再原子 rename,防止并发写入数据损坏。

fs, _ := virefs.NewLocalFS("/data", virefs.WithAtomicWrite())
Key 变换(KeyFunc)

在 CleanKey 之后、实际存储操作之前,对 key 进行自定义变换:

fs, _ := virefs.NewLocalFS("/data", virefs.WithLocalKeyFunc(func(key string) string {
    return time.Now().Format("2006/01/02") + "/" + key
}))
// Put("photo.jpg") → 实际写入 /data/2026/03/06/photo.jpg
Schema — 声明式文件组织

用户数据库里只存简单的文件名(如 cat.jpg),但希望实际存储时按业务规则分目录。Schema 提供声明式的路由规则,按扩展名或自定义函数将文件归类到不同目录前缀。

schema := virefs.NewSchema(
    virefs.RouteByExt("images/", ".jpg", ".jpeg", ".png", ".gif", ".webp"),
    virefs.RouteByExt("videos/", ".mp4", ".avi", ".mkv"),
    virefs.RouteByExt("docs/",   ".pdf", ".doc", ".docx"),
    virefs.DefaultRoute("other/"),
)

// 通过 WithLocalKeyFunc / WithObjectKeyFunc 接入
fs, _ := virefs.NewLocalFS("/data", virefs.WithLocalKeyFunc(schema.Resolve))

fs.Put(ctx, "cat.jpg", r)       // → /data/images/cat.jpg
fs.Put(ctx, "report.pdf", r)    // → /data/docs/report.pdf
fs.Put(ctx, "readme.txt", r)    // → /data/other/readme.txt

对象存储同理:

objFS := virefs.NewObjectFS(client, "bucket",
    virefs.WithPrefix("uploads/"),
    virefs.WithObjectKeyFunc(schema.Resolve),
)
// Put("cat.jpg") → S3 key: uploads/images/cat.jpg

路由规则按声明顺序匹配,第一个命中的生效。支持自定义匹配函数:

virefs.RouteByFunc("archives/", func(key string) bool {
    return strings.HasSuffix(key, ".tar.gz") || strings.HasSuffix(key, ".zip")
})
Walk — 递归遍历

递归列举 prefix 下的所有文件和目录(基于 List 的浅层语义递归展开):

err := virefs.Walk(ctx, fs, "", func(key string, info virefs.FileInfo, err error) error {
    if err != nil {
        return err
    }
    fmt.Println(key, info.Size)
    return nil
})

返回 virefs.ErrSkipDir 可跳过指定子目录。

BatchDelete — 批量删除

ObjectFS 使用 S3 DeleteObjects 实现高效批量删除,其他后端自动退化为逐个删除:

err := virefs.BatchDelete(ctx, fs, []string{"a.txt", "b.txt", "c.txt"})
Migrate — 批量迁移

Migrate 递归复制文件,支持冲突策略、DryRun、进度回调和 key 变换:

result, err := virefs.Migrate(ctx, srcFS, "old-data", dstFS, "new-data",
    virefs.WithConflictPolicy(virefs.ConflictSkip),
    virefs.WithProgressFunc(func(p virefs.MigrateProgress) {
        fmt.Printf("[%d/%d] %s\n", p.Copied+p.Skipped, p.Total, p.Key)
    }),
)
fmt.Printf("copied=%d skipped=%d total=%d\n", result.Copied, result.Skipped, result.Total)

冲突策略:

策略 行为
ConflictError 遇到已存在的 key 立即返回错误(默认)
ConflictSkip 跳过已存在的 key
ConflictOverwrite 覆盖已存在的 key

DryRun 模式只遍历不复制,报告将会发生的操作:

result, _ := virefs.Migrate(ctx, src, "", dst, "",
    virefs.WithDryRun(),
    virefs.WithConflictPolicy(virefs.ConflictSkip),
)

Key 变换——迁移时重命名文件:

virefs.WithMigrateKeyFunc(func(key string) string {
    return "v2/" + key
})
Stat — 获取文件元信息(含 ContentType)

Stat 返回的 FileInfo 包含 ContentType 字段,所有后端行为一致:

  • ObjectFS:从 S3 HeadObject 响应中读取真实的 Content-Type
  • LocalFS:通过文件扩展名推断(基于标准库 mime.TypeByExtension)
info, _ := fs.Stat(ctx, "photos/cat.jpg")

fmt.Println(info.Key)         // "photos/cat.jpg"
fmt.Println(info.Size)        // 102400
fmt.Println(info.ContentType) // "image/jpeg"

// 直接用于填充业务数据库
db.Exec("INSERT INTO files (key, size, content_type) VALUES (?, ?, ?)",
    info.Key, info.Size, info.ContentType)
WithHooks — 操作拦截

WithHooks 可以给任意 FS 添加拦截逻辑,无需手写 6 个方法的转发样板。所有 hook 字段可选,nil 表示不拦截。

hfs := virefs.WithHooks(fs, virefs.Hooks{
    // 包装 Get 返回的 reader(用于计算 hash、解密等)
    WrapGet: func(key string, rc io.ReadCloser) io.ReadCloser {
        return myHashReader(rc)
    },
    // 包装 Put 的输入 reader(用于加密、压缩等)
    WrapPut: func(key string, r io.Reader) io.Reader {
        return myEncryptReader(r)
    },
    // Stat 成功后修改 FileInfo(用于补充信息)
    AfterStat: func(key string, info *virefs.FileInfo) {
        info.ContentType = "custom/override"
    },
    // Delete 成功后回调(用于日志、缓存清理等)
    OnDelete: func(key string) {
        log.Printf("deleted: %s", key)
    },
})

// 像普通 FS 一样使用,hook 自动生效
rc, _ := hfs.Get(ctx, "secret.dat")  // WrapGet 自动应用
hfs.Put(ctx, "encrypted.bin", data)   // WrapPut 自动应用

// 需要访问底层 FS 的可选接口时,通过 Unwrap 获取
inner := hfs.Unwrap()
if p, ok := inner.(virefs.Presigner); ok {
    req, _ := p.PresignGet(ctx, "file.txt", 15*time.Minute)
    fmt.Println(req.URL)
}
Chain — 中间件链

需要同时做日志、加密、限速等多层拦截时,使用 Chain + Middleware 组合多个层。 中间件按声明顺序依次包裹,最后一个中间件处于最外层(调用者最先触达):

fs := virefs.Chain(baseFS,
    encryptionMiddleware(key),    // 内层:靠近 baseFS
    loggingMiddleware(logger),    // 外层:调用者最先触达
)

编写自定义中间件:嵌入 BaseFS,只覆盖需要拦截的方法:

type metricsFS struct {
    virefs.BaseFS
    counter *atomic.Int64
}

func (m *metricsFS) Get(ctx context.Context, key string) (io.ReadCloser, error) {
    m.counter.Add(1)
    return m.Inner.Get(ctx, key)
}

func metricsMiddleware(counter *atomic.Int64) virefs.Middleware {
    return func(next virefs.FS) virefs.FS {
        return &metricsFS{BaseFS: virefs.BaseFS{Inner: next}, counter: counter}
    }
}

WithHooks 可以直接在 Chain 中使用——它本身就是一个中间件:

fs := virefs.Chain(baseFS,
    func(next virefs.FS) virefs.FS {
        return virefs.WithHooks(next, virefs.Hooks{
            OnDelete: func(key string) { log.Println("deleted:", key) },
        })
    },
    metricsMiddleware(counter),
)
MountTable — 多后端路由(可选)

当需要通过单个 FS 接口操作多个后端时,使用 MountTable 按前缀路由:

mt := virefs.NewMountTable()
local, _ := virefs.NewLocalFS("/data/files")
mt.Mount("local", local)
mt.Mount("s3",    virefs.NewObjectFS(s3Client, "my-bucket"))

mt.Get(ctx, "local/reports/q1.csv")  // → LocalFS
mt.Put(ctx, "s3/images/logo.png", r) // → ObjectFS

Key 处理流水线

flowchart LR
    raw["原始 key"] --> clean["CleanKey\n规范化 + 安全校验"]
    clean --> keyFunc["KeyFunc\n用户自定义变换"]
    keyFunc --> prefix["basePrefix\n拼接前缀"]
    prefix --> backend["存储后端操作"]

完整 Option 速查

LocalFS
Option 说明
WithCreateRoot() root 目录不存在时自动创建
WithDirPerm(perm) 自动创建目录的权限(默认 0755)
WithLocalKeyFunc(fn) key 变换函数
WithAtomicWrite() 启用原子写入
WithLocalAccessFunc(fn) 自定义 Access URL 生成(Path + URL 同时返回)
ObjectFS
Option 说明
WithPrefix(p) 所有 key 添加前缀
WithObjectKeyFunc(fn) key 变换函数
WithPresignClient(pc) 启用预签名 URL
WithBaseURL(url) Access 公开 URL 基地址
WithAccessExpires(d) Access 预签名默认过期时间
WithAccessFunc(fn) 自定义 Access URL 生成
Put
Option 说明
WithContentType(ct) 设置 MIME 类型
WithMetadata(m) 设置自定义元数据

参与贡献

欢迎贡献代码、报告 Bug 或提出建议!请阅读 CONTRIBUTING.md 了解开发流程和规范。

License

Apache License 2.0

Documentation

Overview

Package virefs provides a unified file system abstraction over local directories and S3-compatible object stores.

All operations are key-based: a key is a forward-slash separated path such as "photos/2026/cat.jpg". Keys are automatically normalised by CleanKey — leading/trailing slashes are trimmed, duplicate slashes collapsed, and ".." traversals rejected.

Core interface

FS is the minimal interface every storage backend implements. It provides Get, Put, Delete, List, Stat, Access, and Exists operations.

Two built-in backends are included:

  • LocalFS — backed by a local directory on disk.
  • ObjectFS — backed by any S3-compatible object store (AWS S3, MinIO, Cloudflare R2, etc.).

S3 client construction

S3Config and NewS3Client simplify the creation of S3 clients with provider-aware defaults for AWS, MinIO, and Cloudflare R2. Use NewObjectFSFromConfig to create an ObjectFS (with presign support) in a single call.

Optional capabilities

Some backends support additional operations exposed through optional interfaces. Use type assertions to check:

  • Copier — efficient same-backend copy (LocalFS, ObjectFS).
  • Presigner — presigned upload/download URLs (ObjectFS).
  • BatchDeleter — bulk deletion (ObjectFS via S3 DeleteObjects).

Composition

MountTable routes operations to different backends by key prefix, allowing a single FS handle to span multiple storage backends.

Schema provides declarative key routing by file extension or custom match functions, and plugs into any backend via KeyFunc.

Hooks and middleware

WithHooks wraps any FS with optional interceptors (Hooks) for Get, Put, Stat and Delete — no need to implement all seven FS methods just to add behaviour to one. The returned hookFS deliberately does not forward optional interfaces (Copier, Presigner, BatchDeleter) so that all data operations pass through the hooks.

For more complex scenarios (multiple layers, intercepting any method), use Chain with Middleware functions. Embed BaseFS in a custom struct to forward all methods and override only those you need.

Helpers

Package-level functions Copy, BatchDelete, Exists, Walk, and Migrate work with any FS implementation. Migrate supports conflict policies (ConflictSkip, ConflictOverwrite, ConflictError), dry-run mode, and progress callbacks for bulk data migration.

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	ErrNotFound     = errors.New("virefs: not found")
	ErrInvalidKey   = errors.New("virefs: invalid key")
	ErrAlreadyExist = errors.New("virefs: already exists")
	ErrNotSupported = errors.New("virefs: operation not supported")
	ErrPermission   = errors.New("virefs: permission denied")
)

Sentinel errors shared across all FS implementations.

View Source
var ErrSkipDir = errors.New("skip this directory")

ErrSkipDir is used as a return value from WalkFunc to indicate that the directory named in the call is to be skipped. It is not returned as an error by Walk itself.

Functions

func BatchDelete

func BatchDelete(ctx context.Context, fsys FS, keys []string) error

BatchDelete deletes multiple keys from fsys. If fsys implements BatchDeleter, the native bulk operation is used. Otherwise it falls back to calling Delete for each key individually, returning the first error encountered.

func CleanKey

func CleanKey(raw string) (string, error)

CleanKey normalises a key: trims leading/trailing slashes, collapses repeated slashes, resolves "." segments and rejects ".." traversals.

func Copy

func Copy(ctx context.Context, src FS, srcKey string, dst FS, dstKey string, opts ...PutOption) error

Copy copies a file from src to dst. If src and dst are the same FS instance and it implements Copier, the native (efficient) copy is used. Otherwise it falls back to Get + Put.

Example
package main

import (
	"context"
	"fmt"
	"io"
	"log"
	"os"
	"strings"

	virefs "github.com/lin-snow/VireFS"
)

func main() {
	dir, _ := os.MkdirTemp("", "virefs-example-*")
	defer os.RemoveAll(dir)

	fs, err := virefs.NewLocalFS(dir)
	if err != nil {
		log.Fatal(err)
	}
	ctx := context.Background()

	_ = fs.Put(ctx, "src.txt", strings.NewReader("data"))

	if err := virefs.Copy(ctx, fs, "src.txt", fs, "dst.txt"); err != nil {
		log.Fatal(err)
	}

	rc, _ := fs.Get(ctx, "dst.txt")
	defer rc.Close()
	data, _ := io.ReadAll(rc)
	fmt.Println(string(data))
}
Output:
data

func Exists

func Exists(ctx context.Context, fs FS, key string) (bool, error)

Exists is a convenience helper that delegates to fs.Exists. It is kept for backward compatibility with code that calls the package-level function instead of the interface method.

func NewS3Client added in v0.1.1

func NewS3Client(ctx context.Context, cfg *S3Config) (*s3.Client, error)

NewS3Client creates an *s3.Client from the given S3Config. Provider-specific quirks (path style, default region) are applied automatically. The caller's S3Config is not modified.

For ProviderMinIO, request checksum calculation is set to aws.RequestChecksumCalculationWhenRequired to avoid compatibility issues with aws-chunked uploads on large objects.

func Walk

func Walk(ctx context.Context, fsys FS, prefix string, fn WalkFunc) error

Walk recursively traverses the file tree rooted at prefix, calling fn for each file or directory (including prefix itself if it is a directory). It uses List internally and recurses into sub-directories (IsDir == true).

Example
package main

import (
	"context"
	"fmt"
	"log"
	"os"
	"strings"

	virefs "github.com/lin-snow/VireFS"
)

func main() {
	dir, _ := os.MkdirTemp("", "virefs-example-*")
	defer os.RemoveAll(dir)

	fs, err := virefs.NewLocalFS(dir)
	if err != nil {
		log.Fatal(err)
	}
	ctx := context.Background()

	_ = fs.Put(ctx, "a.txt", strings.NewReader("a"))
	_ = fs.Put(ctx, "sub/b.txt", strings.NewReader("b"))

	var count int
	_ = virefs.Walk(ctx, fs, "", func(key string, info virefs.FileInfo, err error) error {
		if err != nil {
			return err
		}
		if !info.IsDir {
			count++
		}
		return nil
	})
	fmt.Println(count)
}
Output:
2

func WithHooks

func WithHooks(inner FS, hooks Hooks) *hookFS

WithHooks returns a new FS that applies hooks to every operation on inner. Operations whose hook field is nil are forwarded to inner unchanged.

The returned FS intentionally does NOT implement optional interfaces (Copier, Presigner, BatchDeleter) so that all data operations pass through the hooks. Call [hookFS.Unwrap] to access the inner FS directly.

Types

type AccessFunc

type AccessFunc func(key string) *AccessInfo

AccessFunc builds an AccessInfo for a fully resolved storage key (after CleanKey + KeyFunc + basePrefix). Use it to implement custom URL schemes such as CDN domains or per-file-type routing.

type AccessInfo

type AccessInfo struct {
	// Path is the absolute local file path (set by LocalFS).
	Path string
	// URL is a directly accessible URL (set by ObjectFS — presigned or public,
	// or by LocalFS when an AccessFunc is configured).
	URL string
}

AccessInfo describes how to access a file from outside the FS abstraction. At least one of Path or URL will be non-empty; both may be set simultaneously (e.g. LocalFS with an AccessFunc that adds an HTTP URL).

type BaseFS added in v0.1.1

type BaseFS struct{ Inner FS }

BaseFS forwards every FS method to Inner. Embed it in a custom struct and override only the methods you want to intercept:

type myFS struct {
    virefs.BaseFS
}

func (m *myFS) Get(ctx context.Context, key string) (io.ReadCloser, error) {
    log.Println("get", key)
    return m.Inner.Get(ctx, key)
}

func (BaseFS) Access added in v0.1.1

func (b BaseFS) Access(ctx context.Context, key string) (*AccessInfo, error)

Access implements FS by forwarding to Inner.

func (BaseFS) Delete added in v0.1.1

func (b BaseFS) Delete(ctx context.Context, key string) error

Delete implements FS by forwarding to Inner.

func (BaseFS) Exists added in v0.1.1

func (b BaseFS) Exists(ctx context.Context, key string) (bool, error)

Exists implements FS by forwarding to Inner.

func (BaseFS) Get added in v0.1.1

func (b BaseFS) Get(ctx context.Context, key string) (io.ReadCloser, error)

Get implements FS by forwarding to Inner.

func (BaseFS) List added in v0.1.1

func (b BaseFS) List(ctx context.Context, prefix string) (*ListResult, error)

List implements FS by forwarding to Inner.

func (BaseFS) Put added in v0.1.1

func (b BaseFS) Put(ctx context.Context, key string, r io.Reader, opts ...PutOption) error

Put implements FS by forwarding to Inner.

func (BaseFS) Stat added in v0.1.1

func (b BaseFS) Stat(ctx context.Context, key string) (*FileInfo, error)

Stat implements FS by forwarding to Inner.

type BatchDeleter

type BatchDeleter interface {
	BatchDelete(ctx context.Context, keys []string) error
}

BatchDeleter is an optional interface for efficient bulk deletion. ObjectFS implements this using S3 DeleteObjects. Use a type assertion to check: if bd, ok := fs.(BatchDeleter); ok { ... }

type ConflictPolicy added in v0.1.1

type ConflictPolicy int

ConflictPolicy controls how Migrate behaves when a destination key already exists.

const (
	// ConflictError causes Migrate to return an error on the first conflict.
	ConflictError ConflictPolicy = iota
	// ConflictSkip silently skips keys that already exist at the destination.
	ConflictSkip
	// ConflictOverwrite overwrites existing keys at the destination.
	ConflictOverwrite
)

type Copier

type Copier interface {
	Copy(ctx context.Context, srcKey, dstKey string) error
}

Copier is an optional interface for efficient same-backend copies. Use a type assertion to check: if c, ok := fs.(Copier); ok { ... }

type FS

type FS interface {
	// Get returns a ReadCloser for the content addressed by key.
	Get(ctx context.Context, key string) (io.ReadCloser, error)

	// Put writes content from r under the given key.
	// If the key already exists its content is overwritten.
	// Use PutOption to set ContentType, Metadata, etc.
	Put(ctx context.Context, key string, r io.Reader, opts ...PutOption) error

	// Delete removes the object addressed by key.
	// Behaviour when the key does not exist is backend-specific:
	// LocalFS returns ErrNotFound; ObjectFS silently succeeds (S3 idempotent delete).
	Delete(ctx context.Context, key string) error

	// List returns immediate children (files and sub-directories) under prefix.
	// Sub-directories are returned as FileInfo with IsDir == true.
	// Pass an empty prefix to list the root level.
	List(ctx context.Context, prefix string) (*ListResult, error)

	// Stat returns metadata for a single key.
	// Returns ErrNotFound if the key does not exist.
	Stat(ctx context.Context, key string) (*FileInfo, error)

	// Access returns backend-specific access information for the given key.
	// LocalFS returns AccessInfo.Path (absolute file path).
	// ObjectFS returns AccessInfo.URL (presigned or public URL).
	Access(ctx context.Context, key string) (*AccessInfo, error)

	// Exists reports whether a key exists in the backend.
	// It returns (false, nil) when the key is not found, rather than an error.
	// Backends may implement this more efficiently than Stat (e.g. S3 HeadObject).
	Exists(ctx context.Context, key string) (bool, error)
}

FS is the minimal interface every storage backend must implement. All keys use forward-slash separated paths with no leading slash.

func Chain added in v0.1.1

func Chain(fs FS, mw ...Middleware) FS

Chain applies middlewares to fs in declaration order. Each middleware wraps the result of the previous one, so the first middleware is closest to the base FS (innermost) and the last middleware is outermost (its methods are called first by the caller).

fs := virefs.Chain(baseFS,
    innerMiddleware,  // applied first, closest to baseFS
    outerMiddleware,  // applied last, outermost layer
)
Example
package main

import (
	"context"
	"fmt"
	"io"
	"os"
	"strings"

	virefs "github.com/lin-snow/VireFS"
)

func main() {
	dir, _ := os.MkdirTemp("", "virefs-example-*")
	defer os.RemoveAll(dir)

	base, _ := virefs.NewLocalFS(dir)
	ctx := context.Background()

	_ = base.Put(ctx, "secret.txt", strings.NewReader("classified"))

	// Chain: uppercase is inner (closest to base), logging is outer (caller hits first)
	fs := virefs.Chain(base,
		func(next virefs.FS) virefs.FS { // inner: uppercase
			return &uppercaseFS{virefs.BaseFS{Inner: next}}
		},
		func(next virefs.FS) virefs.FS { // outer: audit log
			return virefs.WithHooks(next, virefs.Hooks{
				WrapGet: func(key string, rc io.ReadCloser) io.ReadCloser {
					fmt.Println("audit: read", key)
					return rc
				},
			})
		},
	)

	rc, _ := fs.Get(ctx, "secret.txt")
	data, _ := io.ReadAll(rc)
	rc.Close()
	fmt.Println(string(data))
}

type uppercaseFS struct{ virefs.BaseFS }

func (u *uppercaseFS) Get(ctx context.Context, key string) (io.ReadCloser, error) {
	rc, err := u.Inner.Get(ctx, key)
	if err != nil {
		return nil, err
	}
	data, _ := io.ReadAll(rc)
	rc.Close()
	return io.NopCloser(strings.NewReader(strings.ToUpper(string(data)))), nil
}
Output:
audit: read secret.txt
CLASSIFIED

type FileInfo

type FileInfo struct {
	Key          string
	Size         int64
	LastModified time.Time
	IsDir        bool
	ContentType  string // MIME type, e.g. "image/jpeg"; may be empty
}

FileInfo describes a single object / file stored in a FS.

type Hooks

type Hooks struct {
	// WrapGet wraps the ReadCloser returned by a successful Get.
	// Use this for on-the-fly hashing, decryption, decompression, etc.
	WrapGet func(key string, rc io.ReadCloser) io.ReadCloser

	// WrapPut wraps the Reader before it reaches Put.
	// Use this for encryption, compression, byte counting, etc.
	WrapPut func(key string, r io.Reader) io.Reader

	// AfterStat is called after a successful Stat. The hook may mutate
	// the FileInfo in place (e.g. to enrich metadata).
	AfterStat func(key string, info *FileInfo)

	// OnDelete is called after a successful Delete.
	// Use this for audit logging, cache invalidation, etc.
	OnDelete func(key string)
}

Hooks defines optional interceptors for FS operations. A nil field means the corresponding operation is not intercepted.

Use WithHooks to apply hooks to any FS implementation.

type KeyFunc

type KeyFunc func(key string) string

KeyFunc transforms a cleaned key before it reaches the storage backend. It is called after CleanKey, so the input is already normalised (no "..", no leading/trailing slashes). The returned string is used as-is.

type ListResult

type ListResult struct {
	Files []FileInfo
}

ListResult is returned by FS.List.

type LocalFS

type LocalFS struct {
	// contains filtered or unexported fields
}

LocalFS implements FS backed by a local directory.

func NewLocalFS

func NewLocalFS(root string, opts ...LocalOption) (*LocalFS, error)

NewLocalFS creates a LocalFS rooted at the given directory. It returns an error if the absolute path cannot be resolved.

Example
package main

import (
	"context"
	"fmt"
	"io"
	"log"
	"os"
	"strings"

	virefs "github.com/lin-snow/VireFS"
)

func main() {
	dir, _ := os.MkdirTemp("", "virefs-example-*")
	defer os.RemoveAll(dir)

	fs, err := virefs.NewLocalFS(dir)
	if err != nil {
		log.Fatal(err)
	}
	ctx := context.Background()

	if err := fs.Put(ctx, "hello.txt", strings.NewReader("world")); err != nil {
		log.Fatal(err)
	}
	rc, err := fs.Get(ctx, "hello.txt")
	if err != nil {
		log.Fatal(err)
	}
	defer rc.Close()
	data, _ := io.ReadAll(rc)
	fmt.Println(string(data))
}
Output:
world
Example (WithAccessFunc)
package main

import (
	"context"
	"fmt"
	"log"
	"os"
	"strings"

	virefs "github.com/lin-snow/VireFS"
)

func main() {
	dir, _ := os.MkdirTemp("", "virefs-example-*")
	defer os.RemoveAll(dir)

	fs, err := virefs.NewLocalFS(dir, virefs.WithLocalAccessFunc(func(key string) *virefs.AccessInfo {
		return &virefs.AccessInfo{URL: "https://cdn.example.com/files/" + key}
	}))
	if err != nil {
		log.Fatal(err)
	}
	ctx := context.Background()

	_ = fs.Put(ctx, "photo.jpg", strings.NewReader("jpeg-data"))

	info, err := fs.Access(ctx, "photo.jpg")
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(info.URL)
	fmt.Println(info.Path != "")
}
Output:
https://cdn.example.com/files/photo.jpg
true
Example (WithKeyFunc)
package main

import (
	"context"
	"fmt"
	"log"
	"os"
	"strings"

	virefs "github.com/lin-snow/VireFS"
)

func main() {
	dir, _ := os.MkdirTemp("", "virefs-example-*")
	defer os.RemoveAll(dir)

	fs, err := virefs.NewLocalFS(dir, virefs.WithLocalKeyFunc(func(key string) string {
		return "v2/" + key
	}))
	if err != nil {
		log.Fatal(err)
	}
	ctx := context.Background()

	_ = fs.Put(ctx, "note.txt", strings.NewReader("hello"))

	info, err := fs.Access(ctx, "note.txt")
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(strings.Contains(info.Path, "v2/note.txt"))
}
Output:
true

func (*LocalFS) Access

func (l *LocalFS) Access(ctx context.Context, key string) (*AccessInfo, error)

Access implements FS. When an AccessFunc is configured, the returned AccessInfo contains both the absolute disk Path and any URL produced by the AccessFunc.

func (*LocalFS) Copy

func (l *LocalFS) Copy(ctx context.Context, srcKey, dstKey string) error

Copy implements Copier for same-backend file copy.

func (*LocalFS) Delete

func (l *LocalFS) Delete(ctx context.Context, key string) error

Delete implements FS.

func (*LocalFS) Exists added in v0.1.1

func (l *LocalFS) Exists(ctx context.Context, key string) (bool, error)

Exists implements FS.

func (*LocalFS) Get

func (l *LocalFS) Get(ctx context.Context, key string) (io.ReadCloser, error)

Get implements FS.

func (*LocalFS) List

func (l *LocalFS) List(ctx context.Context, prefix string) (*ListResult, error)

List implements FS.

func (*LocalFS) Put

func (l *LocalFS) Put(ctx context.Context, key string, r io.Reader, _ ...PutOption) error

Put implements FS.

func (*LocalFS) Stat

func (l *LocalFS) Stat(ctx context.Context, key string) (*FileInfo, error)

Stat implements FS.

type LocalOption

type LocalOption func(*LocalFS)

LocalOption configures a LocalFS instance.

func WithAtomicWrite

func WithAtomicWrite() LocalOption

WithAtomicWrite enables atomic writes: Put writes to a temporary file in the same directory and then renames it to the target path. This prevents data corruption from concurrent writes to the same key.

func WithCreateRoot

func WithCreateRoot() LocalOption

WithCreateRoot creates the root directory if it does not already exist.

func WithDirPerm

func WithDirPerm(perm os.FileMode) LocalOption

WithDirPerm sets the permission bits used when auto-creating directories. Default is 0755.

func WithLocalAccessFunc added in v0.1.1

func WithLocalAccessFunc(fn AccessFunc) LocalOption

WithLocalAccessFunc sets a custom function for Access URL generation. The function receives the cleaned key (after CleanKey + KeyFunc) and returns an AccessInfo. The returned URL field is merged with the disk Path that LocalFS always provides, so both Path and URL can be set simultaneously.

This is useful for mapping virtual paths to HTTP URLs, e.g.:

WithLocalAccessFunc(func(key string) *AccessInfo {
    return &AccessInfo{URL: "https://cdn.example.com/files/" + key}
})

func WithLocalKeyFunc

func WithLocalKeyFunc(fn KeyFunc) LocalOption

WithLocalKeyFunc sets a KeyFunc that transforms every key after CleanKey and before the key is mapped to a local path.

type Middleware added in v0.1.1

type Middleware func(FS) FS

Middleware wraps an FS and returns a new FS with additional behaviour. Use Chain to compose multiple middlewares.

type MigrateOption added in v0.1.1

type MigrateOption func(*migrateConfig)

MigrateOption configures a Migrate operation.

func WithConflictPolicy added in v0.1.1

func WithConflictPolicy(p ConflictPolicy) MigrateOption

WithConflictPolicy sets the conflict resolution strategy. Default is ConflictError.

func WithDryRun added in v0.1.1

func WithDryRun() MigrateOption

WithDryRun makes Migrate walk and check conflicts without actually copying any data. The returned MigrateResult still reports what would have been copied or skipped.

func WithMigrateKeyFunc added in v0.1.1

func WithMigrateKeyFunc(fn func(srcKey string) string) MigrateOption

WithMigrateKeyFunc sets a function that transforms source keys into destination keys. The function receives the relative source key (with srcPrefix stripped) and returns the relative destination key. If nil, the source relative key is used as-is.

func WithProgressFunc added in v0.1.1

func WithProgressFunc(fn func(MigrateProgress)) MigrateOption

WithProgressFunc registers a callback invoked after each file is processed. The callback is called synchronously from Migrate.

type MigrateProgress added in v0.1.1

type MigrateProgress struct {
	Key     string // source key being processed
	Copied  int    // cumulative files copied so far
	Skipped int    // cumulative files skipped so far
	Total   int    // cumulative files scanned so far (excluding directories)
}

MigrateProgress is passed to the progress callback after each file is processed (copied or skipped).

type MigrateResult added in v0.1.1

type MigrateResult struct {
	Copied  int
	Skipped int
	Total   int
}

MigrateResult summarises a completed Migrate operation.

func Migrate added in v0.1.1

func Migrate(ctx context.Context, src FS, srcPrefix string, dst FS, dstPrefix string, opts ...MigrateOption) (*MigrateResult, error)

Migrate recursively copies files from src (under srcPrefix) to dst (under dstPrefix). It uses Walk to enumerate source files and Copy to transfer each one.

Migrate supports conflict policies, dry-run mode, progress callbacks, and key transformation. See the With* options for details.

Example
package main

import (
	"context"
	"fmt"
	"log"
	"os"
	"strings"

	virefs "github.com/lin-snow/VireFS"
)

func main() {
	srcDir, _ := os.MkdirTemp("", "virefs-src-*")
	defer os.RemoveAll(srcDir)
	dstDir, _ := os.MkdirTemp("", "virefs-dst-*")
	defer os.RemoveAll(dstDir)

	src, _ := virefs.NewLocalFS(srcDir)
	dst, _ := virefs.NewLocalFS(dstDir)
	ctx := context.Background()

	_ = src.Put(ctx, "a.txt", strings.NewReader("aaa"))
	_ = src.Put(ctx, "b.txt", strings.NewReader("bbb"))

	result, err := virefs.Migrate(ctx, src, "", dst, "backup",
		virefs.WithConflictPolicy(virefs.ConflictSkip),
	)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("copied=%d skipped=%d total=%d\n", result.Copied, result.Skipped, result.Total)
}
Output:
copied=2 skipped=0 total=2

type MountTable

type MountTable struct {
	// contains filtered or unexported fields
}

MountTable routes key-based operations to the correct FS by prefix.

A key like "local/docs/a.txt" is split into mount prefix "local" and sub-key "docs/a.txt", then forwarded to the FS mounted at "local".

func NewMountTable

func NewMountTable() *MountTable

NewMountTable returns an empty MountTable.

Example
package main

import (
	"context"
	"fmt"
	"io"
	"os"
	"strings"

	virefs "github.com/lin-snow/VireFS"
)

func main() {
	dir1, _ := os.MkdirTemp("", "virefs-example-*")
	defer os.RemoveAll(dir1)
	dir2, _ := os.MkdirTemp("", "virefs-example-*")
	defer os.RemoveAll(dir2)

	fs1, _ := virefs.NewLocalFS(dir1)
	fs2, _ := virefs.NewLocalFS(dir2)

	mt := virefs.NewMountTable()
	_ = mt.Mount("data", fs1)
	_ = mt.Mount("cache", fs2)

	ctx := context.Background()
	_ = mt.Put(ctx, "data/file.txt", strings.NewReader("hello"))

	rc, _ := mt.Get(ctx, "data/file.txt")
	defer rc.Close()
	data, _ := io.ReadAll(rc)
	fmt.Println(string(data))
}
Output:
hello

func (*MountTable) Access

func (mt *MountTable) Access(ctx context.Context, key string) (*AccessInfo, error)

Access implements FS.

func (*MountTable) Copy

func (mt *MountTable) Copy(ctx context.Context, srcKey, dstKey string) error

Copy implements Copier. When both keys resolve to the same underlying FS and that FS implements Copier, the native copy is used. Otherwise it falls back to Get + Put.

func (*MountTable) Delete

func (mt *MountTable) Delete(ctx context.Context, key string) error

Delete implements FS.

func (*MountTable) Exists added in v0.1.1

func (mt *MountTable) Exists(ctx context.Context, key string) (bool, error)

Exists implements FS.

func (*MountTable) Get

func (mt *MountTable) Get(ctx context.Context, key string) (io.ReadCloser, error)

Get implements FS.

func (*MountTable) List

func (mt *MountTable) List(ctx context.Context, prefix string) (*ListResult, error)

List implements FS. If prefix resolves to a mount point, the sub-prefix is forwarded. If prefix is empty it lists top-level mount points as virtual directories.

func (*MountTable) Mount

func (mt *MountTable) Mount(prefix string, fs FS) error

Mount registers fs under the given prefix. Prefix must be a single path segment with no slashes.

func (*MountTable) Put

func (mt *MountTable) Put(ctx context.Context, key string, r io.Reader, opts ...PutOption) error

Put implements FS.

func (*MountTable) Stat

func (mt *MountTable) Stat(ctx context.Context, key string) (*FileInfo, error)

Stat implements FS.

func (*MountTable) Unmount

func (mt *MountTable) Unmount(prefix string)

Unmount removes the FS registered under prefix.

type ObjectFS

type ObjectFS struct {
	// contains filtered or unexported fields
}

ObjectFS implements FS backed by an S3-compatible object store. It also implements the optional Presigner interface when a PresignAPI client is provided via WithPresignClient.

func NewObjectFS

func NewObjectFS(client S3API, bucket string, opts ...ObjectOption) *ObjectFS

NewObjectFS creates an ObjectFS targeting the given bucket.

Use WithPrefix to add a key prefix. To use a custom endpoint (MinIO, Ceph, R2, ...) configure the *s3.Client before passing it in:

client := s3.NewFromConfig(cfg, func(o *s3.Options) {
    o.BaseEndpoint = aws.String("https://s3.example.com")
    o.UsePathStyle = true
})
fs := NewObjectFS(client, "my-bucket", WithPrefix("data/"))

func NewObjectFSFromConfig added in v0.1.1

func NewObjectFSFromConfig(ctx context.Context, cfg *S3Config, opts ...ObjectOption) (*ObjectFS, error)

NewObjectFSFromConfig creates an ObjectFS (with a presign client) in one step from an S3Config. Any additional ObjectOption values are applied after the presign client is injected.

fs, err := virefs.NewObjectFSFromConfig(ctx, &virefs.S3Config{
    Provider:  virefs.ProviderMinIO,
    Endpoint:  "http://localhost:9000",
    Region:    "us-east-1",
    AccessKey: "minioadmin",
    SecretKey: "minioadmin",
    Bucket:    "my-bucket",
}, virefs.WithPrefix("uploads/"))

func (*ObjectFS) Access

func (o *ObjectFS) Access(ctx context.Context, key string) (*AccessInfo, error)

Access returns an AccessInfo for the given key. Priority: AccessFunc > PresignClient > BaseURL > ErrNotSupported.

func (*ObjectFS) BatchDelete

func (o *ObjectFS) BatchDelete(ctx context.Context, keys []string) error

BatchDelete implements BatchDeleter using S3 DeleteObjects for efficient bulk deletion of up to 1000 keys per call.

func (*ObjectFS) Copy

func (o *ObjectFS) Copy(ctx context.Context, srcKey, dstKey string) error

Copy implements Copier using S3 CopyObject for efficient same-bucket copies.

func (*ObjectFS) Delete

func (o *ObjectFS) Delete(ctx context.Context, key string) error

Delete implements FS.

func (*ObjectFS) Exists added in v0.1.1

func (o *ObjectFS) Exists(ctx context.Context, key string) (bool, error)

Exists implements FS.

func (*ObjectFS) Get

func (o *ObjectFS) Get(ctx context.Context, key string) (io.ReadCloser, error)

Get implements FS.

func (*ObjectFS) List

func (o *ObjectFS) List(ctx context.Context, prefix string) (*ListResult, error)

List implements FS.

func (*ObjectFS) PresignGet

func (o *ObjectFS) PresignGet(ctx context.Context, key string, expires time.Duration) (*PresignedRequest, error)

PresignGet returns a presigned GET URL for the given key. Requires WithPresignClient to have been set; returns ErrNotSupported otherwise.

func (*ObjectFS) PresignPut

func (o *ObjectFS) PresignPut(ctx context.Context, key string, expires time.Duration) (*PresignedRequest, error)

PresignPut returns a presigned PUT URL for the given key. Requires WithPresignClient to have been set; returns ErrNotSupported otherwise.

func (*ObjectFS) Put

func (o *ObjectFS) Put(ctx context.Context, key string, r io.Reader, opts ...PutOption) error

Put implements FS.

func (*ObjectFS) Stat

func (o *ObjectFS) Stat(ctx context.Context, key string) (*FileInfo, error)

Stat implements FS.

type ObjectOption

type ObjectOption func(*ObjectFS)

ObjectOption configures an ObjectFS instance.

func WithAccessExpires

func WithAccessExpires(d time.Duration) ObjectOption

WithAccessExpires sets the default expiry for presigned URLs generated by Access. Default is 15 minutes.

func WithAccessFunc

func WithAccessFunc(fn AccessFunc) ObjectOption

WithAccessFunc sets a custom function for Access URL generation. The function receives the fully resolved S3 key (after CleanKey + KeyFunc + basePrefix) and returns an AccessInfo. This is useful for CDN domains, custom URL schemes, or per-file-type routing.

When set, AccessFunc takes priority over presign client and base URL.

func WithBaseURL

func WithBaseURL(url string) ObjectOption

WithBaseURL sets the public base URL used by Access when no presign client is configured. The URL should include the bucket if needed, e.g. "https://my-bucket.s3.us-east-1.amazonaws.com" or "https://cdn.example.com".

func WithObjectKeyFunc

func WithObjectKeyFunc(fn KeyFunc) ObjectOption

WithObjectKeyFunc sets a KeyFunc that transforms every key after CleanKey and before the key is combined with the base prefix.

func WithPrefix

func WithPrefix(prefix string) ObjectOption

WithPrefix sets a base prefix prepended to every key. For example, WithPrefix("uploads/") makes Get(ctx, "a/b.txt") resolve to S3 key "uploads/a/b.txt".

func WithPresignClient

func WithPresignClient(pc PresignAPI) ObjectOption

WithPresignClient injects a PresignAPI (typically *s3.PresignClient) to enable presigned URL generation via the Presigner interface.

type OpError

type OpError struct {
	Op  string // e.g. "Get", "Put"
	Key string
	Err error
}

OpError wraps a backend error with operation context.

func (*OpError) Error

func (e *OpError) Error() string

func (*OpError) Unwrap

func (e *OpError) Unwrap() error

type PresignAPI

type PresignAPI interface {
	PresignGetObject(ctx context.Context, params *s3.GetObjectInput, optFns ...func(*s3.PresignOptions)) (*v4.PresignedHTTPRequest, error)
	PresignPutObject(ctx context.Context, params *s3.PutObjectInput, optFns ...func(*s3.PresignOptions)) (*v4.PresignedHTTPRequest, error)
}

PresignAPI is the subset of *s3.PresignClient that ObjectFS needs for generating presigned URLs. Accepting an interface keeps tests simple.

type PresignedRequest

type PresignedRequest struct {
	URL    string
	Method string
	Header http.Header
}

PresignedRequest holds a presigned HTTP request returned by Presigner. It deliberately avoids exposing AWS SDK types so callers don't need a direct dependency on aws-sdk-go-v2.

type Presigner

type Presigner interface {
	// PresignGet returns a presigned URL for downloading the given key.
	PresignGet(ctx context.Context, key string, expires time.Duration) (*PresignedRequest, error)

	// PresignPut returns a presigned URL for uploading to the given key.
	PresignPut(ctx context.Context, key string, expires time.Duration) (*PresignedRequest, error)
}

Presigner is an optional interface that FS implementations may support. Use a type assertion to check: if p, ok := fs.(Presigner); ok { ... }

type Provider added in v0.1.1

type Provider int

Provider identifies an S3-compatible storage provider. Each provider may have different defaults (e.g. path-style addressing).

const (
	// ProviderAWS is standard AWS S3 (virtual-hosted-style, default region us-east-1).
	ProviderAWS Provider = iota
	// ProviderMinIO requires path-style addressing.
	ProviderMinIO
	// ProviderR2 is Cloudflare R2, which requires path-style addressing
	// and region "auto".
	ProviderR2
)

type PutConfig

type PutConfig struct {
	ContentType string
	Metadata    map[string]string
}

PutConfig holds optional parameters for Put.

func BuildPutConfig

func BuildPutConfig(opts []PutOption) PutConfig

BuildPutConfig applies all PutOptions and returns the resulting config.

type PutOption

type PutOption func(*PutConfig)

PutOption configures a Put operation.

func WithContentType

func WithContentType(ct string) PutOption

WithContentType sets the MIME type of the content being uploaded. ObjectFS passes it to S3 PutObject; LocalFS ignores it.

func WithMetadata

func WithMetadata(m map[string]string) PutOption

WithMetadata attaches custom key-value metadata to the uploaded object. ObjectFS passes it as S3 user metadata; LocalFS ignores it.

type Route

type Route struct {
	// contains filtered or unexported fields
}

Route defines a single routing rule that maps matching keys to a prefix.

func DefaultRoute

func DefaultRoute(prefix string) Route

DefaultRoute creates a catch-all route that matches any key. Place it last in the route list.

func RouteByExt

func RouteByExt(prefix string, exts ...string) Route

RouteByExt creates a route that matches keys by file extension (case-insensitive). The prefix is prepended to matching keys.

RouteByExt("images/", ".jpg", ".jpeg", ".png")

func RouteByFunc

func RouteByFunc(prefix string, fn func(key string) bool) Route

RouteByFunc creates a route with a custom match function.

RouteByFunc("archives/", func(key string) bool {
    return strings.HasSuffix(key, ".tar.gz") || strings.HasSuffix(key, ".zip")
})

type S3API

type S3API interface {
	GetObject(ctx context.Context, params *s3.GetObjectInput, optFns ...func(*s3.Options)) (*s3.GetObjectOutput, error)
	PutObject(ctx context.Context, params *s3.PutObjectInput, optFns ...func(*s3.Options)) (*s3.PutObjectOutput, error)
	DeleteObject(ctx context.Context, params *s3.DeleteObjectInput, optFns ...func(*s3.Options)) (*s3.DeleteObjectOutput, error)
	DeleteObjects(ctx context.Context, params *s3.DeleteObjectsInput, optFns ...func(*s3.Options)) (*s3.DeleteObjectsOutput, error)
	HeadObject(ctx context.Context, params *s3.HeadObjectInput, optFns ...func(*s3.Options)) (*s3.HeadObjectOutput, error)
	ListObjectsV2(ctx context.Context, params *s3.ListObjectsV2Input, optFns ...func(*s3.Options)) (*s3.ListObjectsV2Output, error)
	CopyObject(ctx context.Context, params *s3.CopyObjectInput, optFns ...func(*s3.Options)) (*s3.CopyObjectOutput, error)
}

S3API is the subset of *s3.Client that ObjectFS needs. Accepting an interface makes unit-testing trivial (no real S3 required).

type S3Config added in v0.1.1

type S3Config struct {
	// Region is the AWS region (e.g. "us-east-1").
	// For R2 this defaults to "auto" if left empty.
	Region string

	// Endpoint is the custom S3-compatible endpoint URL.
	// Required for MinIO, R2, and other non-AWS providers.
	// Leave empty for standard AWS S3.
	Endpoint string

	// Bucket is the target bucket name.
	// Used by NewObjectFSFromConfig; ignored by NewS3Client.
	Bucket string

	// AccessKey and SecretKey provide static credentials.
	// When both are empty, the SDK's default credential chain is used
	// (env vars, shared config, IAM role, etc.).
	AccessKey string
	SecretKey string

	// Provider selects a provider preset that configures known quirks.
	// Default is ProviderAWS.
	Provider Provider

	// UsePathStyle forces path-style addressing (e.g. http://endpoint/bucket/key).
	// Automatically set to true for MinIO and R2 providers; set explicitly
	// to override the provider default.
	UsePathStyle *bool
}

S3Config holds the parameters needed to construct an S3 client and, optionally, an ObjectFS in one step.

type Schema

type Schema struct {
	// contains filtered or unexported fields
}

Schema organises files into directory prefixes based on routing rules. Rules are evaluated in declaration order; the first match wins.

Schema.Resolve has the same signature as KeyFunc, so it plugs directly into WithLocalKeyFunc / WithObjectKeyFunc.

func NewSchema

func NewSchema(routes ...Route) *Schema

NewSchema creates a Schema from the given routes.

Example
package main

import (
	"fmt"

	virefs "github.com/lin-snow/VireFS"
)

func main() {
	schema := virefs.NewSchema(
		virefs.RouteByExt("images/", ".jpg", ".png"),
		virefs.RouteByExt("docs/", ".pdf"),
		virefs.DefaultRoute("other/"),
	)

	fmt.Println(schema.Resolve("cat.jpg"))
	fmt.Println(schema.Resolve("report.pdf"))
	fmt.Println(schema.Resolve("readme.txt"))
}
Output:
images/cat.jpg
docs/report.pdf
other/readme.txt

func (*Schema) Resolve

func (s *Schema) Resolve(key string) string

Resolve maps a key to its storage path by applying the first matching route. If no route matches, the key is returned unchanged.

type WalkFunc

type WalkFunc func(key string, info FileInfo, err error) error

WalkFunc is the type of the function called by Walk to visit each file or directory. The key argument is the full key of the entry. If there was an error listing a directory, err will be non-nil and info may be zero-valued.

If WalkFunc returns ErrSkipDir when invoked on a directory, Walk skips that directory's contents. If WalkFunc returns any other non-nil error, Walk stops entirely and returns that error.

Directories

Path Synopsis
plugin
zip

Jump to

Keyboard shortcuts

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