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 ¶
- Variables
- func BatchDelete(ctx context.Context, fsys FS, keys []string) error
- func CleanKey(raw string) (string, error)
- func Copy(ctx context.Context, src FS, srcKey string, dst FS, dstKey string, ...) error
- func Exists(ctx context.Context, fs FS, key string) (bool, error)
- func NewS3Client(ctx context.Context, cfg *S3Config) (*s3.Client, error)
- func Walk(ctx context.Context, fsys FS, prefix string, fn WalkFunc) error
- func WithHooks(inner FS, hooks Hooks) *hookFS
- type AccessFunc
- type AccessInfo
- type BaseFS
- func (b BaseFS) Access(ctx context.Context, key string) (*AccessInfo, error)
- func (b BaseFS) Delete(ctx context.Context, key string) error
- func (b BaseFS) Exists(ctx context.Context, key string) (bool, error)
- func (b BaseFS) Get(ctx context.Context, key string) (io.ReadCloser, error)
- func (b BaseFS) List(ctx context.Context, prefix string) (*ListResult, error)
- func (b BaseFS) Put(ctx context.Context, key string, r io.Reader, opts ...PutOption) error
- func (b BaseFS) Stat(ctx context.Context, key string) (*FileInfo, error)
- type BatchDeleter
- type ConflictPolicy
- type Copier
- type FS
- type FileInfo
- type Hooks
- type KeyFunc
- type ListResult
- type LocalFS
- func (l *LocalFS) Access(ctx context.Context, key string) (*AccessInfo, error)
- func (l *LocalFS) Copy(ctx context.Context, srcKey, dstKey string) error
- func (l *LocalFS) Delete(ctx context.Context, key string) error
- func (l *LocalFS) Exists(ctx context.Context, key string) (bool, error)
- func (l *LocalFS) Get(ctx context.Context, key string) (io.ReadCloser, error)
- func (l *LocalFS) List(ctx context.Context, prefix string) (*ListResult, error)
- func (l *LocalFS) Put(ctx context.Context, key string, r io.Reader, _ ...PutOption) error
- func (l *LocalFS) Stat(ctx context.Context, key string) (*FileInfo, error)
- type LocalOption
- type Middleware
- type MigrateOption
- type MigrateProgress
- type MigrateResult
- type MountTable
- func (mt *MountTable) Access(ctx context.Context, key string) (*AccessInfo, error)
- func (mt *MountTable) Copy(ctx context.Context, srcKey, dstKey string) error
- func (mt *MountTable) Delete(ctx context.Context, key string) error
- func (mt *MountTable) Exists(ctx context.Context, key string) (bool, error)
- func (mt *MountTable) Get(ctx context.Context, key string) (io.ReadCloser, error)
- func (mt *MountTable) List(ctx context.Context, prefix string) (*ListResult, error)
- func (mt *MountTable) Mount(prefix string, fs FS) error
- func (mt *MountTable) Put(ctx context.Context, key string, r io.Reader, opts ...PutOption) error
- func (mt *MountTable) Stat(ctx context.Context, key string) (*FileInfo, error)
- func (mt *MountTable) Unmount(prefix string)
- type ObjectFS
- func (o *ObjectFS) Access(ctx context.Context, key string) (*AccessInfo, error)
- func (o *ObjectFS) BatchDelete(ctx context.Context, keys []string) error
- func (o *ObjectFS) Copy(ctx context.Context, srcKey, dstKey string) error
- func (o *ObjectFS) Delete(ctx context.Context, key string) error
- func (o *ObjectFS) Exists(ctx context.Context, key string) (bool, error)
- func (o *ObjectFS) Get(ctx context.Context, key string) (io.ReadCloser, error)
- func (o *ObjectFS) List(ctx context.Context, prefix string) (*ListResult, error)
- func (o *ObjectFS) PresignGet(ctx context.Context, key string, expires time.Duration) (*PresignedRequest, error)
- func (o *ObjectFS) PresignPut(ctx context.Context, key string, expires time.Duration) (*PresignedRequest, error)
- func (o *ObjectFS) Put(ctx context.Context, key string, r io.Reader, opts ...PutOption) error
- func (o *ObjectFS) Stat(ctx context.Context, key string) (*FileInfo, error)
- type ObjectOption
- type OpError
- type PresignAPI
- type PresignedRequest
- type Presigner
- type Provider
- type PutConfig
- type PutOption
- type Route
- type S3API
- type S3Config
- type Schema
- type WalkFunc
Examples ¶
Constants ¶
This section is empty.
Variables ¶
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.
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 ¶
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 ¶
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 ¶
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
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 ¶
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 ¶
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)
}
type BatchDeleter ¶
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 ¶
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 ¶
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 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 ¶
Access implements FS. When an AccessFunc is configured, the returned AccessInfo contains both the absolute disk Path and any URL produced by the AccessFunc.
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
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
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) 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) 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 ¶
Access returns an AccessInfo for the given key. Priority: AccessFunc > PresignClient > BaseURL > ErrNotSupported.
func (*ObjectFS) BatchDelete ¶
BatchDelete implements BatchDeleter using S3 DeleteObjects for efficient bulk deletion of up to 1000 keys per call.
func (*ObjectFS) Copy ¶
Copy implements Copier using S3 CopyObject for efficient same-bucket copies.
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.
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 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 ¶
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).
type PutConfig ¶
PutConfig holds optional parameters for Put.
func BuildPutConfig ¶
BuildPutConfig applies all PutOptions and returns the resulting config.
type PutOption ¶
type PutOption func(*PutConfig)
PutOption configures a Put operation.
func WithContentType ¶
WithContentType sets the MIME type of the content being uploaded. ObjectFS passes it to S3 PutObject; LocalFS ignores it.
func WithMetadata ¶
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 ¶
DefaultRoute creates a catch-all route that matches any key. Place it last in the route list.
func RouteByExt ¶
RouteByExt creates a route that matches keys by file extension (case-insensitive). The prefix is prepended to matching keys.
RouteByExt("images/", ".jpg", ".jpeg", ".png")
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 ¶
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
type WalkFunc ¶
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.