middleware

package
v0.0.0-...-c2ffd79 Latest Latest
Warning

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

Go to latest
Published: Aug 18, 2025 License: MIT Imports: 23 Imported by: 0

Documentation

Overview

Package middleware provides optional CSRF protection middleware for flash. This middleware uses a double-submit cookie pattern and is suitable for APIs and web apps. Usage: app.Use(mw.CSRF(mw.CSRFConfig{...}))

Package middleware provides HTTP middleware for flash.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Buffer

func Buffer(cfgs ...BufferConfig) flash.Middleware

Buffer returns middleware that wraps the ResponseWriter with a pooled buffer to reduce syscalls and set Content-Length. Not recommended for streaming/SSE. Apply before handlers that generate bounded payloads.

func CORS

func CORS(cfg CORSConfig) flash.Middleware

CORS returns middleware that sets CORS headers and handles preflight requests according to the provided config. For OPTIONS requests, it responds with allowed methods/headers and 204 No Content.

func CSRF

func CSRF(cfgs ...CSRFConfig) flash.Middleware

CSRF returns middleware that provides CSRF protection using the double-submit cookie pattern. For unsafe methods, the token is checked in both cookie and header. For safe methods, a token is set if missing.

func Gzip

func Gzip(cfgs ...GzipConfig) flash.Middleware

Gzip returns middleware that enables gzip compression when the client sends Accept-Encoding: gzip. The compression level can be configured via GzipConfig. HEAD requests are never compressed.

func Logger

func Logger() flash.Middleware

Logger returns middleware that logs each request using slog, including method, path, status, duration, remote address, and user agent. The logger is taken from the request context or app, and can be enriched with a request ID if present.

func OTel

func OTel(serviceName string, extraAttrs ...attribute.KeyValue) flash.Middleware

OTel returns middleware that creates an OpenTelemetry server span for each request. Kept for convenience; delegates to OTelWithConfig with service name and extra attributes.

func OTelWithConfig

func OTelWithConfig(cfg OTelConfig) flash.Middleware

OTelWithConfig returns middleware that creates an OpenTelemetry server span using cfg.

func RateLimit

func RateLimit(l Limiter) flash.Middleware

RateLimit returns middleware that uses the provided Limiter to restrict requests. If the request is not allowed, responds with 429 Too Many Requests and optional Retry-After header.

func Recover

func Recover() flash.Middleware

Recover returns middleware that recovers from panics in handlers and returns a 500 Internal Server Error. This prevents panics from crashing the server and provides a generic error response.

func RequestID

func RequestID(cfgs ...RequestIDConfig) flash.Middleware

RequestID returns middleware that adds a unique request ID to each request/response. The request ID is set in the configured header and made available in the request context.

func RequestIDFromContext

func RequestIDFromContext(ctx context.Context) (string, bool)

RequestIDFromContext returns the request ID from the context, if available.

func Sessions

func Sessions(cfg SessionConfig) flash.Middleware

Sessions returns middleware that loads/saves a session around each request.

func Timeout

func Timeout(cfg TimeoutConfig) flash.Middleware

Timeout returns middleware that applies a timeout to the request context. If the handler does not complete within Duration, a 504 Gateway Timeout is returned.

func ValidatorI18n

func ValidatorI18n(cfg ValidatorI18nConfig) flash.Middleware

ValidatorI18n returns middleware that attaches a request-scoped validator message function to the request context based on a locale.

Types

type BufferConfig

type BufferConfig struct {
	InitialSize int // preallocated buffer size
	MaxSize     int // max buffer size before switching to streaming
}

BufferConfig configures the write-buffering middleware. InitialSize preallocates the response buffer. MaxSize limits buffering; if exceeded, switches to streaming.

type CORSConfig

type CORSConfig struct {
	Origins     []string // allowed origins
	Methods     []string // allowed methods
	Headers     []string // allowed headers
	Expose      []string // headers to expose
	Credentials bool     // allow credentials
	MaxAge      int      // preflight cache duration (seconds)
}

CORSConfig holds configuration for the CORS middleware. Origins, Methods, and Headers control allowed cross-origin requests. Expose lists headers exposed to the browser. Credentials enables cookies. MaxAge sets preflight cache duration (seconds).

type CSRFConfig

type CSRFConfig struct {
	CookieName     string        // Name of the CSRF cookie
	HeaderName     string        // Name of the header to check for the token
	TokenLength    int           // Length of the generated token (bytes)
	CookiePath     string        // Path for the CSRF cookie
	CookieDomain   string        // Domain for the CSRF cookie
	CookieSecure   bool          // Secure flag for the CSRF cookie
	CookieHTTPOnly bool          // HttpOnly flag for the CSRF cookie
	CookieSameSite http.SameSite // SameSite policy
	TTL            time.Duration // Cookie expiration
}

CSRFConfig configures the CSRF middleware. CookieName and HeaderName control where the token is stored and checked. TokenLength sets the length of the generated token (in bytes). Cookie* fields control cookie properties. TTL sets cookie expiration.

func DefaultCSRFConfig

func DefaultCSRFConfig() CSRFConfig

DefaultCSRFConfig returns a safe default config for CSRF protection.

type GzipConfig

type GzipConfig struct {
	Level int // gzip compression level
}

GzipConfig configures the gzip middleware. Level sets the gzip compression level (see compress/gzip). Defaults to gzip.DefaultCompression.

