uploader

package module
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Nov 13, 2025 License: MIT Imports: 37 Imported by: 0

README

go-uploader

File upload library for Go with multiple storage backends.

Overview

go-uploader provides a unified interface for file uploads with support for AWS S3, local filesystem, and hybrid storage patterns. The library implements a provider pattern where different storage backends conform to the same Uploader interface.

Feature Highlights

  • Chunked uploads with resumable sessions (InitiateChunked, UploadChunk, CompleteChunked, AbortChunked) backed by AWS multipart uploads or filesystem chunk staging. See examples/chunked.
  • Direct-to-storage presigned posts including confirmation helpers so your API only receives metadata. See examples/presignedpost.
  • Server-side thumbnails driven by a pluggable ImageProcessor, producing derivative metadata alongside the original asset. See examples/thumbnails.
  • Post-upload callbacks with strict/best-effort modes and async executors for downstream automation. See examples/callbacks.

Need deeper design references?

  • FEATURE_TDD.md – behaviour-driven specs with current status references.
  • docs/FEATURE_DESIGN_NOTES.md – provider constraints and validation rules.
  • FEATURE_TSK.md – phased implementation tracker (updated after every phase).

Installation

go get github.com/goliatone/go-uploader

Quick Start

Filesystem Provider
package main

import (
    "context"
    "fmt"

    "github.com/goliatone/go-uploader"
)

func main() {
    // Create filesystem provider
    provider := uploader.NewFSProvider("/uploads")

    // Create manager with validation
    manager := uploader.NewManager(provider).
        WithMaxFileSize(10 * 1024 * 1024). // 10MB
        WithAllowedTypes([]string{"image/jpeg", "image/png"})

    // Upload file
    url, err := manager.UploadFile(context.Background(), "avatar.jpg", fileData)
    if err != nil {
        panic(err)
    }

    fmt.Printf("File uploaded: %s\n", url)
}
AWS S3 Provider
package main

import (
    "context"

    "github.com/aws/aws-sdk-go-v2/config"
    "github.com/aws/aws-sdk-go-v2/service/s3"
    "github.com/goliatone/go-uploader"
)

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

    // Create S3 client and provider
    client := s3.NewFromConfig(cfg)
    provider := uploader.NewAWSProvider(client, "my-bucket").
        WithBasePath("uploads/")

    // Create manager
    manager := uploader.NewManager(provider)

    // Upload with metadata
    url, err := manager.UploadFile(
        context.Background(),
        "document.pdf",
        fileData,
        uploader.WithContentType("application/pdf"),
        uploader.WithPublicAccess(true),
    )
    if err != nil {
        panic(err)
    }
}

Core Interface

type Uploader interface {
    UploadFile(ctx context.Context, path string, content []byte, opts ...UploadOption) (string, error)
    GetFile(ctx context.Context, path string) ([]byte, error)
    DeleteFile(ctx context.Context, path string) error
    GetPresignedURL(ctx context.Context, path string, expires time.Duration) (string, error)
}

Providers

FSProvider
  • Stores files on local filesystem
  • Uses Go's fs.FS interface for abstraction
  • URL generation for web serving
AWSProvider
  • Stores files in AWS S3
  • Supports presigned URLs
  • Configurable ACLs and metadata
MultiProvider
  • Hybrid storage: local caching + remote storage
  • Automatic fallback and synchronization
  • Configurable storage strategies

Validation

manager := uploader.NewManager(provider).
    WithMaxFileSize(5 * 1024 * 1024).                    // 5MB limit
    WithAllowedTypes([]string{"image/jpeg", "image/png"}). // MIME types
    WithAllowedExtensions([]string{".jpg", ".png"}).     // File extensions
    WithValidator(customValidator)                        // Custom validation

Upload Options

url, err := manager.UploadFile(ctx, "file.jpg", data,
    uploader.WithContentType("image/jpeg"),
    uploader.WithCacheControl("max-age=3600"),
    uploader.WithPublicAccess(true),
    uploader.WithTTL(24 * time.Hour),
)

Chunked Uploads

Large files or unreliable networks can use the chunked API, which streams parts to any provider implementing ChunkedUploader (AWS S3, filesystem, multi-provider).

session, err := manager.InitiateChunked(ctx, "videos/raw.mov", totalSize)
if err != nil {
    panic(err)
}

