middleware

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Jan 17, 2026 License: MIT Imports: 25 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func BodyLimit

func BodyLimit(maxBytes int64) bebo.Middleware

BodyLimit caps the request body size.

func CORS

func CORS(options CORSOptions) bebo.Middleware

CORS enables cross-origin requests.

func CSRF

func CSRF(options CSRFOptions) bebo.Middleware

CSRF protects against cross-site request forgery using a double-submit cookie.

func CSRFToken

func CSRFToken(ctx *bebo.Context) string

CSRFToken returns the request CSRF token.

func CacheControl

func CacheControl(value string) bebo.Middleware

CacheControl sets a Cache-Control header on responses.

func ETag

func ETag(options ETagOptions) bebo.Middleware

ETag adds ETag handling for buffered responses.

func Gzip

func Gzip(level int) bebo.Middleware

Gzip compresses responses when supported by the client.

func IPFilter

func IPFilter(options IPFilterOptions) (bebo.Middleware, error)

IPFilter blocks or allows requests based on IP allow/deny lists.

func JWT

func JWT(options JWTOptions) bebo.Middleware

JWT validates bearer tokens using the JWT authenticator.

func Logger

func Logger() bebo.Middleware

Logger logs request/response details.

func LoggerWith

func LoggerWith(fields ...LogField) bebo.Middleware

LoggerWith logs request/response details using custom fields.

func LoggerWithOptions

func LoggerWithOptions(options LoggerOptions) bebo.Middleware

LoggerWithOptions logs requests using the provided options.

func MethodOverride

func MethodOverride(options MethodOverrideOptions) bebo.PreMiddleware

MethodOverride enables HTML form method overrides via header or _method field.

func Metrics

func Metrics(registry *metrics.Registry) bebo.Middleware

Metrics records request metrics into the registry.

func MetricsWithOptions

func MetricsWithOptions(options MetricsOptions) bebo.Middleware

MetricsWithOptions records request metrics with options.

func RateLimit

func RateLimit(limiter *Limiter, options ...RateLimitOption) bebo.Middleware

RateLimit enforces a token bucket rate limit.

func RateLimitWith

func RateLimitWith(allow AllowFunc, options ...RateLimitOption) bebo.Middleware

RateLimitWith enforces a rate limit using a custom allow function.

func Recover

func Recover() bebo.Middleware

Recover converts panics into internal errors.

func RequestContext

func RequestContext() bebo.Middleware

RequestContext stores request metadata in the request context.

func RequestID

func RequestID() bebo.Middleware

RequestID ensures a request id header is present.

func RequireAuth

func RequireAuth(auth bebo.Authenticator, options ...AuthOption) bebo.Middleware

RequireAuth ensures a request is authenticated.

func RequireAuthorization

func RequireAuthorization(auth bebo.Authenticator, authorizer bebo.Authorizer, options ...AuthOption) bebo.Middleware

RequireAuthorization ensures a request is authenticated and authorized.

func RequireJWT

func RequireJWT(authenticator auth.JWTAuthenticator, options ...AuthOption) bebo.Middleware

RequireJWT validates bearer tokens using the JWT authenticator.

func SecurityHeaders

func SecurityHeaders(options SecurityHeadersOptions) bebo.Middleware

SecurityHeaders adds common security headers.

func Session

func Session(store session.Store, options ...SessionOption) bebo.Middleware

Session loads a session and stores it on the request context.

func SessionFromContext

func SessionFromContext(ctx *bebo.Context) (*session.Session, bool)

SessionFromContext returns the loaded session.

func SetSession

func SetSession(ctx *bebo.Context, sess *session.Session)

SetSession stores a session in context for downstream handlers.

func Timeout

func Timeout(duration time.Duration) bebo.Middleware

Timeout enforces a request timeout.

func Trace

func Trace(tracer Tracer) bebo.Middleware

Trace records request spans using the provided tracer.

func TraceWithOptions

func TraceWithOptions(options TraceOptions) bebo.Middleware

TraceWithOptions records request spans with options.

Types

type AllowFunc

type AllowFunc func(*bebo.Context, string) (bool, error)

AllowFunc evaluates whether a request should proceed.

type AuthOption

type AuthOption func(*authConfig)

AuthOption customizes auth middleware behavior.

func AuthForbiddenMessage

func AuthForbiddenMessage(message string) AuthOption

AuthForbiddenMessage sets the forbidden message.