type Limiter

type Limiter interface {
	Allow(key string) (allowed bool, retryAfter time.Duration)
}

Limiter is a generic interface for rate limiting. Allow returns whether the request is allowed and, if not, how long to wait before retrying.

type MemoryStore

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

MemoryStore is a simple in-memory session store with TTL. Not suitable for production or multi-process deployments.

func NewMemoryStore

func NewMemoryStore() *MemoryStore

NewMemoryStore creates a new in-memory session store.

func (*MemoryStore) Delete

func (m *MemoryStore) Delete(id string) error

func (*MemoryStore) Get

func (m *MemoryStore) Get(id string) (map[string]any, bool)

func (*MemoryStore) Save

func (m *MemoryStore) Save(id string, data map[string]any, ttl time.Duration) error

type OTelConfig

type OTelConfig struct {
	// Tracer to use. If nil, otel.Tracer("github.com/goflash/flash") is used.
	Tracer trace.Tracer
	// Propagator to extract context. If nil, otel.GetTextMapPropagator() is used.
	Propagator propagation.TextMapPropagator
	// Filter returns true to skip tracing for a request (e.g., health checks).
	Filter func(*flash.Ctx) bool
	// SpanName formats the span name. If nil, defaults to "METHOD ROUTE" or "METHOD PATH".
	SpanName func(*flash.Ctx) string
	// Attributes returns additional attributes to set on the span at the end of the request.
	Attributes func(*flash.Ctx) []attribute.KeyValue
	// Status maps HTTP status and error to span status code/description. If nil, defaults to
	// Error for err!=nil or status>=500, else Ok.
	Status func(status int, err error) (codes.Code, string)
	// RecordDuration enables recording request duration in milliseconds as attribute
	// "http.server.duration_ms" (float64).
	RecordDuration bool
	// ServiceName, if set, adds attribute service.name. Prefer setting service name on Resource
	// in your TracerProvider; this is offered as a convenience.
	ServiceName string
	// ExtraAttributes are appended to span attributes.
	ExtraAttributes []attribute.KeyValue
}

OTelConfig configures the OpenTelemetry middleware. All fields are optional; sensible defaults are used when not provided.

type RequestIDConfig

type RequestIDConfig struct {
	Header string // response header name, default: X-Request-ID
}

RequestIDConfig configures the RequestID middleware. Header sets the response header name (default: X-Request-ID).

type Session

type Session struct {
	ID     string
	Values map[string]any
	// contains filtered or unexported fields
}

Session represents the per-request view of a session.

func SessionFromCtx

func SessionFromCtx(c *flash.Ctx) *Session

SessionFromCtx retrieves the Session previously loaded by Sessions middleware.

func (*Session) Delete

func (s *Session) Delete(key string)

func (*Session) Get

func (s *Session) Get(key string) (any, bool)

func (*Session) Set

func (s *Session) Set(key string, v any)

type SessionConfig

type SessionConfig struct {
	Store      Store
	TTL        time.Duration
	CookieName string
	CookiePath string
	Domain     string
	Secure     bool
	HTTPOnly   bool
	SameSite   http.SameSite
	HeaderName string // if set, read/write session id via header as well
}

SessionConfig configures the session middleware.

type SimpleIPLimiter

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

SimpleIPLimiter is a basic token bucket per-IP limiter. It limits requests per unique key (e.g., IP address) with a fixed capacity and refill interval.

func NewSimpleIPLimiter

func NewSimpleIPLimiter(capacity int, refill time.Duration) *SimpleIPLimiter

NewSimpleIPLimiter creates a new SimpleIPLimiter with the given capacity and refill interval.

func (*SimpleIPLimiter) Allow

func (l *SimpleIPLimiter) Allow(key string) (bool, time.Duration)

type Store

type Store interface {
	Get(id string) (map[string]any, bool)
	Save(id string, data map[string]any, ttl time.Duration) error
	Delete(id string) error
}

Store abstracts session persistence for the session middleware. Implementations must provide Get, Save, and Delete for session data by ID.

type TimeoutConfig

type TimeoutConfig struct {
	Duration      time.Duration          // request timeout duration
	OnTimeout     func(*flash.Ctx)       // optional callback on timeout
	ErrorResponse func(*flash.Ctx) error // optional custom error response
}

TimeoutConfig configures the timeout middleware. Duration sets the timeout. OnTimeout is called when a timeout occurs. ErrorResponse can customize the timeout response.

type ValidatorI18nConfig

type ValidatorI18nConfig struct {
	// DefaultLocale used when none is derived from the request.
	DefaultLocale string
	// LocaleFromCtx returns the desired locale for a request.
	// Default: use lowercased route param ":lang" if present.
	LocaleFromCtx func(c *flash.Ctx) string
	// MessageFuncFor returns a function that translates a FieldError into a message
	// for a given locale. The application typically closes over its prepared
	// translators and returns: func(fe validator.FieldError) string { return fe.Translate(trans) }.
	// Required.
	MessageFuncFor func(locale string) func(validator.FieldError) string
	// SetGlobal optionally sets the global fallback message function to DefaultLocale,
	// used when no per-request function was provided.
	SetGlobal bool
}

ValidatorI18nConfig configures the ValidatorI18n middleware. The application supplies how to get a message function for a given locale. No locale or translation packages are imported by the framework.

Jump to

Keyboard shortcuts

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