for idx, chunk := range parts {
    if err := manager.UploadChunk(ctx, session.ID, idx, bytes.NewReader(chunk)); err != nil {
        panic(err)
    }
}

meta, err := manager.CompleteChunked(ctx, session.ID)
if err != nil {
    panic(err)
}

fmt.Println("Uploaded via chunked API:", meta.URL)

Each session tracks expected part counts and expiries inside the manager's registry; both AWS and filesystem providers persist their own IDs so restarts continue safely. Try go run ./examples/chunked for a CLI that simulates a UI progress bar and inspects the staged data under .example-chunks/.

Direct to Storage Presigned Posts

Generate presigned POST data so browsers can upload directly to storage, then confirm the asset without proxying the bytes through your API.

post, err := manager.CreatePresignedPost(ctx, "uploads/raw.mov",
    uploader.WithContentType("video/quicktime"),
    uploader.WithTTL(10*time.Minute),
)
if err != nil {
    panic(err)
}

// Send post.URL + post.Fields to the browser for the actual upload.

meta, err := manager.ConfirmPresignedUpload(ctx, &uploader.PresignedUploadResult{
    Key:         "uploads/raw.mov",
    Size:        104857600,
    ContentType: "video/quicktime",
})
if err != nil {
    panic(err)
}

Use the generated payload to build a browser form:

<form action="{{ .URL }}" method="post" enctype="multipart/form-data">
  {{ range $k, $v := .Fields }}
    <input type="hidden" name="{{ $k }}" value="{{ $v }}">
  {{ end }}
  <input type="file" name="file">
  <button>Upload</button>
</form>

See examples/presignedpost/ for a runnable CLI plus a ready-to-copy HTML template.

Server Side Thumbnails

Generate consistent derivatives on the server after validating uploads.

sizes := []uploader.ThumbnailSize{
    {Name: "small", Width: 200, Height: 200, Fit: "cover"},
    {Name: "preview", Width: 800, Height: 600, Fit: "contain"},
}

imageMeta, err := manager.HandleImageWithThumbnails(ctx, fileHeader, "gallery", sizes)
if err != nil {
    panic(err)
}

fmt.Println("Original:", imageMeta.URL)
fmt.Println("Small thumb:", imageMeta.Thumbnails["small"].URL)

The default processor is pure Go and can be replaced via WithImageProcessor for advanced pipelines.

Post Upload Callbacks

Register a callback to perform follow-up work (virus scanning, notifications, etc.) after uploads complete.

manager := uploader.NewManager(
    uploader.WithProvider(provider),
    uploader.WithOnUploadComplete(func(ctx context.Context, meta *uploader.FileMeta) error {
        log.Printf("stored %s (%d bytes)", meta.Name, meta.Size)
        return nil
    }),
    uploader.WithCallbackMode(uploader.CallbackModeStrict),
)

Callbacks default to best-effort. Use CallbackModeStrict to fail uploads when the callback returns an error, or provide WithCallbackExecutor(NewAsyncCallbackExecutor(nil)) to dispatch work asynchronously.

Error Handling

The library uses structured error handling with categorized errors:

if gerrors.IsValidation(err) {
    // Handle validation errors
    if validationErrs, ok := gerrors.GetValidationErrors(err); ok {
        for _, fieldErr := range validationErrs {
            fmt.Printf("Field %s: %s\n", fieldErr.Field, fieldErr.Message)
        }
    }
}

if gerrors.IsNotFound(err) {
    // Handle file not found
}

Examples

See examples/README.md for full walkthroughs. Highlights:

  • examples/router/: HTTP server (Fiber + go-router) with upload API, gallery view, and presigned URL helper.
  • examples/chunked/: Chunk UI simulator that spins up chunk sessions, streams parts, and inspects the final artifact.
  • examples/presignedpost/: Presigned upload form generator plus CLI confirmation flow.
  • examples/thumbnails/: Thumbnail handler that renders gradients, resizes them, and prints resulting URLs.
  • examples/callbacks/: Demonstrates callback registration, logging, and strict/best-effort considerations.

Dependencies

  • github.com/aws/aws-sdk-go-v2: AWS S3 integration
  • github.com/goliatone/go-errors: Structured error handling
  • github.com/jszwec/s3fs/v2: S3 filesystem abstraction

License

