filekit

package
v0.1.1 Latest Latest
Warning

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

Go to latest
Published: Aug 18, 2025 License: Apache-2.0 Imports: 18 Imported by: 0

README

FileKit

FileKit is a robust, secure, and easy-to-use filesystem abstraction package for Go that handles multiple cloud providers with a unified API.

Features

  • Small, composable interfaces following Go idioms
  • Clear separation of concerns between different filesystem operations
  • Strong security with built-in encryption and access control
  • Streaming-first approach for efficient handling of large files
  • Comprehensive error handling with rich context
  • Extensive adapter support with a consistent API across all storage backends
  • Configuration-based initialization with environment variable support
  • Built-in file validation and constraints

Installation

go get github.com/beaver-kit/filekit

Quick Start

Using Configuration

FileKit now supports configuration-based initialization using the config package:

// Initialize from environment variables
if err := filekit.InitFromEnv(); err != nil {
    log.Fatal(err)
}

// Use the global instance
fs := filekit.FS()

// Upload a file
err := fs.Upload(context.Background(), "example.txt", content)
Environment Variables

Configure FileKit using environment variables:

# Driver selection
BEAVER_FILEKIT_DRIVER=s3  # or "local"

# Local driver settings
BEAVER_FILEKIT_LOCAL_BASE_PATH=./storage

# S3 driver settings
BEAVER_FILEKIT_S3_REGION=us-east-1
BEAVER_FILEKIT_S3_BUCKET=my-bucket
BEAVER_FILEKIT_S3_PREFIX=uploads/
BEAVER_FILEKIT_S3_ACCESS_KEY_ID=your-key-id
BEAVER_FILEKIT_S3_SECRET_ACCESS_KEY=your-secret-key

# Default options
BEAVER_FILEKIT_DEFAULT_VISIBILITY=private
BEAVER_FILEKIT_DEFAULT_CACHE_CONTROL=max-age=3600
BEAVER_FILEKIT_DEFAULT_OVERWRITE=false

# File validation
BEAVER_FILEKIT_MAX_FILE_SIZE=10485760  # 10MB
BEAVER_FILEKIT_ALLOWED_MIME_TYPES=image/jpeg,image/png,application/pdf
BEAVER_FILEKIT_ALLOWED_EXTENSIONS=.jpg,.jpeg,.png,.pdf

# Encryption
BEAVER_FILEKIT_ENCRYPTION_ENABLED=false
BEAVER_FILEKIT_ENCRYPTION_ALGORITHM=AES-256-GCM
BEAVER_FILEKIT_ENCRYPTION_KEY=your-base64-encoded-32-byte-key
Custom Configuration

Create a custom configuration programmatically:

cfg := filekit.Config{
    Driver:        "s3",
    S3Region:      "us-west-2",
    S3Bucket:      "my-bucket",
    S3Prefix:      "uploads/",
    
    // Default options
    DefaultVisibility: "private",
    MaxFileSize:      5 * 1024 * 1024, // 5MB
    AllowedMimeTypes: "image/jpeg,image/png",
}

fs, err := filekit.New(cfg)
if err != nil {
    log.Fatal(err)
}
Generating Encryption Keys

To use encryption, you need a base64-encoded 32-byte key:

import (
    "crypto/rand"
    "encoding/base64"
)

// Generate a random 32-byte key
key := make([]byte, 32)
if _, err := rand.Read(key); err != nil {
    panic(err)
}

// Encode to base64
encodedKey := base64.StdEncoding.EncodeToString(key)
fmt.Println("BEAVER_FILEKIT_ENCRYPTION_KEY=" + encodedKey)

Usage

Local Filesystem
package main

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

	"github.com/gobeaver/beaver-kit/filekit"
	"github.com/gobeaver/beaver-kit/filekit/driver/local"
)

