Documentation
¶
Index ¶
- Variables
- func CORSMiddleware(cfg *CORSConfig) fiber.Handler
- func CompileAllowOrigin(pattern string) *regexp.Regexp
- func DefaultMiddlewareStack(cfg *CORSConfig) []fiber.Handler
- func MethodOverrideMiddleware() fiber.Handler
- func PrometheusHandler() fiber.Handler
- func RegisterStopCallback(id string, fn func(HTTPResponse))
- func TusResumableMiddleware() fiber.Handler
- func UnregisterStopCallback(id string)
- func ValidateCORSOrigin(cfg *CORSConfig) fiber.Handler
- type CORSConfig
- type ConcatableUpload
- type ConcaterDataStore
- type Config
- type ContentServerDataStore
- type DataStore
- type FileInfo
- type FileInfoChanges
- type HTTPHeader
- type HTTPRequest
- type HTTPResponse
- type Handler
- type HookEvent
- type HookHandler
- type HookRequest
- type HookResponse
- type HookType
- type LengthDeclarableUpload
- type LengthDeferrerDataStore
- type Lock
- type Locker
- type MetaData
- type Metrics
- type ServableUpload
- type StoreComposer
- type TUSError
- type TerminatableUpload
- type TerminaterDataStore
- type UnroutedHandler
- func (h *UnroutedHandler) DelFile(c *fiber.Ctx) error
- func (h *UnroutedHandler) Extensions() string
- func (h *UnroutedHandler) GetFile(c *fiber.Ctx) error
- func (h *UnroutedHandler) HeadFile(c *fiber.Ctx) error
- func (h *UnroutedHandler) Options(c *fiber.Ctx) error
- func (h *UnroutedHandler) PatchFile(c *fiber.Ctx) error
- func (h *UnroutedHandler) PostFile(c *fiber.Ctx) error
- func (h *UnroutedHandler) PostFileV2(c *fiber.Ctx) error
- type Upload
Constants ¶
This section is empty.
Variables ¶
var ( ErrUnsupportedVersion = NewError("ERR_UNSUPPORTED_VERSION", "missing, invalid or unsupported Tus-Resumable header", http.StatusPreconditionFailed) ErrMaxSizeExceeded = NewError("ERR_MAX_SIZE_EXCEEDED", "maximum size exceeded", http.StatusRequestEntityTooLarge) ErrInvalidContentType = NewError("ERR_INVALID_CONTENT_TYPE", "missing or invalid Content-Type header", http.StatusBadRequest) ErrInvalidUploadLength = NewError("ERR_INVALID_UPLOAD_LENGTH", "missing or invalid Upload-Length header", http.StatusBadRequest) ErrInvalidOffset = NewError("ERR_INVALID_OFFSET", "missing or invalid Upload-Offset header", http.StatusBadRequest) ErrNotFound = NewError("ERR_UPLOAD_NOT_FOUND", "upload not found", http.StatusNotFound) ErrFileLocked = NewError("ERR_UPLOAD_LOCKED", "file currently locked", http.StatusLocked) ErrLockTimeout = NewError("ERR_LOCK_TIMEOUT", "failed to acquire lock before timeout", http.StatusInternalServerError) ErrMismatchOffset = NewError("ERR_MISMATCHED_OFFSET", "mismatched offset", http.StatusConflict) ErrSizeExceeded = NewError("ERR_UPLOAD_SIZE_EXCEEDED", "upload's size exceeded", http.StatusRequestEntityTooLarge) ErrNotImplemented = NewError("ERR_NOT_IMPLEMENTED", "feature not implemented", http.StatusNotImplemented) ErrUploadNotFinished = NewError("ERR_UPLOAD_NOT_FINISHED", "one of the partial uploads is not finished", http.StatusBadRequest) ErrInvalidConcat = NewError("ERR_INVALID_CONCAT", "invalid Upload-Concat header", http.StatusBadRequest) ErrConcatenationUnsupported = NewError("ERR_CONCATENATION_UNSUPPORTED", "Upload-Concat header is not supported by server", http.StatusBadRequest) ErrModifyFinal = NewError("ERR_MODIFY_FINAL", "modifying a final upload is not allowed", http.StatusForbidden) ErrUploadLengthAndUploadDeferLength = NewError("ERR_AMBIGUOUS_UPLOAD_LENGTH", "provided both Upload-Length and Upload-Defer-Length", http.StatusBadRequest) ErrInvalidUploadDeferLength = NewError("ERR_INVALID_UPLOAD_LENGTH_DEFER", "invalid Upload-Defer-Length header", http.StatusBadRequest) ErrUploadStoppedByServer = NewError("ERR_UPLOAD_STOPPED", "upload has been stopped by server", http.StatusBadRequest) ErrUploadRejectedByServer = NewError("ERR_UPLOAD_REJECTED", "upload creation has been rejected by server", http.StatusBadRequest) ErrUploadTerminationRejected = NewError("ERR_UPLOAD_TERMINATION_REJECTED", "upload termination has been rejected by server", http.StatusBadRequest) ErrUploadInterrupted = NewError("ERR_UPLOAD_INTERRUPTED", "upload has been interrupted by another request for this upload resource", http.StatusBadRequest) ErrServerShutdown = NewError("ERR_SERVER_SHUTDOWN", "request has been interrupted because the server is shutting down", http.StatusServiceUnavailable) ErrOriginNotAllowed = NewError("ERR_ORIGIN_NOT_ALLOWED", "request origin is not allowed", http.StatusForbidden) ErrUnexpectedEOF = NewError("ERR_UNEXPECTED_EOF", "server expected to receive more bytes", http.StatusBadRequest) ErrReadTimeout = NewError("ERR_READ_TIMEOUT", "timeout while reading request body", http.StatusInternalServerError) ErrConnectionReset = NewError("ERR_CONNECTION_RESET", "TCP connection reset by peer", http.StatusInternalServerError) )
Standard TUS protocol errors.
var AvailableHooks = []HookType{ HookPreCreate, HookPostCreate, HookPostReceive, HookPreTerminate, HookPostTerminate, HookPostFinish, HookPreFinish, }
AvailableHooks lists all supported hook types.
var DefaultCORSConfig = CORSConfig{ Disable: false, AllowOrigin: regexp.MustCompile(".*"), AllowCredentials: false, AllowMethods: "POST, HEAD, PATCH, OPTIONS, GET, DELETE", AllowHeaders: "Authorization, Origin, X-Requested-With, X-Request-ID, " + "X-HTTP-Method-Override, Content-Type, Upload-Length, Upload-Offset, " + "Tus-Resumable, Upload-Metadata, Upload-Defer-Length, Upload-Concat, " + "Upload-Incomplete, Upload-Complete, Upload-Draft-Interop-Version", MaxAge: "86400", ExposeHeaders: "Upload-Offset, Location, Upload-Length, Tus-Version, " + "Tus-Resumable, Tus-Max-Size, Tus-Extension, Upload-Metadata, " + "Upload-Defer-Length, Upload-Concat, Upload-Incomplete, " + "Upload-Complete, Upload-Draft-Interop-Version", }
DefaultCORSConfig is used when Config.CORS is nil.
Functions ¶
func CORSMiddleware ¶
func CORSMiddleware(cfg *CORSConfig) fiber.Handler
CORSMiddleware returns a Fiber handler that adds CORS headers and handles preflight OPTIONS requests according to the TUS protocol. If cfg is nil, the DefaultCORSConfig is used.
func CompileAllowOrigin ¶
CompileAllowOrigin compiles a regex string into a *regexp.Regexp. Useful when building config from user input.
func DefaultMiddlewareStack ¶
func DefaultMiddlewareStack(cfg *CORSConfig) []fiber.Handler
DefaultMiddlewareStack returns the standard TUS middleware chain: MethodOverride → CORS → TusResumable. You can use this if you need to compose the middleware manually.
func MethodOverrideMiddleware ¶
MethodOverrideMiddleware allows clients to override the HTTP method using the X-HTTP-Method-Override header. Required for environments that do not support PATCH / DELETE (e.g. older browsers, Flash).
func PrometheusHandler ¶ added in v1.0.2
PrometheusHandler returns a Fiber-native handler that renders Prometheus metrics in text format. No adaptor needed.
app.Get("/metrics", m.Middleware(), tusdfiber.PrometheusHandler())
func RegisterStopCallback ¶
func RegisterStopCallback(id string, fn func(HTTPResponse))
RegisterStopCallback stores a callback that can stop an upload mid-stream. The callback is invoked when a hook returns StopUpload: true.
func TusResumableMiddleware ¶
TusResumableMiddleware checks that the Tus-Resumable header is present on mutating requests (POST, PATCH, DELETE), or that Upload-Draft-Interop-Version is present if the experimental protocol is enabled. GET and HEAD are allowed without it.
func UnregisterStopCallback ¶
func UnregisterStopCallback(id string)
UnregisterStopCallback removes a previously registered stop callback.
func ValidateCORSOrigin ¶
func ValidateCORSOrigin(cfg *CORSConfig) fiber.Handler
ValidateCORSOrigin checks if the Origin header matches the allowed pattern.
Types ¶
type CORSConfig ¶
type CORSConfig struct {
// Disable skips all CORS handling.
Disable bool
// AllowOrigin is a regex that the Origin header must match.
AllowOrigin *regexp.Regexp
// AllowCredentials includes Access-Control-Allow-Credentials: true.
AllowCredentials bool
// AllowMethods is the value of Access-Control-Allow-Methods.
AllowMethods string
// AllowHeaders is the value of Access-Control-Allow-Headers.
AllowHeaders string
// MaxAge is the value of Access-Control-Max-Age.
MaxAge string
// ExposeHeaders is the value of Access-Control-Expose-Headers.
ExposeHeaders string
}
CORSConfig controls Cross-Origin Resource Sharing behaviour.
type ConcatableUpload ¶
type ConcatableUpload = tusd.ConcatableUpload
Type aliases for core tusd types.
type ConcaterDataStore ¶
type ConcaterDataStore = tusd.ConcaterDataStore
Type aliases for core tusd types.
type Config ¶
type Config struct {
// StoreComposer composes the core data store and optional extensions.
StoreComposer *StoreComposer
// MaxSize is the maximum upload size in bytes (0 = no limit).
MaxSize int64
// BasePath is the URL prefix for uploads, e.g. "/files/".
// If no trailing slash is present, one will be added.
BasePath string
// DisableDownload removes the GET / download endpoint.
DisableDownload bool
// DisableTermination removes the DELETE endpoint.
DisableTermination bool
// DisableConcatenation rejects Upload-Concat headers.
DisableConcatenation bool
// NotifyCompleteUploads enables the CompleteUploads notification channel.
NotifyCompleteUploads bool
// NotifyTerminatedUploads enables the TerminatedUploads notification channel.
NotifyTerminatedUploads bool
// NotifyUploadProgress enables the UploadProgress notification channel.
NotifyUploadProgress bool
// NotifyCreatedUploads enables the CreatedUploads notification channel.
NotifyCreatedUploads bool
// UploadProgressInterval controls how often progress notifications are emitted.
UploadProgressInterval time.Duration
// RespectForwardedHeaders makes the handler read X-Forwarded-* / Forwarded headers.
RespectForwardedHeaders bool
// PreUploadCreateCallback is called before a new upload is created.
// Return an error to reject the upload.
PreUploadCreateCallback func(hook HookEvent) (HTTPResponse, FileInfoChanges, error)
// PreFinishResponseCallback is called after an upload is completed.
PreFinishResponseCallback func(hook HookEvent) (HTTPResponse, error)
// PreUploadTerminateCallback is called before an upload is terminated.
PreUploadTerminateCallback func(hook HookEvent) (HTTPResponse, error)
// GracefulRequestCompletionTimeout is the time given to stores after a request ends.
GracefulRequestCompletionTimeout time.Duration
// AcquireLockTimeout is the maximum time to wait for an upload lock.
AcquireLockTimeout time.Duration
// NetworkTimeout is the read deadline for individual body reads.
NetworkTimeout time.Duration
// EnableExperimentalProtocol enables the IETF resumable upload draft
// (Upload-Draft-Interop-Version) next to the TUS v1 protocol.
EnableExperimentalProtocol bool
// CORS configuration. If nil, DefaultCORSConfig is used.
CORS *CORSConfig
// contains filtered or unexported fields
}
Config configures the TUS handler for Fiber.
type ContentServerDataStore ¶
type ContentServerDataStore = tusd.ContentServerDataStore
Type aliases for core tusd types.
type FileInfoChanges ¶
type FileInfoChanges = tusd.FileInfoChanges
Type aliases for core tusd types.
type HTTPHeader ¶
type HTTPHeader = tusd.HTTPHeader
All HTTP types are aliased from tusd for full compatibility.
type HTTPRequest ¶
type HTTPRequest = tusd.HTTPRequest
All HTTP types are aliased from tusd for full compatibility.
type HTTPResponse ¶
type HTTPResponse = tusd.HTTPResponse
All HTTP types are aliased from tusd for full compatibility.
type Handler ¶
type Handler struct {
*UnroutedHandler
// contains filtered or unexported fields
}
Handler wraps an UnroutedHandler with Fiber-native route registration. Create one via NewHandler, then call Register() or use Middleware().
func NewHandler ¶
NewHandler creates a TUS Handler that auto-registers all TUS protocol routes on a Fiber router when you call Register().
func NewHandlerWithHooks ¶
func NewHandlerWithHooks(cfg Config, hookHandler HookHandler, enabledHooks []HookType) (*Handler, error)
NewHandlerWithHooks creates a TUS Fiber handler whose callbacks and notification channels are wired to invoke the given HookHandler. It accepts the same Config as NewHandler.
This lets you use tusd's file hooks, HTTP hooks, gRPC hooks, or plugin hooks.
Example (file hooks):
hookHandler := &filehook.FileHook{Directory: "./hooks"}
handler, err := tusdfiber.NewHandlerWithHooks(config, hookHandler, tusdfiber.AvailableHooks)
func (*Handler) Middleware ¶
Middleware returns a Fiber handler that routes TUS requests internally. It is a convenience for cases where you want to mount it on a sub-router:
sub := app.Group("/files")
sub.Use("/", handler.Middleware())
type HookEvent ¶
type HookEvent struct {
Upload FileInfo
HTTPRequest HTTPRequest
}
HookEvent is an event from tusd that can be handled by the application.
type HookHandler ¶
type HookHandler = tusdhooks.HookHandler
Re-export tusd hook types for convenience.
type HookRequest ¶
type HookRequest = tusdhooks.HookRequest
Re-export tusd hook types for convenience.
type HookResponse ¶
type HookResponse = tusdhooks.HookResponse
Re-export tusd hook types for convenience.
type HookType ¶
Re-export tusd hook types for convenience.
const ( HookPostFinish HookType = "post-finish" HookPostTerminate HookType = "post-terminate" HookPostReceive HookType = "post-receive" HookPostCreate HookType = "post-create" HookPreCreate HookType = "pre-create" HookPreFinish HookType = "pre-finish" HookPreTerminate HookType = "pre-terminate" )
Standard hook types.
type LengthDeclarableUpload ¶
type LengthDeclarableUpload = tusd.LengthDeclarableUpload
Type aliases for core tusd types.
type LengthDeferrerDataStore ¶
type LengthDeferrerDataStore = tusd.LengthDeferrerDataStore
Type aliases for core tusd types.
type Metrics ¶
type Metrics struct {
UploadsCreated prometheus.Counter
UploadsFinished prometheus.Counter
UploadsTerminated prometheus.Counter
BytesReceived prometheus.Counter
ErrorsTotal *prometheus.CounterVec
RequestsTotal *prometheus.CounterVec
ActiveUploads prometheus.Gauge
}
Metrics holds Prometheus collectors for TUS operations.
func NewMetrics ¶
func NewMetrics(reg prometheus.Registerer) *Metrics
NewMetrics registers and returns TUS metrics with the given Prometheus registerer.
func (*Metrics) Middleware ¶
Middleware returns a Fiber handler that counts requests and active uploads.
type StoreComposer ¶
type StoreComposer struct {
*tusd.StoreComposer
}
StoreComposer is a thin wrapper around tusd's StoreComposer. It composes core data stores with optional extensions (locker, terminator, etc.).
func NewStoreComposer ¶
func NewStoreComposer() *StoreComposer
NewStoreComposer creates a fresh StoreComposer.
func (*StoreComposer) Capabilities ¶
func (sc *StoreComposer) Capabilities() string
Capabilities returns a human-readable string of supported extensions.
type TUSError ¶
type TUSError struct {
Code string
Message string
HTTPResponse HTTPResponse
}
TUSError represents a TUS protocol error with an associated HTTP status code.
type TerminatableUpload ¶
type TerminatableUpload = tusd.TerminatableUpload
Type aliases for core tusd types.
type TerminaterDataStore ¶
type TerminaterDataStore = tusd.TerminaterDataStore
Type aliases for core tusd types.
type UnroutedHandler ¶
type UnroutedHandler struct {
// Notification channels (mirror tusd's interface)
CompleteUploads chan HookEvent
TerminatedUploads chan HookEvent
UploadProgress chan HookEvent
CreatedUploads chan HookEvent
// contains filtered or unexported fields
}
UnroutedHandler provides TUS protocol methods (PostFile, HeadFile, PatchFile, …) that you can wire into any router. Use NewUnroutedHandler to create one.
func NewUnroutedHandler ¶
func NewUnroutedHandler(config Config) (*UnroutedHandler, error)
NewUnroutedHandler creates an UnroutedHandler with the given config.
func (*UnroutedHandler) DelFile ¶
func (h *UnroutedHandler) DelFile(c *fiber.Ctx) error
DelFile terminates an upload.
func (*UnroutedHandler) Extensions ¶
func (h *UnroutedHandler) Extensions() string
Extensions returns a comma-separated list of supported tus extensions.
func (*UnroutedHandler) GetFile ¶
func (h *UnroutedHandler) GetFile(c *fiber.Ctx) error
GetFile serves the uploaded content for download.
func (*UnroutedHandler) HeadFile ¶
func (h *UnroutedHandler) HeadFile(c *fiber.Ctx) error
HeadFile returns the upload offset and metadata.
func (*UnroutedHandler) Options ¶
func (h *UnroutedHandler) Options(c *fiber.Ctx) error
Options handles OPTIONS requests for protocol discovery.
func (*UnroutedHandler) PatchFile ¶
func (h *UnroutedHandler) PatchFile(c *fiber.Ctx) error
PatchFile appends a chunk to an upload.
func (*UnroutedHandler) PostFile ¶
func (h *UnroutedHandler) PostFile(c *fiber.Ctx) error
PostFile creates a new upload resource.
func (*UnroutedHandler) PostFileV2 ¶
func (h *UnroutedHandler) PostFileV2(c *fiber.Ctx) error
PostFileV2 creates an upload using the IETF resumable upload draft protocol.