Goliatone MIT

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// DefaultChunkSessionTTL is the fallback expiration applied to chunked upload sessions
	// when a custom TTL is not provided.
	DefaultChunkSessionTTL = 30 * time.Minute

	// DefaultChunkPartSize defines the default size (bytes) used for chunked uploads when
	// callers do not provide a custom size.
	DefaultChunkPartSize int64 = 5 * 1024 * 1024

	// DefaultPresignedPostTTL controls how long presigned posts remain valid when a custom TTL is not supplied.
	DefaultPresignedPostTTL = 15 * time.Minute

	// MaxPresignedPostTTL caps presigned post lifetimes to avoid long-lived public upload surfaces.
	MaxPresignedPostTTL = 24 * time.Hour

	// DefaultPresignedURLTTL determines how long confirmation URLs remain valid when returned via ConfirmPresignedUpload.
	DefaultPresignedURLTTL = 10 * time.Minute

	// DefaultPresignedMaxFileSize enforces the default max payload accepted via presigned uploads (matches validator default).
	DefaultPresignedMaxFileSize = DefaultMaxFileSize
)
View Source
var (
	ErrImageNotFound = gerrors.New("image not found", gerrors.CategoryNotFound).
						WithCode(404).
						WithTextCode("IMAGE_NOT_FOUND")

	ErrPermissionDenied = gerrors.New("permission denied", gerrors.CategoryAuthz).
						WithCode(403).
						WithTextCode("PERMISSION_DENIED")

	ErrInvalidPath = gerrors.New("invalid path", gerrors.CategoryBadInput).
					WithCode(400).
					WithTextCode("INVALID_PATH")

	ErrProviderNotConfigured = gerrors.New("provider not configured", gerrors.CategoryInternal).
								WithCode(500).
								WithTextCode("PROVIDER_NOT_CONFIGURED")

	ErrNotImplemented = gerrors.New("feature not implemented", gerrors.CategoryInternal).
						WithCode(501).
						WithTextCode("NOT_IMPLEMENTED")

	ErrChunkSessionNotFound = gerrors.New("chunk session not found", gerrors.CategoryNotFound).
							WithCode(404).
							WithTextCode("CHUNK_SESSION_NOT_FOUND")

	ErrChunkSessionExists = gerrors.New("chunk session already exists", gerrors.CategoryConflict).
							WithCode(409).
							WithTextCode("CHUNK_SESSION_EXISTS")

	ErrChunkSessionClosed = gerrors.New("chunk session is no longer active", gerrors.CategoryConflict).
							WithCode(409).
							WithTextCode("CHUNK_SESSION_CLOSED")

	ErrChunkPartOutOfRange = gerrors.New("chunk part index is out of range", gerrors.CategoryBadInput).
							WithCode(400).
							WithTextCode("CHUNK_PART_OUT_OF_RANGE")

	ErrChunkPartDuplicate = gerrors.New("chunk part already uploaded", gerrors.CategoryConflict).
							WithCode(409).
							WithTextCode("CHUNK_PART_DUPLICATE")
)
View Source
var (
	DefaultMaxFileSize  int64 = 25 * 1024 * 1024
	AllowedImageFormats       = map[string]bool{
		".jpg":  true,
		".jpeg": true,
		".png":  true,
		".gif":  true,
		".webp": true,
		".bmp":  true,
		".tiff": true,
		".svg":  true,
	}
	AllowedImageMimeTypes = map[string]bool{
		"image/jpeg":    true,
		"image/png":     true,
		"image/gif":     true,
		"image/webp":    true,
		"image/bmp":     true,
		"image/tiff":    true,
		"image/svg+xml": true,
		"image/pdf":     true,
	}
)

Functions

func NewFileFS

func NewFileFS(client *s3.Client, bucket string) fs.FS

func RandomName

func RandomName(file *multipart.FileHeader, paths ...string) (string, error)

func ValidateFile

func ValidateFile(file *multipart.FileHeader) error

func ValidateFileContent

func ValidateFileContent(content []byte) error

func ValidateThumbnailSizes added in v0.3.0

func ValidateThumbnailSizes(sizes []ThumbnailSize) error

ValidateThumbnailSizes ensures the configured derivatives are viable.

Types

type AWSProvider

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

func NewAWSProvider

func NewAWSProvider(client *s3.Client, bucket string) *AWSProvider

func (*AWSProvider) AbortChunked added in v0.3.0

func (p *AWSProvider) AbortChunked(ctx context.Context, session *ChunkSession) error

func (*AWSProvider) CompleteChunked added in v0.3.0

