Documentation
¶
Overview ¶
Package objstore provides a unified interface for file storage operations across multiple cloud and local backends.
Supported backends:
- Local filesystem (objstore.LocalStorage)
- AWS S3 and S3-compatible services (s3.Storage)
- Google Cloud Storage (gcs.Storage)
- Azure Blob Storage (azure.Storage)
- In-memory for testing (objstore.MemoryStorage)
All backends implement the Storage interface, allowing seamless switching between providers without changing application code.
Quick Start ¶
// Create a storage backend
store, err := objstore.NewLocalStorage(
objstore.DefaultLocalConfig().WithBasePath("./uploads"),
)
if err != nil {
log.Fatal(err)
}
// Upload
info, err := store.Put(ctx, "images/photo.jpg", file,
objstore.WithContentType("image/jpeg"),
)
// Download
reader, err := store.Get(ctx, "images/photo.jpg")
defer reader.Close()
// Delete
err = store.Delete(ctx, "images/photo.jpg")
Backend Selection ¶
Use the same interface across environments:
var store objstore.Storage
switch env {
case "test":
store = objstore.NewMemoryStorage()
case "local":
store, _ = objstore.NewLocalStorage(objstore.DefaultLocalConfig())
case "production":
store, _ = s3.New(ctx, s3.DefaultConfig().WithBucket("my-bucket"))
}
Upload Options ¶
Use functional options to configure uploads:
store.Put(ctx, path, reader,
objstore.WithContentType("image/png"),
objstore.WithMetadata(map[string]string{"owner": "alice"}),
objstore.WithCacheControl("max-age=86400"),
objstore.WithACL("public-read"),
objstore.WithOverwrite(false),
)
Package objstore provides a unified interface for file storage operations across different backends including local filesystem, AWS S3, Google Cloud Storage, and Azure Blob Storage.
Index ¶
- Variables
- func CopyTo(ctx context.Context, src Storage, srcPath string, dst Storage, dstPath string, ...) error
- func DeletePrefix(ctx context.Context, s Storage, prefix string) error
- func DetectContentType(path string) string
- func FormatSize(size int64) string
- func GenerateFileName(originalName string) string
- func GenerateHashedPath(originalName string, prefix string, levels int) string
- func GeneratePath(originalName string, prefix string) string
- func GetBytes(ctx context.Context, s Storage, path string) ([]byte, error)
- func GetString(ctx context.Context, s Storage, path string) (string, error)
- func IsAudio(info *FileInfo) bool
- func IsDocument(info *FileInfo) bool
- func IsImage(info *FileInfo) bool
- func IsVideo(info *FileInfo) bool
- func MoveTo(ctx context.Context, src Storage, srcPath string, dst Storage, dstPath string, ...) error
- func NormalizePath(path string) string
- func ParseDataURI(dataURI string) ([]byte, string, error)
- func SyncDir(ctx context.Context, s Storage, localPath, remotePath string) error
- type BatchDeleter
- type FileInfo
- func PutBytes(ctx context.Context, s Storage, path string, data []byte, opts ...PutOption) (*FileInfo, error)
- func PutDataURI(ctx context.Context, s Storage, path string, dataURI string, opts ...PutOption) (*FileInfo, error)
- func PutString(ctx context.Context, s Storage, path string, data string, opts ...PutOption) (*FileInfo, error)
- type ListOption
- type ListOptions
- type ListResult
- type LocalConfig
- type LocalStorage
- func (s *LocalStorage) Close() error
- func (s *LocalStorage) Copy(ctx context.Context, src, dst string) error
- func (s *LocalStorage) Delete(ctx context.Context, path string) error
- func (s *LocalStorage) DeleteDir(ctx context.Context, path string) error
- func (s *LocalStorage) Exists(ctx context.Context, path string) (bool, error)
- func (s *LocalStorage) Get(ctx context.Context, path string) (io.ReadCloser, error)
- func (s *LocalStorage) List(ctx context.Context, prefix string, opts ...ListOption) (*ListResult, error)
- func (s *LocalStorage) Move(ctx context.Context, src, dst string) error
- func (s *LocalStorage) Put(ctx context.Context, path string, reader io.Reader, opts ...PutOption) (*FileInfo, error)
- func (s *LocalStorage) SignedURL(ctx context.Context, path string, opts ...SignedURLOption) (string, error)
- func (s *LocalStorage) Stat(ctx context.Context, path string) (*FileInfo, error)
- func (s *LocalStorage) URL(ctx context.Context, path string) (string, error)
- type MemoryStorage
- func (s *MemoryStorage) Clear()
- func (s *MemoryStorage) Close() error
- func (s *MemoryStorage) Copy(ctx context.Context, src, dst string) error
- func (s *MemoryStorage) Delete(ctx context.Context, path string) error
- func (s *MemoryStorage) Exists(ctx context.Context, path string) (bool, error)
- func (s *MemoryStorage) Get(ctx context.Context, path string) (io.ReadCloser, error)
- func (s *MemoryStorage) GetBytes(path string) ([]byte, error)
- func (s *MemoryStorage) List(ctx context.Context, prefix string, opts ...ListOption) (*ListResult, error)
- func (s *MemoryStorage) Move(ctx context.Context, src, dst string) error
- func (s *MemoryStorage) Put(ctx context.Context, path string, reader io.Reader, opts ...PutOption) (*FileInfo, error)
- func (s *MemoryStorage) SignedURL(ctx context.Context, path string, opts ...SignedURLOption) (string, error)
- func (s *MemoryStorage) Size() int
- func (s *MemoryStorage) Stat(ctx context.Context, path string) (*FileInfo, error)
- func (s *MemoryStorage) TotalBytes() int64
- func (s *MemoryStorage) URL(ctx context.Context, path string) (string, error)
- func (s *MemoryStorage) WithBaseURL(url string) *MemoryStorage
- type PutOption
- type PutOptions
- type SignedURLOption
- type SignedURLOptions
- type Storage
Constants ¶
This section is empty.
Variables ¶
var ( ErrNotFound = errors.New("objstore: file not found") ErrAlreadyExists = errors.New("objstore: file already exists") ErrInvalidPath = errors.New("objstore: invalid path") ErrPermission = errors.New("objstore: permission denied") ErrNotImplemented = errors.New("objstore: operation not implemented") ErrInvalidConfig = errors.New("objstore: invalid configuration") )
Sentinel errors for storage operations.
Functions ¶
func CopyTo ¶
func CopyTo(ctx context.Context, src Storage, srcPath string, dst Storage, dstPath string, opts ...PutOption) error
CopyTo copies a file from one storage to another.
func DeletePrefix ¶
DeletePrefix deletes all files matching a prefix. If the storage backend implements BatchDeleter, it uses batch deletion for efficiency.
func DetectContentType ¶
DetectContentType detects the MIME type from file extension.
func FormatSize ¶
FormatSize formats a file size in human-readable format.
func GenerateFileName ¶
GenerateFileName generates a unique filename with the original extension.
func GenerateHashedPath ¶
GenerateHashedPath generates a path using hash-based distribution. This helps distribute files across directories when you have many files.
func GeneratePath ¶
GeneratePath generates a unique path with date-based organization.
func IsDocument ¶
IsDocument checks if a file is a document (PDF, Word, Excel, etc.).
func MoveTo ¶
func MoveTo(ctx context.Context, src Storage, srcPath string, dst Storage, dstPath string, opts ...PutOption) error
MoveTo moves a file from one storage to another.
func NormalizePath ¶
NormalizePath normalizes a path for consistent storage.
func ParseDataURI ¶
ParseDataURI parses a data URI and returns the content and MIME type.
Types ¶
type BatchDeleter ¶
BatchDeleter is an optional interface for backends that support batch deletion.
type FileInfo ¶
type FileInfo struct {
Path string // Full path including filename
Name string // Filename only
Size int64 // Size in bytes
ContentType string // MIME type
ETag string // Entity tag for versioning
LastModified time.Time // Last modification time
Metadata map[string]string // Custom metadata
IsDir bool // True if this is a directory/prefix
}
FileInfo contains information about a stored file.
func PutBytes ¶
func PutBytes(ctx context.Context, s Storage, path string, data []byte, opts ...PutOption) (*FileInfo, error)
PutBytes uploads bytes to storage.
type ListOption ¶
type ListOption func(*ListOptions)
ListOption is a function that modifies ListOptions.
func WithDelimiter ¶
func WithDelimiter(delimiter string) ListOption
WithDelimiter sets the delimiter for grouping.
func WithMaxKeys ¶
func WithMaxKeys(maxKeys int) ListOption
WithMaxKeys sets the maximum number of results.
func WithRecursive ¶
func WithRecursive(recursive bool) ListOption
WithRecursive enables recursive listing.
type ListOptions ¶
type ListOptions struct {
MaxKeys int // Maximum number of results
Delimiter string // Delimiter for grouping (e.g., "/")
Token string // Continuation token for pagination
Recursive bool // List recursively (ignore delimiter)
}
ListOptions configures list behavior.
func ApplyListOptions ¶
func ApplyListOptions(opts []ListOption) *ListOptions
ApplyListOptions applies ListOption functions to ListOptions.
type ListResult ¶
type ListResult struct {
Files []*FileInfo // Files matching the prefix
Prefixes []string // Common prefixes (directories)
NextToken string // Token for pagination
IsTruncated bool // True if there are more results
}
ListResult contains the result of a list operation.
type LocalConfig ¶
type LocalConfig struct {
// BasePath is the root directory for storage.
BasePath string
// BaseURL is the public URL prefix for serving files.
BaseURL string
// CreateDirs automatically creates directories when uploading.
CreateDirs bool
// Permissions for created files (default: 0644).
FilePermissions os.FileMode
// Permissions for created directories (default: 0755).
DirPermissions os.FileMode
}
LocalConfig holds configuration for local filesystem storage.
func DefaultLocalConfig ¶
func DefaultLocalConfig() LocalConfig
DefaultLocalConfig returns a default local storage configuration.
func (LocalConfig) WithBasePath ¶
func (c LocalConfig) WithBasePath(path string) LocalConfig
WithBasePath returns a new config with the specified base path.
func (LocalConfig) WithBaseURL ¶
func (c LocalConfig) WithBaseURL(url string) LocalConfig
WithBaseURL returns a new config with the specified base URL.
func (LocalConfig) WithCreateDirs ¶
func (c LocalConfig) WithCreateDirs(create bool) LocalConfig
WithCreateDirs returns a new config with auto directory creation.
func (LocalConfig) WithPermissions ¶
func (c LocalConfig) WithPermissions(file, dir os.FileMode) LocalConfig
WithPermissions returns a new config with the specified permissions.
type LocalStorage ¶
type LocalStorage struct {
// contains filtered or unexported fields
}
LocalStorage implements Storage for local filesystem.
func NewLocalStorage ¶
func NewLocalStorage(config LocalConfig) (*LocalStorage, error)
NewLocalStorage creates a new local filesystem storage.
func (*LocalStorage) Close ¶
func (s *LocalStorage) Close() error
Close is a no-op for local storage.
func (*LocalStorage) Copy ¶
func (s *LocalStorage) Copy(ctx context.Context, src, dst string) error
Copy copies a file.
func (*LocalStorage) Delete ¶
func (s *LocalStorage) Delete(ctx context.Context, path string) error
Delete removes a file from the local filesystem.
func (*LocalStorage) DeleteDir ¶
func (s *LocalStorage) DeleteDir(ctx context.Context, path string) error
DeleteDir removes a directory and all its contents.
func (*LocalStorage) Get ¶
func (s *LocalStorage) Get(ctx context.Context, path string) (io.ReadCloser, error)
Get retrieves content from the local filesystem.
func (*LocalStorage) List ¶
func (s *LocalStorage) List(ctx context.Context, prefix string, opts ...ListOption) (*ListResult, error)
List returns files matching the prefix.
func (*LocalStorage) Move ¶
func (s *LocalStorage) Move(ctx context.Context, src, dst string) error
Move moves a file.
func (*LocalStorage) Put ¶
func (s *LocalStorage) Put(ctx context.Context, path string, reader io.Reader, opts ...PutOption) (*FileInfo, error)
Put uploads content to the local filesystem.
func (*LocalStorage) SignedURL ¶
func (s *LocalStorage) SignedURL(ctx context.Context, path string, opts ...SignedURLOption) (string, error)
SignedURL returns a signed URL (not supported for local storage).
type MemoryStorage ¶
type MemoryStorage struct {
// contains filtered or unexported fields
}
MemoryStorage implements Storage with in-memory storage for testing.
func NewMemoryStorage ¶
func NewMemoryStorage() *MemoryStorage
NewMemoryStorage creates a new in-memory storage.
func (*MemoryStorage) Close ¶
func (s *MemoryStorage) Close() error
Close is a no-op for memory storage.
func (*MemoryStorage) Copy ¶
func (s *MemoryStorage) Copy(ctx context.Context, src, dst string) error
Copy copies a file in memory.
func (*MemoryStorage) Delete ¶
func (s *MemoryStorage) Delete(ctx context.Context, path string) error
Delete removes a file from memory.
func (*MemoryStorage) Get ¶
func (s *MemoryStorage) Get(ctx context.Context, path string) (io.ReadCloser, error)
Get retrieves content from memory.
func (*MemoryStorage) GetBytes ¶
func (s *MemoryStorage) GetBytes(path string) ([]byte, error)
GetBytes returns the raw bytes of a file (useful for testing).
func (*MemoryStorage) List ¶
func (s *MemoryStorage) List(ctx context.Context, prefix string, opts ...ListOption) (*ListResult, error)
List returns files matching the prefix.
func (*MemoryStorage) Move ¶
func (s *MemoryStorage) Move(ctx context.Context, src, dst string) error
Move moves a file in memory atomically.
func (*MemoryStorage) Put ¶
func (s *MemoryStorage) Put(ctx context.Context, path string, reader io.Reader, opts ...PutOption) (*FileInfo, error)
Put uploads content to memory.
func (*MemoryStorage) SignedURL ¶
func (s *MemoryStorage) SignedURL(ctx context.Context, path string, opts ...SignedURLOption) (string, error)
SignedURL returns a signed URL (not supported for memory storage).
func (*MemoryStorage) Size ¶
func (s *MemoryStorage) Size() int
Size returns the number of files in memory.
func (*MemoryStorage) TotalBytes ¶
func (s *MemoryStorage) TotalBytes() int64
TotalBytes returns the total size of all files in memory.
func (*MemoryStorage) WithBaseURL ¶
func (s *MemoryStorage) WithBaseURL(url string) *MemoryStorage
WithBaseURL sets the base URL for the memory storage.
type PutOption ¶
type PutOption func(*PutOptions)
PutOption is a function that modifies PutOptions.
func WithCacheControl ¶
WithCacheControl sets the Cache-Control header.
func WithContentType ¶
WithContentType sets the content type.
func WithMetadata ¶
WithMetadata sets custom metadata.
func WithOverwrite ¶
WithOverwrite allows overwriting existing files.
type PutOptions ¶
type PutOptions struct {
ContentType string // MIME type (auto-detected if empty)
Metadata map[string]string // Custom metadata
CacheControl string // Cache-Control header
ACL string // Access control (e.g., "public-read")
Overwrite bool // Allow overwriting existing files
}
PutOptions configures upload behavior.
func ApplyPutOptions ¶
func ApplyPutOptions(opts []PutOption) *PutOptions
ApplyPutOptions applies PutOption functions to PutOptions.
type SignedURLOption ¶
type SignedURLOption func(*SignedURLOptions)
SignedURLOption is a function that modifies SignedURLOptions.
func WithExpires ¶
func WithExpires(expires time.Duration) SignedURLOption
WithExpires sets the URL expiration time.
func WithHeaders ¶
func WithHeaders(headers map[string]string) SignedURLOption
WithHeaders sets additional headers for signed URLs.
func WithMethod ¶
func WithMethod(method string) SignedURLOption
WithMethod sets the HTTP method for the signed URL.
func WithSignedContentType ¶
func WithSignedContentType(contentType string) SignedURLOption
WithSignedContentType sets the content type for PUT signed URLs.
type SignedURLOptions ¶
type SignedURLOptions struct {
Expires time.Duration // URL expiration time
Method string // HTTP method (GET, PUT)
ContentType string // Content-Type for PUT requests
Headers map[string]string // Additional headers
}
SignedURLOptions configures signed URL generation.
func ApplySignedURLOptions ¶
func ApplySignedURLOptions(opts []SignedURLOption) *SignedURLOptions
ApplySignedURLOptions applies SignedURLOption functions to SignedURLOptions.
type Storage ¶
type Storage interface {
// Put uploads content to the specified path.
Put(ctx context.Context, path string, reader io.Reader, opts ...PutOption) (*FileInfo, error)
// Get retrieves content from the specified path.
Get(ctx context.Context, path string) (io.ReadCloser, error)
// Delete removes the file at the specified path.
Delete(ctx context.Context, path string) error
// Exists checks if a file exists at the specified path.
Exists(ctx context.Context, path string) (bool, error)
// Stat returns file information without downloading content.
Stat(ctx context.Context, path string) (*FileInfo, error)
// List returns files matching the prefix.
List(ctx context.Context, prefix string, opts ...ListOption) (*ListResult, error)
// Copy copies a file from src to dst.
Copy(ctx context.Context, src, dst string) error
// Move moves a file from src to dst.
Move(ctx context.Context, src, dst string) error
// URL returns a public URL for the file (if supported).
URL(ctx context.Context, path string) (string, error)
// SignedURL returns a pre-signed URL for temporary access.
SignedURL(ctx context.Context, path string, opts ...SignedURLOption) (string, error)
// Close releases any resources held by the storage backend.
Close() error
}
Storage defines the interface for storage backends.
Directories
¶
| Path | Synopsis |
|---|---|
|
examples
|
|
|
basic
command
Example: basic demonstrates core objstore operations using local filesystem storage.
|
Example: basic demonstrates core objstore operations using local filesystem storage. |
|
helpers
command
Example: helpers demonstrates objstore helper functions using in-memory storage.
|
Example: helpers demonstrates objstore helper functions using in-memory storage. |
|
switching-backends
command
Example: switching-backends demonstrates how to swap storage backends using the unified objstore.Storage interface.
|
Example: switching-backends demonstrates how to swap storage backends using the unified objstore.Storage interface. |