func AuthUnauthorizedMessage

func AuthUnauthorizedMessage(message string) AuthOption

AuthUnauthorizedMessage sets the unauthorized message.

type CORSOptions

type CORSOptions struct {
	AllowedOrigins   []string
	AllowedMethods   []string
	AllowedHeaders   []string
	ExposedHeaders   []string
	AllowCredentials bool
	MaxAge           time.Duration
}

CORSOptions configures CORS behavior.

type CSRFOptions

type CSRFOptions struct {
	DisableDefaults bool
	CookieName      string
	HeaderName      string
	FormField       string
	CookiePath      string
	CookieSecure    bool
	CookieHTTPOnly  bool
	CookieSameSite  http.SameSite
	TokenLength     int
	Rotate          bool
}

CSRFOptions configures CSRF behavior.

type ETagOptions

type ETagOptions struct {
	MaxSize int64
	Weak    bool
}

ETagOptions configures ETag behavior.

type ErrorHandler

type ErrorHandler func(*bebo.Context, error) error

ErrorHandler handles rate limiter errors.

type IPFilterOptions

type IPFilterOptions struct {
	Allow        []string
	Deny         []string
	UseForwarded bool
}

IPFilterOptions configures IP allow/deny rules.

type JWTOptions

type JWTOptions struct {
	Authenticator       auth.JWTAuthenticator
	Authorizer          bebo.Authorizer
	UnauthorizedMessage string
	ForbiddenMessage    string
}

JWTOptions configures JWT auth middleware.

type KeyFunc

type KeyFunc func(*bebo.Context) string

KeyFunc extracts a rate limiting key from the request.

type LimitHandler

type LimitHandler func(*bebo.Context) error

LimitHandler handles rate limit violations.

type Limiter

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

Limiter enforces a token-bucket rate limit.

func NewLimiter

func NewLimiter(rate float64, burst int, options ...LimiterOption) *Limiter

NewLimiter creates a limiter with tokens per second and burst.

func (*Limiter) Allow

func (l *Limiter) Allow(key string) bool

Allow reports whether the key can proceed.

type LimiterOption

type LimiterOption func(*Limiter)

LimiterOption customizes the limiter.

func LimiterTTL

func LimiterTTL(ttl time.Duration) LimiterOption

LimiterTTL evicts idle buckets after the duration.

type LogField

type LogField func(*bebo.Context, *responseRecorder, time.Duration) slog.Attr

LogField builds a structured log attribute.

func DefaultLogFields

func DefaultLogFields() []LogField

DefaultLogFields returns the standard access log fields.

func LogBytes

func LogBytes() LogField

LogBytes logs response size in bytes.

func LogDuration

func LogDuration() LogField

LogDuration logs request latency.

func LogMethod

func LogMethod() LogField

LogMethod logs the HTTP method.

func LogPath

func LogPath() LogField

LogPath logs the request path.

func LogQuery

func LogQuery() LogField

LogQuery logs the raw query string.

func LogRemoteAddr

func LogRemoteAddr() LogField

LogRemoteAddr logs the client IP.

func LogRequestBytes

func LogRequestBytes() LogField

LogRequestBytes logs request size in bytes (from Content-Length when provided).

func LogRequestID

func LogRequestID() LogField

LogRequestID logs the request id.

func LogSpanID

func LogSpanID() LogField

LogSpanID logs the span id from the traceparent header.

func LogStatus

func LogStatus() LogField

LogStatus logs the response status.

func LogTraceID

func LogTraceID() LogField

LogTraceID logs the trace id from the traceparent header.

func LogUserAgent

func LogUserAgent() LogField

LogUserAgent logs the user agent.

type LoggerOptions

type LoggerOptions struct {
	Fields     []LogField
	Message    string
	SkipPaths  []string
	ErrorLevel bool
	Sampler    Sampler
	SampleRate float64
}

LoggerOptions configures access logging.

func DefaultLoggerOptions

func DefaultLoggerOptions() LoggerOptions

DefaultLoggerOptions returns default logging options.

type MethodOverrideOptions

type MethodOverrideOptions struct {
	DisableDefaults bool
	HeaderName      string
	FormField       string
	AllowedMethods  []string
}

MethodOverrideOptions configures form method overrides.

type MetricsOptions

type MetricsOptions struct {
	Registry  *metrics.Registry
	SkipPaths []string
}

MetricsOptions configures metrics recording.