func (p *AWSProvider) CompleteChunked(ctx context.Context, session *ChunkSession) (*FileMeta, error)

func (*AWSProvider) CreatePresignedPost added in v0.3.0

func (p *AWSProvider) CreatePresignedPost(ctx context.Context, key string, metadata *Metadata) (*PresignedPost, error)

func (*AWSProvider) DeleteFile

func (p *AWSProvider) DeleteFile(ctx context.Context, path string) error

func (*AWSProvider) GetFile

func (p *AWSProvider) GetFile(ctx context.Context, path string) ([]byte, error)

func (*AWSProvider) GetPresignedURL

func (p *AWSProvider) GetPresignedURL(ctx context.Context, path string, ttl time.Duration) (string, error)

func (*AWSProvider) InitiateChunked added in v0.3.0

func (p *AWSProvider) InitiateChunked(ctx context.Context, session *ChunkSession) (*ChunkSession, error)

func (*AWSProvider) UploadChunk added in v0.3.0

func (p *AWSProvider) UploadChunk(ctx context.Context, session *ChunkSession, index int, payload io.Reader) (ChunkPart, error)

func (*AWSProvider) UploadFile

func (p *AWSProvider) UploadFile(ctx context.Context, path string, content []byte, opts ...UploadOption) (string, error)

func (*AWSProvider) Validate added in v0.2.0

func (p *AWSProvider) Validate(ctx context.Context) error

func (*AWSProvider) WithBasePath

func (p *AWSProvider) WithBasePath(basePath string) *AWSProvider

func (*AWSProvider) WithLogger

func (p *AWSProvider) WithLogger(logger Logger) *AWSProvider

type AsyncCallbackExecutor added in v0.3.0

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

func NewAsyncCallbackExecutor added in v0.3.0

func NewAsyncCallbackExecutor(logger Logger) *AsyncCallbackExecutor

func (*AsyncCallbackExecutor) Execute added in v0.3.0

type CallbackExecutor added in v0.3.0

type CallbackExecutor interface {
	Execute(ctx context.Context, cb UploadCallback, meta *FileMeta) error
}

type CallbackMode added in v0.3.0

type CallbackMode string

CallbackMode describes how the manager should react when post-upload callbacks fail.

const (
	// CallbackModeStrict propagates callback errors back to the caller and should trigger cleanup.
	CallbackModeStrict CallbackMode = "strict"
	// CallbackModeBestEffort logs callback failures but still reports success to the caller.
	CallbackModeBestEffort CallbackMode = "best_effort"
)

type ChunkPart added in v0.3.0

type ChunkPart struct {
	Index      int
	Size       int64
	Checksum   string
	ETag       string
	UploadedAt time.Time
}

ChunkPart captures metadata for an uploaded chunk.

type ChunkSession added in v0.3.0

type ChunkSession struct {
	ID            string
	Key           string
	TotalSize     int64
	PartSize      int64
	Metadata      *Metadata
	CreatedAt     time.Time
	ExpiresAt     time.Time
	State         ChunkSessionState
	UploadedParts map[int]ChunkPart
	ProviderData  map[string]any
}

ChunkSession keeps track of multipart upload progress and provider-specific details.

type ChunkSessionState added in v0.3.0

type ChunkSessionState string

ChunkSessionState represents the lifecycle stage of a chunked upload session.

const (
	// ChunkSessionStateActive indicates chunks may still be uploaded.
	ChunkSessionStateActive ChunkSessionState = "active"
	// ChunkSessionStateCompleted is set after the finalization step succeeds.
	ChunkSessionStateCompleted ChunkSessionState = "completed"
	// ChunkSessionStateAborted is set when the session is canceled by the client or due to errors.
	ChunkSessionStateAborted ChunkSessionState = "aborted"
)

type ChunkSessionStore added in v0.3.0

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

ChunkSessionStore is an in-memory registry backed by a RWMutex. Implementation can be swapped later.

func NewChunkSessionStore added in v0.3.0

func NewChunkSessionStore(ttl time.Duration) *ChunkSessionStore

NewChunkSessionStore creates a new store with the provided TTL (or DefaultChunkSessionTTL if <= 0).

func (*ChunkSessionStore) AddPart added in v0.3.0

func (s *ChunkSessionStore) AddPart(id string, part ChunkPart) (*ChunkSession, error)

AddPart registers a chunk part for the given session ID.