func main() {
	// Create a local filesystem adapter
	fs, err := local.New("/tmp/filekit")
	if err != nil {
		panic(err)
	}

	// Upload a file
	content := strings.NewReader("Hello, World!")
	err = fs.Upload(context.Background(), "example.txt", content, filekit.WithContentType("text/plain"))
	if err != nil {
		panic(err)
	}
	fmt.Println("File uploaded successfully")

	// Download the file
	reader, err := fs.Download(context.Background(), "example.txt")
	if err != nil {
		panic(err)
	}
	defer reader.Close()

	data, err := io.ReadAll(reader)
	if err != nil {
		panic(err)
	}
	fmt.Println("File content:", string(data))

	// Delete the file
	err = fs.Delete(context.Background(), "example.txt")
	if err != nil {
		panic(err)
	}
	fmt.Println("File deleted successfully")
}
S3 Filesystem
package main

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

	"github.com/aws/aws-sdk-go-v2/config"
	"github.com/aws/aws-sdk-go-v2/service/s3"
	"github.com/gobeaver/beaver-kit/filekit"
	"github.com/gobeaver/beaver-kit/filekit/driver/s3"
)

func main() {
	// Load AWS configuration
	cfg, err := config.LoadDefaultConfig(context.Background())
	if err != nil {
		panic(err)
	}

	// Create S3 client
	s3Client := s3.NewFromConfig(cfg)

	// Create S3 filesystem adapter
	fs := s3.New(s3Client, "my-bucket", s3.WithPrefix("my-prefix"))

	// Upload a file
	content := strings.NewReader("Hello, World!")
	err = fs.Upload(context.Background(), "example.txt", content, 
		filekit.WithContentType("text/plain"),
		filekit.WithVisibility(filekit.Private),
	)
	if err != nil {
		panic(err)
	}
	fmt.Println("File uploaded successfully")

	// Download the file
	reader, err := fs.Download(context.Background(), "example.txt")
	if err != nil {
		panic(err)
	}
	defer reader.Close()

	data, err := io.ReadAll(reader)
	if err != nil {
		panic(err)
	}
	fmt.Println("File content:", string(data))

	// Delete the file
	err = fs.Delete(context.Background(), "example.txt")
	if err != nil {
		panic(err)
	}
	fmt.Println("File deleted successfully")
}
Chunked Uploads
package main

import (
	"context"
	"fmt"
	"os"

	"github.com/beaver-kit/filekit"
	"github.com/beaver-kit/filekit/driver/local"
)

func main() {
	// Create a local filesystem adapter
	fs, err := local.New("/tmp/filekit")
	if err != nil {
		panic(err)
	}

	// Open a large file
	file, err := os.Open("large-file.zip")
	if err != nil {
		panic(err)
	}
	defer file.Close()

	// Get file info
	fileInfo, err := file.Stat()
	if err != nil {
		panic(err)
	}

	// Upload with progress reporting
	err = filekit.Upload(context.Background(), fs, "large-file.zip", file, fileInfo.Size(), &filekit.UploadOptions{
		ContentType: "application/zip",
		ChunkSize:   5 * 1024 * 1024, // 5MB chunks
		Progress: func(transferred, total int64) {
			fmt.Printf("Progress: %d of %d bytes (%.2f%%)\n", transferred, total, float64(transferred)/float64(total)*100)
		},
	})
	if err != nil {
		panic(err)
	}
	fmt.Println("File uploaded successfully")
}
Encrypted Filesystem
package main

import (
	"context"
	"crypto/rand"
	"fmt"
	"io"
	"strings"

	"github.com/beaver-kit/filekit"
	"github.com/beaver-kit/filekit/driver/local"
)

func main() {
	// Create a local filesystem adapter
	fs, err := local.New("/tmp/filekit")
	if err != nil {
		panic(err)
	}

	// Generate a random encryption key (32 bytes for AES-256)
	key := make([]byte, 32)
	if _, err := rand.Read(key); err != nil {
		panic(err)
	}

	// Create an encrypted filesystem
	encryptedFS := filekit.NewEncryptedFS(fs, key)

	// Upload a file with encryption
	content := strings.NewReader("This is a secret message")
	err = encryptedFS.Upload(context.Background(), "secret.txt", content)
	if err != nil {
		panic(err)
	}
	fmt.Println("Encrypted file uploaded successfully")

	// Download and decrypt the file
	reader, err := encryptedFS.Download(context.Background(), "secret.txt")
	if err != nil {
		panic(err)
	}
	defer reader.Close()

	data, err := io.ReadAll(reader)
	if err != nil {
		panic(err)
	}
	fmt.Println("Decrypted content:", string(data))

	// Try to download with the original filesystem (will be encrypted)
	reader, err = fs.Download(context.Background(), "secret.txt")
	if err != nil {
		panic(err)
	}
	defer reader.Close()

	encryptedData, err := io.ReadAll(reader)
	if err != nil {
		panic(err)
	}
	fmt.Println("Raw encrypted content length:", len(encryptedData))
}
File Validation

