Documentation
¶
Overview ¶
Package storage provides a pluggable file storage solution for Go developers. Configure once via YAML/JSON, use everywhere without writing initialization code.
Index ¶
- Variables
- func Debug() bool
- func Delete(key string) error
- func DetectContentType(filename string) string
- func DownloadToFile(ctx context.Context, s Storage, key, filePath string) error
- func Drivers() []string
- func EnableDebugLog()
- func Exists(key string) (bool, error)
- func GenerateKey(prefix, filename string) string
- func GenerateKeyFlat(prefix, filename string) string
- func Get(key string) (io.ReadCloser, error)
- func GetBytes(key string) ([]byte, error)
- func GetString(key string) (string, error)
- func IsNotExist(err error) bool
- func IsNotFoundError(err error) bool
- func IsPermissionError(err error) bool
- func Must[T any](v T, err error) T
- func MustSetup(cfg map[string]any)
- func Register(name string, driver Driver)
- func Retry(ctx context.Context, maxAttempts int, fn func() error) error
- func SetLogger(l Logger)
- func Setup(cfg map[string]any) error
- func URL(key string) (string, error)
- type AdvancedStorage
- type BatchDeleteResult
- type BatchError
- type BatchUploadItem
- type BatchUploadResult
- type Config
- type DiskWrapper
- func (d *DiskWrapper) Delete(key string) error
- func (d *DiskWrapper) Exists(key string) (bool, error)
- func (d *DiskWrapper) Get(key string) (io.ReadCloser, error)
- func (d *DiskWrapper) GetBytes(key string) ([]byte, error)
- func (d *DiskWrapper) GetString(key string) (string, error)
- func (d *DiskWrapper) GetWithContext(ctx context.Context, key string) (io.ReadCloser, error)
- func (d *DiskWrapper) MustGet(key string) io.ReadCloser
- func (d *DiskWrapper) MustPut(key string, reader io.Reader, opts ...UploadOption) *UploadResult
- func (d *DiskWrapper) Put(key string, reader io.Reader, opts ...UploadOption) (*UploadResult, error)
- func (d *DiskWrapper) PutBytes(key string, data []byte, opts ...UploadOption) (*UploadResult, error)
- func (d *DiskWrapper) PutFile(key, filePath string, opts ...UploadOption) (*UploadResult, error)
- func (d *DiskWrapper) PutString(key, content string, opts ...UploadOption) (*UploadResult, error)
- func (d *DiskWrapper) PutWithContext(ctx context.Context, key string, reader io.Reader, opts ...UploadOption) (*UploadResult, error)
- func (d *DiskWrapper) Storage() (Storage, error)
- func (d *DiskWrapper) URL(key string) (string, error)
- type Driver
- type Error
- type FileInfo
- type ListOption
- type ListOptions
- type ListResult
- type Logger
- type LoggingStorage
- type Manager
- type ProgressReader
- type SizeReader
- type SlogAdapter
- type Storage
- type StorageConfig
- type UploadOption
- type UploadOptions
- type UploadResult
- func Put(key string, reader io.Reader, opts ...UploadOption) (*UploadResult, error)
- func PutBytes(key string, data []byte, opts ...UploadOption) (*UploadResult, error)
- func PutFile(key, filePath string, opts ...UploadOption) (*UploadResult, error)
- func PutString(key, content string, opts ...UploadOption) (*UploadResult, error)
- func UploadFile(ctx context.Context, s Storage, key, filePath string, opts ...UploadOption) (*UploadResult, error)
Constants ¶
This section is empty.
Variables ¶
var ( ErrNotFound = errors.New("storage: file not found") ErrAlreadyExists = errors.New("storage: file already exists") ErrPermission = errors.New("storage: permission denied") ErrInvalidKey = errors.New("storage: invalid key") ErrNotImplemented = errors.New("storage: not implemented") ErrClosed = errors.New("storage: storage is closed") )
Common errors.
Functions ¶
func DetectContentType ¶
DetectContentType detects the content type based on file extension.
func DownloadToFile ¶
DownloadToFile is a convenience function to download a file to disk.
func GenerateKey ¶
GenerateKey generates a unique key for a file. Format: prefix/2006/01/02/uuid.ext
func GenerateKeyFlat ¶
GenerateKeyFlat generates a unique key without date directories. Format: prefix/uuid.ext
func IsNotExist ¶
IsNotExist checks if the error indicates the file does not exist.
func IsNotFoundError ¶
IsNotFound checks if the error is a "not found" error.
func IsPermissionError ¶
IsPermissionError checks if the error is a permission error.
func Register ¶
Register registers a storage driver. This is typically called in init() by each driver package.
func Setup ¶
Setup initializes storage from a map (works with viper, koanf, etc).
Example with viper:
viper.ReadInConfig()
storage.Setup(viper.GetStringMap("storage"))
Example with raw map:
storage.Setup(map[string]any{
"default": "local",
"disks": map[string]any{
"local": map[string]any{
"driver": "local",
"root": "./uploads",
},
},
})
Types ¶
type AdvancedStorage ¶
type AdvancedStorage interface {
Storage
// SignedURL generates a pre-signed URL for temporary access to private files.
// expires specifies how long the URL should be valid.
SignedURL(ctx context.Context, key string, expires time.Duration) (string, error)
// List lists files in the storage with the given prefix.
List(ctx context.Context, prefix string, opts ...ListOption) (*ListResult, error)
// Copy copies a file from src to dst within the same storage.
Copy(ctx context.Context, src, dst string) error
// Move moves a file from src to dst within the same storage.
Move(ctx context.Context, src, dst string) error
// Size returns the size of a file in bytes.
Size(ctx context.Context, key string) (int64, error)
// Metadata returns the metadata of a file.
Metadata(ctx context.Context, key string) (*FileInfo, error)
}
AdvancedStorage extends Storage with optional advanced features. Not all drivers support these methods.
type BatchDeleteResult ¶
type BatchDeleteResult struct {
Succeeded []string
Failed []BatchError
}
BatchDeleteResult contains results of a batch delete.
func BatchDelete ¶
BatchDelete deletes multiple files concurrently.
type BatchError ¶
BatchError represents an error for a single item in a batch operation.
type BatchUploadItem ¶
type BatchUploadItem struct {
Key string
Reader io.Reader
Opts []UploadOption
}
BatchUploadItem represents a single item in a batch upload.
type BatchUploadResult ¶
type BatchUploadResult struct {
Succeeded []*UploadResult
Failed []BatchError
}
BatchUploadResult contains results of a batch upload.
func BatchUpload ¶
func BatchUpload(ctx context.Context, s Storage, items []BatchUploadItem, concurrency int) *BatchUploadResult
BatchUpload uploads multiple files concurrently. concurrency controls how many uploads run in parallel (0 = no limit).
type Config ¶
type Config struct {
Default string `yaml:"default" json:"default"`
Storages map[string]StorageConfig `yaml:"storages" json:"storages"`
}
Config represents the storage configuration structure.
type DiskWrapper ¶
type DiskWrapper struct {
// contains filtered or unexported fields
}
DiskWrapper provides a fluent API for storage operations.
func Disk ¶
func Disk(name string) *DiskWrapper
Disk returns a storage disk by name. Returns the default disk if name is empty.
func (*DiskWrapper) Delete ¶
func (d *DiskWrapper) Delete(key string) error
Delete removes a file from the storage.
func (*DiskWrapper) Exists ¶
func (d *DiskWrapper) Exists(key string) (bool, error)
Exists checks if a file exists.
func (*DiskWrapper) Get ¶
func (d *DiskWrapper) Get(key string) (io.ReadCloser, error)
Get downloads data from the storage.
func (*DiskWrapper) GetBytes ¶
func (d *DiskWrapper) GetBytes(key string) ([]byte, error)
GetBytes downloads and returns bytes.
func (*DiskWrapper) GetString ¶
func (d *DiskWrapper) GetString(key string) (string, error)
GetString downloads and returns string.
func (*DiskWrapper) GetWithContext ¶
func (d *DiskWrapper) GetWithContext(ctx context.Context, key string) (io.ReadCloser, error)
GetWithContext downloads data with context.
func (*DiskWrapper) MustGet ¶
func (d *DiskWrapper) MustGet(key string) io.ReadCloser
MustGet downloads and panics on error.
func (*DiskWrapper) MustPut ¶
func (d *DiskWrapper) MustPut(key string, reader io.Reader, opts ...UploadOption) *UploadResult
MustPut uploads and panics on error.
func (*DiskWrapper) Put ¶
func (d *DiskWrapper) Put(key string, reader io.Reader, opts ...UploadOption) (*UploadResult, error)
Put uploads data to the storage.
func (*DiskWrapper) PutBytes ¶
func (d *DiskWrapper) PutBytes(key string, data []byte, opts ...UploadOption) (*UploadResult, error)
PutBytes uploads bytes directly.
func (*DiskWrapper) PutFile ¶
func (d *DiskWrapper) PutFile(key, filePath string, opts ...UploadOption) (*UploadResult, error)
PutFile uploads a file from local path.
func (*DiskWrapper) PutString ¶
func (d *DiskWrapper) PutString(key, content string, opts ...UploadOption) (*UploadResult, error)
PutString uploads a string directly.
func (*DiskWrapper) PutWithContext ¶
func (d *DiskWrapper) PutWithContext(ctx context.Context, key string, reader io.Reader, opts ...UploadOption) (*UploadResult, error)
PutWithContext uploads data with context.
func (*DiskWrapper) Storage ¶
func (d *DiskWrapper) Storage() (Storage, error)
Storage returns the underlying Storage interface. Use this to access AdvancedStorage features like SignedURL, List, etc.
Example:
s, err := storage.Disk("aliyun").Storage()
if adv, ok := s.(storage.AdvancedStorage); ok {
url, _ := adv.SignedURL(ctx, "file.txt", time.Hour)
}
type Error ¶
type Error struct {
Op string // Operation that failed (e.g., "upload", "download")
Driver string // Driver name (e.g., "aliyun", "s3")
Key string // File key
Err error // Underlying error
}
Error represents a storage error with additional context.
type FileInfo ¶
type FileInfo struct {
Key string
Size int64
LastModified time.Time
ContentType string
ETag string
Metadata map[string]string
}
FileInfo contains metadata about a file.
type ListOption ¶
type ListOption func(*ListOptions)
ListOption is a functional option for List.
func WithDelimiter ¶
func WithDelimiter(d string) ListOption
WithDelimiter sets the delimiter for directory-like listing.
func WithMarker ¶
func WithMarker(marker string) ListOption
WithMarker sets the marker for pagination.
func WithMaxKeys ¶
func WithMaxKeys(n int) ListOption
WithMaxKeys sets the maximum number of keys to return.
type ListOptions ¶
type ListOptions struct {
MaxKeys int
Marker string // Start listing after this key
Delimiter string // e.g., "/" for directory-like listing
}
ListOptions configures list behavior.
type ListResult ¶
type ListResult struct {
Files []FileInfo
NextMarker string // For pagination
IsTruncated bool // Whether there are more results
}
ListResult contains the result of a List operation.
type Logger ¶
type Logger interface {
Debug(msg string, args ...any)
Info(msg string, args ...any)
Warn(msg string, args ...any)
Error(msg string, args ...any)
}
Logger interface for custom logging.
type LoggingStorage ¶
type LoggingStorage struct {
Storage
// contains filtered or unexported fields
}
LoggingStorage wraps a Storage with logging.
func WrapWithLogging ¶
func WrapWithLogging(s Storage, name string, logger Logger) *LoggingStorage
WrapWithLogging wraps a storage with logging.
func (*LoggingStorage) Delete ¶
func (l *LoggingStorage) Delete(ctx context.Context, key string) error
func (*LoggingStorage) Download ¶
func (l *LoggingStorage) Download(ctx context.Context, key string) (io.ReadCloser, error)
func (*LoggingStorage) Upload ¶
func (l *LoggingStorage) Upload(ctx context.Context, key string, reader io.Reader, opts ...UploadOption) (*UploadResult, error)
type Manager ¶
type Manager struct {
// contains filtered or unexported fields
}
Manager manages multiple storage backends based on configuration.
func NewManager ¶
NewManager creates a new storage manager from configuration.
type ProgressReader ¶
type ProgressReader struct {
// contains filtered or unexported fields
}
ProgressReader wraps a reader to track progress.
func NewProgressReader ¶
func NewProgressReader(r io.Reader, total int64, fn func(uploaded, total int64)) *ProgressReader
NewProgressReader creates a new progress reader.
type SizeReader ¶
SizeReader wraps a reader to get its size.
func NewSizeReader ¶
func NewSizeReader(r io.Reader, size int64) *SizeReader
NewSizeReader creates a reader that knows its size.
type SlogAdapter ¶
type SlogAdapter struct {
// contains filtered or unexported fields
}
SlogAdapter adapts slog.Logger to our Logger interface. Usage: storage.SetLogger(storage.NewSlogAdapter(slog.Default()))
func NewSlogAdapter ¶
func (*SlogAdapter) Debug ¶
func (a *SlogAdapter) Debug(msg string, args ...any)
func (*SlogAdapter) Error ¶
func (a *SlogAdapter) Error(msg string, args ...any)
func (*SlogAdapter) Info ¶
func (a *SlogAdapter) Info(msg string, args ...any)
func (*SlogAdapter) Warn ¶
func (a *SlogAdapter) Warn(msg string, args ...any)
type Storage ¶
type Storage interface {
// Upload uploads a file to the storage backend.
Upload(ctx context.Context, key string, reader io.Reader, opts ...UploadOption) (*UploadResult, error)
// Download downloads a file from the storage backend.
Download(ctx context.Context, key string) (io.ReadCloser, error)
// Delete deletes a file from the storage backend.
Delete(ctx context.Context, key string) error
// Exists checks if a file exists in the storage backend.
Exists(ctx context.Context, key string) (bool, error)
// URL returns the public URL of a file (if supported).
URL(ctx context.Context, key string) (string, error)
// Close releases any resources held by the storage backend.
Close() error
}
Storage is the main interface that all storage backends must implement.
type StorageConfig ¶
type StorageConfig struct {
Driver string `yaml:"driver" json:"driver"`
Options map[string]any `yaml:"options" json:"options"`
}
StorageConfig represents a single storage backend configuration.
type UploadOption ¶
type UploadOption func(*UploadOptions)
UploadOption is a functional option for Upload.
func WithContentDisposition ¶
func WithContentDisposition(cd string) UploadOption
WithContentDisposition sets the content disposition.
func WithContentType ¶
func WithContentType(ct string) UploadOption
WithContentType sets the content type.
func WithMetadata ¶
func WithMetadata(m map[string]string) UploadOption
WithMetadata sets custom metadata.
func WithProgress ¶
func WithProgress(fn func(uploaded, total int64)) UploadOption
WithProgress sets a progress callback for upload.
type UploadOptions ¶
type UploadOptions struct {
ContentType string
ContentDisposition string
Metadata map[string]string
ACL string // e.g., "public-read", "private"
ProgressFn func(uploaded, total int64) // Progress callback
}
UploadOptions configures upload behavior.
type UploadResult ¶
type UploadResult struct {
Key string // The key/path of the uploaded file
URL string // Public URL (if available)
Size int64 // Size in bytes
ETag string // ETag/checksum (if available)
Metadata map[string]string // Additional metadata
}
UploadResult contains information about an uploaded file.
func Put ¶
func Put(key string, reader io.Reader, opts ...UploadOption) (*UploadResult, error)
Put uploads to the default disk.
func PutBytes ¶
func PutBytes(key string, data []byte, opts ...UploadOption) (*UploadResult, error)
PutBytes uploads bytes directly.
func PutFile ¶
func PutFile(key, filePath string, opts ...UploadOption) (*UploadResult, error)
PutFile uploads a file from local path.
func PutString ¶
func PutString(key, content string, opts ...UploadOption) (*UploadResult, error)
PutString uploads a string directly.
func UploadFile ¶
func UploadFile(ctx context.Context, s Storage, key, filePath string, opts ...UploadOption) (*UploadResult, error)
UploadFile is a convenience function to upload a file from disk.