func (*ChunkSessionStore) CleanupExpired added in v0.3.0

func (s *ChunkSessionStore) CleanupExpired(now time.Time) []string

CleanupExpired removes expired sessions and returns their IDs.

func (*ChunkSessionStore) Create added in v0.3.0

func (s *ChunkSessionStore) Create(session *ChunkSession) (*ChunkSession, error)

Create registers a new chunk upload session.

func (*ChunkSessionStore) Delete added in v0.3.0

func (s *ChunkSessionStore) Delete(id string)

Delete removes a session from the store.

func (*ChunkSessionStore) Get added in v0.3.0

func (s *ChunkSessionStore) Get(id string) (*ChunkSession, bool)

Get returns a copy of the session if it exists and has not expired.

func (*ChunkSessionStore) MarkAborted added in v0.3.0

func (s *ChunkSessionStore) MarkAborted(id string) (*ChunkSession, error)

MarkAborted flags a session as aborted if it is active.

func (*ChunkSessionStore) MarkCompleted added in v0.3.0

func (s *ChunkSessionStore) MarkCompleted(id string) (*ChunkSession, error)

MarkCompleted flags a session as completed if it is active.

type ChunkedUploader added in v0.3.0

type ChunkedUploader interface {
	InitiateChunked(ctx context.Context, session *ChunkSession) (*ChunkSession, error)
	UploadChunk(ctx context.Context, session *ChunkSession, index int, payload io.Reader) (ChunkPart, error)
	CompleteChunked(ctx context.Context, session *ChunkSession) (*FileMeta, error)
	AbortChunked(ctx context.Context, session *ChunkSession) error
}

type DefaultLogger

type DefaultLogger struct{}

func (*DefaultLogger) Error

func (l *DefaultLogger) Error(msg string, args ...any)

func (*DefaultLogger) Info

func (l *DefaultLogger) Info(msg string, args ...any)

type FSProvider

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

func NewFSProvider

func NewFSProvider(base string) *FSProvider

func (*FSProvider) AbortChunked added in v0.3.0

func (p *FSProvider) AbortChunked(_ context.Context, session *ChunkSession) error

func (*FSProvider) CompleteChunked added in v0.3.0

func (p *FSProvider) CompleteChunked(_ context.Context, session *ChunkSession) (*FileMeta, error)

func (*FSProvider) CreatePresignedPost added in v0.3.0

func (p *FSProvider) CreatePresignedPost(context.Context, string, *Metadata) (*PresignedPost, error)

func (*FSProvider) DeleteFile

func (p *FSProvider) DeleteFile(ctx context.Context, path string) error

func (*FSProvider) GetFile

func (p *FSProvider) GetFile(ctx context.Context, path string) ([]byte, error)

func (*FSProvider) GetPresignedURL

func (p *FSProvider) GetPresignedURL(ctx context.Context, path string, _ time.Duration) (string, error)

func (*FSProvider) InitiateChunked added in v0.3.0

func (p *FSProvider) InitiateChunked(_ context.Context, session *ChunkSession) (*ChunkSession, error)

func (*FSProvider) UploadChunk added in v0.3.0

func (p *FSProvider) UploadChunk(_ context.Context, session *ChunkSession, index int, payload io.Reader) (ChunkPart, error)

func (*FSProvider) UploadFile

func (p *FSProvider) UploadFile(ctx context.Context, path string, content []byte, opts ...UploadOption) (string, error)

func (*FSProvider) Validate added in v0.2.0

func (p *FSProvider) Validate(ctx context.Context) error

func (*FSProvider) WithFS

func (p *FSProvider) WithFS(f fs.FS) *FSProvider

func (*FSProvider) WithLogger

func (p *FSProvider) WithLogger(l Logger) *FSProvider

func (*FSProvider) WithURLPrefix

func (p *FSProvider) WithURLPrefix(prefix string) *FSProvider

type FileMeta

type FileMeta struct {
	Content      []byte `json:"content"`
	ContentType  string `json:"content_type"`
	Name         string `json:"name"`
	OriginalName string `json:"original_name"`
	Size         int64  `json:"size"`
	URL          string `json:"url"`
}

type ImageMeta added in v0.3.0

type ImageMeta struct {
	*FileMeta
	Thumbnails map[string]*FileMeta `json:"thumbnails"`
}

type ImageProcessor added in v0.3.0