FileKit integrates with the filevalidator package for comprehensive file validation:

package main

import (
	"context"
	"fmt"
	"strings"

	"github.com/beaver-kit/filekit"
	"github.com/beaver-kit/filekit/driver/local"
	"github.com/beaver-kit/filevalidator"
)

func main() {
	// Create a local filesystem adapter
	fs, err := local.New("/tmp/filekit")
	if err != nil {
		panic(err)
	}

	// Create a file validator with constraints
	constraints := filevalidator.Constraints{
		MaxFileSize:   10 * 1024 * 1024, // 10MB
		AcceptedTypes: []string{"image/*", "application/pdf"},
		AllowedExts:   []string{".jpg", ".jpeg", ".png", ".pdf"},
	}
	validator := filevalidator.New(constraints)

	// Create a validated filesystem
	validatedFS := filekit.NewValidatedFileSystem(fs, validator)

	// Upload a file with automatic validation
	content := strings.NewReader("PDF content here...")
	err = validatedFS.Upload(context.Background(), "document.pdf", content, 
		filekit.WithContentType("application/pdf"))
	if err != nil {
		fmt.Println("Validation error:", err)
		return
	}
	fmt.Println("File uploaded successfully")
}

Adapters

FileKit includes the following adapters:

  • Local filesystem
  • S3 compatible storage
  • Encrypted filesystem wrapper

Error Handling

FileKit provides detailed error handling with context:

err := fs.Upload(context.Background(), "example.txt", content)
if err != nil {
	var pathErr *filekit.PathError
	if errors.As(err, &pathErr) {
		fmt.Printf("Operation: %s, Path: %s, Error: %v\n", pathErr.Op, pathErr.Path, pathErr.Err)
	}
	
	if filekit.IsNotExist(err) {
		fmt.Println("File does not exist")
	} else if filekit.IsPermission(err) {
		fmt.Println("Permission denied")
	}
}

Package Structure

filekit/
├── fs.go           (main interfaces)
├── config.go       (configuration struct and loader)
├── service.go      (global instance management)
├── upload.go       (upload specific implementations)
├── stream.go       (streaming specific implementations)
├── errors.go       (error handling)
├── validated_fs.go (validation wrapper)
├── encryption.go   (encryption layer)
├── driver/
│   ├── local/
│   │   └── local.go
│   ├── s3/
│   │   └── s3.go
│   └── gcs/
│       └── gcs.go (future implementation)
└── options.go      (shared options and configurations)

TODO

  • FTP & SFTP adapter
  • Google Cloud Storage adapter
  • Memory adapter for testing
  • Additional encryption methods

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

License

This project is licensed under the MIT License - see the LICENSE file for details.

Documentation

Index

Constants

View Source
const (
	MIMETypeTextPlain       = "text/plain"
	MIMETypeTextHTML        = "text/html"
	MIMETypeTextCSS         = "text/css"
	MIMETypeTextJavaScript  = "text/javascript"
	MIMETypeApplicationJSON = "application/json"
	MIMETypeApplicationXML  = "application/xml"
	MIMETypeImageJPEG       = "image/jpeg"
	MIMETypeImagePNG        = "image/png"
	MIMETypeImageGIF        = "image/gif"
	MIMETypeImageSVG        = "image/svg+xml"
	MIMETypeImageWebP       = "image/webp"
	MIMETypeAudioMP3        = "audio/mpeg"
	MIMETypeAudioOGG        = "audio/ogg"
	MIMETypeVideoMP4        = "video/mp4"
	MIMETypeVideoWebM       = "video/webm"
	MIMETypeApplicationPDF  = "application/pdf"
	MIMETypeApplicationZip  = "application/zip"
)

Common MIME types

Variables