func DefaultMetricsOptions

func DefaultMetricsOptions(registry *metrics.Registry) MetricsOptions

DefaultMetricsOptions returns default metrics options.

type RateLimitOption

type RateLimitOption func(*rateLimitConfig)

RateLimitOption customizes rate limit middleware behavior.

func RateLimitFailOpen

func RateLimitFailOpen(enabled bool) RateLimitOption

RateLimitFailOpen allows requests when the limiter errors.

func RateLimitHandler

func RateLimitHandler(fn LimitHandler) RateLimitOption

RateLimitHandler sets the handler for limited requests.

func RateLimitKey

func RateLimitKey(fn KeyFunc) RateLimitOption

RateLimitKey sets the key function.

func RateLimitOnError

func RateLimitOnError(fn ErrorHandler) RateLimitOption

RateLimitOnError sets the handler for limiter errors.

func RateLimitRetryAfter

func RateLimitRetryAfter(duration time.Duration) RateLimitOption

RateLimitRetryAfter sets the Retry-After header duration.

type RateLimitPolicies

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

RateLimitPolicies applies rate limits per route.

func NewRateLimitPolicies

func NewRateLimitPolicies(policies []RateLimitPolicy) (*RateLimitPolicies, error)

NewRateLimitPolicies builds a route policy matcher.

func (*RateLimitPolicies) Middleware

func (p *RateLimitPolicies) Middleware(options ...RateLimitOption) bebo.Middleware

Middleware returns a middleware that enforces the policies.

type RateLimitPolicy

type RateLimitPolicy struct {
	Method string
	Host   string
	Path   string
	Allow  AllowFunc
}

RateLimitPolicy maps a route to an allow function.

type RedisLimiter

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

RedisLimiter enforces a token bucket rate limit in Redis.

func NewRedisLimiter

func NewRedisLimiter(rate float64, burst int, options RedisLimiterOptions) *RedisLimiter

NewRedisLimiter creates a Redis-backed limiter.

func (*RedisLimiter) Allow

func (l *RedisLimiter) Allow(ctx context.Context, key string) (bool, error)

Allow evaluates a token bucket rate limit for a key.

func (*RedisLimiter) AllowKey

func (l *RedisLimiter) AllowKey(key string) (bool, error)

AllowKey evaluates a token bucket rate limit for a key without a context.

type RedisLimiterOptions

type RedisLimiterOptions struct {
	DisableDefaults bool
	Network         string
	Address         string
	Username        string
	Password        string
	DB              int
	Prefix          string
	TTL             time.Duration
	DialTimeout     time.Duration
	ReadTimeout     time.Duration
	WriteTimeout    time.Duration
	Now             func() time.Time
}

RedisLimiterOptions configures a Redis-backed limiter.

type Sampler

type Sampler func(*bebo.Context) bool

Sampler decides whether to sample a request.

func SampleRate

func SampleRate(rate float64) Sampler

SampleRate returns a sampler that samples a percentage of requests.

type SecurityHeadersOptions

type SecurityHeadersOptions struct {
	DisableDefaults           bool
	ContentTypeNosniff        bool
	FrameOptions              string
	ReferrerPolicy            string
	ContentSecurityPolicy     string
	PermissionsPolicy         string
	StrictTransportSecurity   string
	CrossOriginOpenerPolicy   string
	CrossOriginEmbedderPolicy string
	CrossOriginResourcePolicy string
}

SecurityHeadersOptions configures security response headers.

func DefaultSecurityHeaders

func DefaultSecurityHeaders() SecurityHeadersOptions

DefaultSecurityHeaders returns the default header settings.

type SessionOption

type SessionOption func(*sessionConfig)

SessionOption customizes session middleware behavior.

func SessionClearInvalid

func SessionClearInvalid(enabled bool) SessionOption

SessionClearInvalid clears invalid session cookies when enabled.

type TraceOptions

type TraceOptions struct {
	Tracer     Tracer
	SkipPaths  []string
	Sampler    Sampler
	SampleRate float64
}

TraceOptions configures tracing middleware.

func DefaultTraceOptions

func DefaultTraceOptions(tracer Tracer) TraceOptions

DefaultTraceOptions returns default tracing options.

type Tracer

type Tracer interface {
	Start(*bebo.Context) (context.Context, func(status int, err error))
}

Tracer starts spans for incoming requests.

Jump to

Keyboard shortcuts

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