type ImageProcessor interface {
	Generate(ctx context.Context, source []byte, size ThumbnailSize, contentType string) ([]byte, string, error)
}

type LocalImageProcessor added in v0.3.0

type LocalImageProcessor struct{}

LocalImageProcessor resizes images using a simple nearest-neighbor algorithm.

func NewLocalImageProcessor added in v0.3.0

func NewLocalImageProcessor() *LocalImageProcessor

func (*LocalImageProcessor) Generate added in v0.3.0

func (p *LocalImageProcessor) Generate(ctx context.Context, source []byte, size ThumbnailSize, contentType string) ([]byte, string, error)

type Logger

type Logger interface {
	Info(msg string, args ...any)
	Error(msg string, args ...any)
}

Logger interface allows for dependency injection of logging

type Manager

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

func NewManager

func NewManager(opts ...Option) *Manager

func (*Manager) AbortChunked added in v0.3.0

func (m *Manager) AbortChunked(ctx context.Context, sessionID string) error

func (*Manager) CompleteChunked added in v0.3.0

func (m *Manager) CompleteChunked(ctx context.Context, sessionID string) (*FileMeta, error)

func (*Manager) ConfirmPresignedUpload added in v0.3.0

func (m *Manager) ConfirmPresignedUpload(ctx context.Context, result *PresignedUploadResult) (*FileMeta, error)

func (*Manager) CreatePresignedPost added in v0.3.0

func (m *Manager) CreatePresignedPost(ctx context.Context, key string, opts ...UploadOption) (*PresignedPost, error)

func (*Manager) DeleteFile

func (m *Manager) DeleteFile(ctx context.Context, path string) error

func (*Manager) GetFile

func (m *Manager) GetFile(ctx context.Context, path string) ([]byte, error)

func (*Manager) GetPresignedURL

func (m *Manager) GetPresignedURL(ctx context.Context, path string, expires time.Duration) (string, error)

func (*Manager) HandleFile

func (m *Manager) HandleFile(ctx context.Context, file *multipart.FileHeader, path string) (*FileMeta, error)

func (*Manager) HandleImageWithThumbnails added in v0.3.0

func (m *Manager) HandleImageWithThumbnails(ctx context.Context, file *multipart.FileHeader, path string, sizes []ThumbnailSize) (*ImageMeta, error)

func (*Manager) InitiateChunked added in v0.3.0

func (m *Manager) InitiateChunked(ctx context.Context, key string, totalSize int64, opts ...UploadOption) (*ChunkSession, error)

func (*Manager) UploadChunk added in v0.3.0

func (m *Manager) UploadChunk(ctx context.Context, sessionID string, index int, payload io.Reader) error

func (*Manager) UploadFile

func (m *Manager) UploadFile(ctx context.Context, path string, content []byte, opts ...UploadOption) (string, error)

func (*Manager) ValidateProvider added in v0.2.0

func (m *Manager) ValidateProvider(ctx context.Context) error

type Metadata

type Metadata struct {
	ContentType  string
	CacheControl string
	Public       bool
	TTL          time.Duration
}

type MultiProvider

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

func NewMultiProvider

func NewMultiProvider(local *FSProvider, objectStore Uploader) *MultiProvider

func (*MultiProvider) AbortChunked added in v0.3.0

func (m *MultiProvider) AbortChunked(ctx context.Context, session *ChunkSession) error

func (*MultiProvider) CompleteChunked added in v0.3.0

func (m *MultiProvider) CompleteChunked(ctx context.Context, session *ChunkSession) (*FileMeta, error)

func (*MultiProvider) CreatePresignedPost added in v0.3.0

func (m *MultiProvider) CreatePresignedPost(ctx context.Context, key string, metadata *Metadata) (*PresignedPost, error)

func (*MultiProvider) DeleteFile

func (m *MultiProvider) DeleteFile(ctx context.Context, path string) error

func (*MultiProvider) GetFile

func (m *MultiProvider) GetFile(ctx context.Context, path string) ([]byte, error)

func (*MultiProvider) GetPresignedURL

func (m *MultiProvider) GetPresignedURL(ctx context.Context, path string, expires time.Duration) (string, error)

func (*MultiProvider) InitiateChunked added in v0.3.0

func (m *MultiProvider) InitiateChunked(ctx context.Context, session *ChunkSession) (*ChunkSession, error)

func (*MultiProvider) UploadChunk added in v0.3.0