View Source
var (
	ErrNotExist      = errors.New("file does not exist")
	ErrExist         = errors.New("file already exists")
	ErrPermission    = errors.New("permission denied")
	ErrClosed        = errors.New("file already closed")
	ErrNotDir        = errors.New("not a directory")
	ErrIsDir         = errors.New("is a directory")
	ErrNotEmpty      = errors.New("directory not empty")
	ErrInvalidName   = errors.New("invalid name")
	ErrInvalidOffset = errors.New("invalid offset")
	ErrInvalidWhence = errors.New("invalid whence")
	ErrNotSupported  = errors.New("operation not supported")
	ErrNotAllowed    = errors.New("operation not allowed")
)

Common filesystem errors

Functions

func GetFileExtensionForMIME added in v0.0.4

func GetFileExtensionForMIME(contentType string) string

GetFileExtensionForMIME returns a suitable file extension for a given MIME type

func GuessContentType added in v0.0.4

func GuessContentType(filePath string, data []byte) string

GuessContentType tries to determine the content type of a file from its path and data

func Init added in v0.1.0

func Init(configs ...Config) error

Init initializes the global file system instance

func InitFromEnv added in v0.1.0

func InitFromEnv() error

InitFromEnv initializes the global instance from environment variables (convenience method)

func IsAudioFile added in v0.0.4

func IsAudioFile(contentType string) bool

IsAudioFile returns true if the file is an audio file based on its MIME type

func IsCompressedFile added in v0.0.4

func IsCompressedFile(contentType string) bool

IsCompressedFile returns true if the file is a compressed file based on its MIME type

func IsExist added in v0.0.4

func IsExist(err error) bool

IsExist reports whether an error indicates that a file or directory already exists

func IsImageFile added in v0.0.4

func IsImageFile(contentType string) bool

IsImageFile returns true if the file is an image file based on its MIME type

func IsNotExist added in v0.0.4

func IsNotExist(err error) bool

IsNotExist reports whether an error indicates that a file or directory does not exist

func IsPDFFile added in v0.0.4

func IsPDFFile(contentType string) bool

IsPDFFile returns true if the file is a PDF file based on its MIME type

func IsPermission added in v0.0.4

func IsPermission(err error) bool

IsPermission reports whether an error indicates that permission is denied

func IsTextFile added in v0.0.4

func IsTextFile(contentType string) bool

IsTextFile returns true if the file is a text file based on its MIME type

func IsVideoFile added in v0.0.4

func IsVideoFile(contentType string) bool

IsVideoFile returns true if the file is a video file based on its MIME type

func RegisterDriver added in v0.1.0

func RegisterDriver(name string, factory DriverFactory)

RegisterDriver registers a driver factory function

func Reset added in v0.1.0

func Reset()

Reset clears the global instance (for testing)

func Upload added in v0.0.4

func Upload(ctx context.Context, fs FileSystem, path string, r io.Reader, size int64, opts *UploadOptions) error

Upload uploads a file to the filesystem with the given options

Types

type Builder added in v0.1.0

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

Builder provides a way to create FileSystem instances with custom prefixes

func WithPrefix added in v0.1.0

func WithPrefix(prefix string) *Builder

WithPrefix creates a new Builder with the specified prefix

func (*Builder) Init added in v0.1.0

func (b *Builder) Init() error

Init initializes the global FileSystem instance using the builder's prefix

func (*Builder) New added in v0.1.0

func (b *Builder) New() (FileSystem, error)

New creates a new FileSystem instance using the builder's prefix

type ChunkedUploader added in v0.0.4

type ChunkedUploader interface {
	// InitiateUpload starts a chunked upload process and returns an upload ID
	InitiateUpload(ctx context.Context, path string) (string, error)

	// UploadPart uploads a part of a file in a chunked upload process
	UploadPart(ctx context.Context, uploadID string, partNumber int, data []byte) error

	// CompleteUpload finalizes a chunked upload
	CompleteUpload(ctx context.Context, uploadID string) error

	// AbortUpload cancels a chunked upload
	AbortUpload(ctx context.Context, uploadID string) error
}

ChunkedUploader is the interface for filesystems that support chunked uploads

type Config added in v0.1.0

type Config struct {
	// Default driver to use (local, s3)
	Driver string `env:"FILEKIT_DRIVER,default:local"`

	// Local driver configuration
	LocalBasePath string `env:"FILEKIT_LOCAL_BASE_PATH,default:./storage"`

	// S3 driver configuration
	S3Region          string `env:"FILEKIT_S3_REGION,default:us-east-1"`
	S3Bucket          string `env:"FILEKIT_S3_BUCKET"`
	S3Prefix          string `env:"FILEKIT_S3_PREFIX"`
	S3Endpoint        string `env:"FILEKIT_S3_ENDPOINT"`
	S3AccessKeyID     string `env:"FILEKIT_S3_ACCESS_KEY_ID"`
	S3SecretAccessKey string `env:"FILEKIT_S3_SECRET_ACCESS_KEY"`
	S3ForcePathStyle  bool   `env:"FILEKIT_S3_FORCE_PATH_STYLE,default:false"`

	// Default upload options
	DefaultVisibility       string `env:"FILEKIT_DEFAULT_VISIBILITY,default:private"`
	DefaultCacheControl     string `env:"FILEKIT_DEFAULT_CACHE_CONTROL"`
	DefaultOverwrite        bool   `env:"FILEKIT_DEFAULT_OVERWRITE,default:false"`
	DefaultPreserveFilename bool   `env:"FILEKIT_DEFAULT_PRESERVE_FILENAME,default:false"`

	// File validation defaults
	MaxFileSize       int64  `env:"FILEKIT_MAX_FILE_SIZE,default:10485760"` // 10MB default
	AllowedMimeTypes  string `env:"FILEKIT_ALLOWED_MIME_TYPES"`             // comma-separated
	BlockedMimeTypes  string `env:"FILEKIT_BLOCKED_MIME_TYPES"`             // comma-separated
	AllowedExtensions string `env:"FILEKIT_ALLOWED_EXTENSIONS"`             // comma-separated
	BlockedExtensions string `env:"FILEKIT_BLOCKED_EXTENSIONS"`             // comma-separated

	// Encryption settings
	EncryptionEnabled   bool   `env:"FILEKIT_ENCRYPTION_ENABLED,default:false"`
	EncryptionAlgorithm string `env:"FILEKIT_ENCRYPTION_ALGORITHM,default:AES-256-GCM"`
	EncryptionKey       string `env:"FILEKIT_ENCRYPTION_KEY"`
}

func GetConfig added in v0.1.0

func GetConfig() (*Config, error)

GetConfig returns config loaded from environment

type DriverFactory added in v0.1.0

type DriverFactory func(cfg Config) (FileSystem, error)

DriverFactory is a function that creates a FileSystem from a config

type EncryptedFS added in v0.0.4

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

EncryptedFS is a wrapper around a FileSystem that encrypts and decrypts data

func NewEncryptedFS added in v0.0.4

func NewEncryptedFS(fs FileSystem, key []byte) *EncryptedFS

NewEncryptedFS creates a new encrypted filesystem

func (*EncryptedFS) CreateDir added in v0.0.4

func (e *EncryptedFS) CreateDir(ctx context.Context, path string) error

CreateDir delegates to the underlying filesystem

func (*EncryptedFS) Delete added in v0.0.4

func (e *EncryptedFS) Delete(ctx context.Context, path string) error

Delete delegates to the underlying filesystem

func (*EncryptedFS) DeleteDir added in v0.0.4

func (e *EncryptedFS) DeleteDir(ctx context.Context, path string) error

DeleteDir delegates to the underlying filesystem

func (*EncryptedFS) Download added in v0.0.4

func (e *EncryptedFS) Download(ctx context.Context, path string) (io.ReadCloser, error)

Download decrypts the content after downloading

func (*EncryptedFS) Exists added in v0.0.4

func (e *EncryptedFS) Exists(ctx context.Context, path string) (bool, error)

Exists delegates to the underlying filesystem

func (*EncryptedFS) FileInfo added in v0.0.4

func (e *EncryptedFS) FileInfo(ctx context.Context, path string) (*File, error)

FileInfo delegates to the underlying filesystem

func (*EncryptedFS) List added in v0.0.4

func (e *EncryptedFS) List(ctx context.Context, prefix string) ([]File, error)

List delegates to the underlying filesystem

func (*EncryptedFS) Upload added in v0.0.4

func (e *EncryptedFS) Upload(ctx context.Context, path string, content io.Reader, options ...Option) error

Upload encrypts the content before uploading

func (*EncryptedFS) UploadFile added in v0.0.4