func (m *MultiProvider) UploadChunk(ctx context.Context, session *ChunkSession, index int, payload io.Reader) (ChunkPart, error)

func (*MultiProvider) UploadFile

func (m *MultiProvider) UploadFile(ctx context.Context, path string, content []byte, opts ...UploadOption) (string, error)

func (*MultiProvider) Validate added in v0.2.0

func (m *MultiProvider) Validate(ctx context.Context) error

func (*MultiProvider) WithLogger

func (p *MultiProvider) WithLogger(l Logger) *MultiProvider

type Option

type Option func(m *Manager)

func WithCallbackExecutor added in v0.3.0

func WithCallbackExecutor(exec CallbackExecutor) Option

func WithCallbackMode added in v0.3.0

func WithCallbackMode(mode CallbackMode) Option

func WithChunkPartSize added in v0.3.0

func WithChunkPartSize(size int64) Option

func WithChunkSessionStore added in v0.3.0

func WithChunkSessionStore(store *ChunkSessionStore) Option

func WithImageProcessor added in v0.3.0

func WithImageProcessor(processor ImageProcessor) Option

func WithLogger

func WithLogger(l Logger) Option

func WithOnUploadComplete added in v0.3.0

func WithOnUploadComplete(cb UploadCallback) Option

func WithProvider

func WithProvider(p Uploader) Option

func WithProviderValidationContext added in v0.2.0

func WithProviderValidationContext(ctx context.Context) Option

func WithValidator

func WithValidator(v *Validator) Option

type PresignedPost added in v0.3.0

type PresignedPost struct {
	URL    string            `json:"url"`
	Method string            `json:"method"`
	Fields map[string]string `json:"fields"`
	Expiry time.Time         `json:"expiry"`
}

type PresignedPoster added in v0.3.0

type PresignedPoster interface {
	CreatePresignedPost(ctx context.Context, key string, metadata *Metadata) (*PresignedPost, error)
}

type PresignedUploadResult added in v0.3.0

type PresignedUploadResult struct {
	Key          string
	OriginalName string
	Size         int64
	ContentType  string
	Metadata     map[string]string
}

type ProviderValidator added in v0.2.0

type ProviderValidator interface {
	Validate(context.Context) error
}

type ThumbnailSize added in v0.3.0

type ThumbnailSize struct {
	Name   string
	Width  int
	Height int
	Fit    string
}

ThumbnailSize describes a requested derivative output.

type UploadCallback added in v0.3.0

type UploadCallback func(ctx context.Context, meta *FileMeta) error

type UploadOption

type UploadOption func(*Metadata)

func WithCacheControl

func WithCacheControl(c string) UploadOption

func WithContentType

func WithContentType(t string) UploadOption

func WithPublicAccess

func WithPublicAccess(a bool) UploadOption

func WithTTL

func WithTTL(ttl time.Duration) UploadOption

type Uploader

type Uploader interface {
	UploadFile(ctx context.Context, path string, content []byte, opts ...UploadOption) (string, error)
	GetFile(ctx context.Context, path string) ([]byte, error)
	DeleteFile(ctx context.Context, path string) error
	GetPresignedURL(ctx context.Context, path string, expires time.Duration) (string, error)
}

type Validator

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

func NewValidator

func NewValidator(opts ...ValidatorOption) *Validator

func (*Validator) IsAllowedMimeType added in v0.3.0

func (u *Validator) IsAllowedMimeType(mime string) bool

func (*Validator) MaxFileSize added in v0.3.0

func (u *Validator) MaxFileSize() int64

func (*Validator) RandomName

func (u *Validator) RandomName(file *multipart.FileHeader, paths ...string) (string, error)

func (*Validator) ValidateFile

func (u *Validator) ValidateFile(file *multipart.FileHeader) error

func (*Validator) ValidateFileContent

func (u *Validator) ValidateFileContent(content []byte) error

type ValidatorOption

type ValidatorOption func(*Validator)

func WithAllowedImageFormats

func WithAllowedImageFormats(formats map[string]bool) ValidatorOption

func WithAllowedMimeTypes

func WithAllowedMimeTypes(types map[string]bool) ValidatorOption

func WithUploadMaxFileSize

func WithUploadMaxFileSize(size int64) ValidatorOption

Directories

Path Synopsis
examples
callbacks command
chunked command
presignedpost command
thumbnails command

Jump to

Keyboard shortcuts

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