func (e *EncryptedFS) UploadFile(ctx context.Context, path, localPath string, options ...Option) error

UploadFile encrypts and uploads a local file

type EncryptionOptions added in v0.0.4

type EncryptionOptions struct {
	// Algorithm specifies the encryption algorithm to use
	Algorithm string

	// Key is the encryption key
	Key []byte

	// KeyID is an identifier for the encryption key (for key rotation)
	KeyID string
}

EncryptionOptions contains options for file encryption

type File

type File struct {
	Name        string
	Path        string
	Size        int64
	ModTime     time.Time
	IsDir       bool
	ContentType string
	Metadata    map[string]string
}

File represents a file in the filesystem

type FileSystem

type FileSystem interface {
	// Core operations
	Upload(ctx context.Context, path string, content io.Reader, options ...Option) error
	Download(ctx context.Context, path string) (io.ReadCloser, error)
	Delete(ctx context.Context, path string) error

	// File operations
	Exists(ctx context.Context, path string) (bool, error)
	FileInfo(ctx context.Context, path string) (*File, error)

	// Directory operations
	List(ctx context.Context, prefix string) ([]File, error)
	CreateDir(ctx context.Context, path string) error
	DeleteDir(ctx context.Context, path string) error
}

FileSystem defines the main interface for file operations

func CreateDriver added in v0.1.0

func CreateDriver(cfg Config) (FileSystem, error)

CreateDriver creates a driver instance from config

func Default added in v0.1.0

func Default() (FileSystem, error)

Default returns the global instance, initializing if needed with error handling

func FS added in v0.1.0

func FS() FileSystem

FS returns the global file system instance

func New added in v0.1.0

func New(cfg Config) (FileSystem, error)

New creates a new file system instance with given config

func NewFromEnv added in v0.1.0

func NewFromEnv() (FileSystem, error)

NewFromEnv creates instance from environment variables (convenience constructor)

type Option

type Option func(*Options)

Option represents a configuration option

func WithACL added in v0.0.4

func WithACL(acl string) Option

WithACL sets specific access control list settings

func WithCacheControl added in v0.0.4

func WithCacheControl(cacheControl string) Option

WithCacheControl sets the Cache-Control header

func WithContentDisposition added in v0.0.4

func WithContentDisposition(disposition string) Option

WithContentDisposition sets the Content-Disposition header

func WithContentType

func WithContentType(contentType string) Option

WithContentType sets the content type of the file

func WithEncryption added in v0.0.4

func WithEncryption(algorithm string, key []byte) Option

WithEncryption enables encryption for the file

func WithEncryptionKeyID added in v0.0.4

func WithEncryptionKeyID(algorithm string, key []byte, keyID string) Option

WithEncryptionKeyID enables encryption with a specific key ID

func WithExpires added in v0.0.4

func WithExpires(expires time.Time) Option

WithExpires sets when the file should expire

func WithHeaders added in v0.0.4

func WithHeaders(headers map[string]string) Option

WithHeaders sets additional HTTP headers

func WithMetadata

func WithMetadata(metadata map[string]string) Option

WithMetadata sets additional metadata for the file

func WithOverwrite added in v0.0.4

func WithOverwrite(overwrite bool) Option

WithOverwrite enables or disables overwriting existing files

func WithPreserveFilename added in v0.0.4

func WithPreserveFilename(preserve bool) Option

WithPreserveFilename enables or disables preserving the original filename

func WithValidator added in v0.0.4

func WithValidator(validator filevalidator.Validator) Option

WithValidator sets a file validator to use before upload

func WithVisibility

func WithVisibility(visibility Visibility) Option

WithVisibility sets the file visibility

type Options

type Options struct {
	// ContentType specifies the MIME type of the file
	ContentType string

	// Metadata contains additional metadata for the file
	Metadata map[string]string

	// Visibility defines the file visibility (public or private)
	Visibility Visibility

	// CacheControl sets the Cache-Control header for the file
	CacheControl string

	// Overwrite determines whether to overwrite existing files
	Overwrite bool

	// Encryption specifies encryption settings for the file
	Encryption *EncryptionOptions

	// Expires sets when the file should expire
	Expires *time.Time

	// PreserveFilename determines whether to keep the original filename
	PreserveFilename bool

	// Headers contains additional HTTP headers to set
	Headers map[string]string

	// SkipExistingCheck skips checking if a file already exists before upload
	SkipExistingCheck bool

	// ContentDisposition sets the Content-Disposition header
	ContentDisposition string

	// ACL sets specific access control list settings
	ACL string

	// Validator is an optional file validator to use before upload
	Validator filevalidator.Validator
}

Options contains all possible options for file operations

type PathError added in v0.0.4

type PathError struct {
	Op   string
	Path string
	Err  error
}

PathError records an error and the operation and file path that caused it

func (*PathError) Error added in v0.0.4

func (e *PathError) Error() string

Error implements the error interface

func (*PathError) Unwrap added in v0.0.4

func (e *PathError) Unwrap() error

Unwrap returns the underlying error

type ProgressFunc added in v0.0.4

type ProgressFunc func(bytesTransferred int64, totalBytes int64)

ProgressFunc is a callback function for upload progress

type Streamer

type Streamer interface {
	Stream(ctx context.Context, path string) (io.ReadCloser, error)
	StreamWrite(ctx context.Context, path string, reader io.Reader) error
}

Streamer interface for streaming operations

func NewStreamer

func NewStreamer(fs FileSystem) Streamer

type UploadOptions added in v0.0.4

type UploadOptions struct {
	// ContentType specifies the MIME type of the file
	ContentType string

	// ChunkSize defines the size of chunks for chunked upload
	// If zero, a default chunk size will be used
	ChunkSize int64

	// Progress is a callback function for upload progress
	Progress ProgressFunc

	// Metadata contains additional metadata for the file
	Metadata map[string]string

	// Visibility defines the file visibility (public or private)
	Visibility Visibility
}

UploadOptions contains options for uploading files

type Uploader

type Uploader interface {
	Upload(ctx context.Context, path string, content io.Reader, options ...Option) error
	UploadFile(ctx context.Context, path string, localPath string, options ...Option) error
}

Uploader interface specifically for upload operations

type ValidatedFileSystem added in v0.0.4

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

ValidatedFileSystem wraps a FileSystem with validation support

func NewValidatedFileSystem added in v0.0.4

func NewValidatedFileSystem(fs FileSystem, validator filevalidator.Validator) *ValidatedFileSystem

NewValidatedFileSystem creates a new FileSystem with validation

func (*ValidatedFileSystem) CreateDir added in v0.0.4

func (v *ValidatedFileSystem) CreateDir(ctx context.Context, path string) error

CreateDir implements FileSystem

func (*ValidatedFileSystem) Delete added in v0.0.4

func (v *ValidatedFileSystem) Delete(ctx context.Context, path string) error

Delete implements FileSystem

func (*ValidatedFileSystem) DeleteDir added in v0.0.4

func (v *ValidatedFileSystem) DeleteDir(ctx context.Context, path string) error

DeleteDir implements FileSystem

func (*ValidatedFileSystem) Download added in v0.0.4

func (v *ValidatedFileSystem) Download(ctx context.Context, path string) (io.ReadCloser, error)

Download implements FileSystem

func (*ValidatedFileSystem) Exists added in v0.0.4

func (v *ValidatedFileSystem) Exists(ctx context.Context, path string) (bool, error)

Exists implements FileSystem

func (*ValidatedFileSystem) FileInfo added in v0.0.4

func (v *ValidatedFileSystem) FileInfo(ctx context.Context, path string) (*File, error)

FileInfo implements FileSystem

func (*ValidatedFileSystem) List added in v0.0.4

func (v *ValidatedFileSystem) List(ctx context.Context, prefix string) ([]File, error)

List implements FileSystem

func (*ValidatedFileSystem) Upload added in v0.0.4

func (v *ValidatedFileSystem) Upload(ctx context.Context, path string, content io.Reader, options ...Option) error

Upload implements FileSystem with validation

type Visibility

type Visibility string

Visibility represents file visibility

const (
	// Private means the file is only accessible by authenticated users
	Private Visibility = "private"

	// Public means the file is publicly accessible
	Public Visibility = "public"

	// Protected means the file is accessible with specific permissions
	Protected Visibility = "protected"
)

Directories

Path Synopsis
driver
s3
examples
config command
local command

Jump to

Keyboard shortcuts

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