Skip to content

middleware #

Constants #

const request_id_header = 'X-Request-ID'
const request_id_key = 'request_id'

fn build_from_interfaces #

fn build_from_interfaces(middlewares []IMiddleware, handler http.HandlerFunc) http.HandlerFunc

build_from_interfaces wraps a handler with struct-based middleware chain Middleware is applied in order so first middleware executes first CRITICAL FIX (v0.2.1): Execute middleware chain at RUNTIME to avoid closure capture bugs

fn csrf_field_html #

fn csrf_field_html(token string) string

Template helper for CSRF token in forms

fn csrf_meta_html #

fn csrf_meta_html(token string) string

Template helper for CSRF meta tag

fn new_auth #

fn new_auth(database &vareldb.DB) AuthMiddleware

new_auth creates authentication middleware

fn new_auth_with_urls #

fn new_auth_with_urls(database &vareldb.DB, login_url string, redirect_url string) AuthMiddleware

new_auth_with_urls creates authentication middleware with custom URLs

fn new_compression_middleware #

fn new_compression_middleware(config CompressionConfig) &CompressionMiddleware

new_compression_middleware creates a new compression middleware

fn new_cors_middleware #

fn new_cors_middleware(config CORSConfig) &CORSMiddleware

new_cors_middleware creates a new CORS middleware

fn new_csrf_middleware #

fn new_csrf_middleware(config CSRFConfig) &CSRFMiddleware

new_csrf_middleware creates a new CSRF protection middleware

fn new_health_middleware #

fn new_health_middleware(config HealthCheckConfig) &HealthMiddleware

new_health_middleware creates a new health check middleware

fn new_logger_middleware #

fn new_logger_middleware(config LoggerConfig) &LoggerMiddleware

new_logger_middleware creates a new logging middleware

fn new_method_override_middleware #

fn new_method_override_middleware(config MethodOverrideConfig) &MethodOverrideMiddleware

new_method_override_middleware creates a new method override middleware

fn new_rate_limit_middleware #

fn new_rate_limit_middleware(config RateLimitConfig) &RateLimitMiddleware

new_rate_limit_middleware creates a new rate limit middleware

fn new_recovery_middleware #

fn new_recovery_middleware(config RecoveryConfig) &RecoveryMiddleware

new_recovery_middleware creates a new recovery middleware

fn new_request_id_middleware #

fn new_request_id_middleware(config RequestIDConfig) &RequestIDMiddleware

new_request_id_middleware creates a new request ID middleware

fn new_session_middleware #

fn new_session_middleware(config session.Config, mut db database.DB) !&SessionMiddleware

new_session_middleware creates PostgreSQL-backed session middleware (v0.3.0) This is called ONCE during server initialization

fn session_middleware #

fn session_middleware(config session.Config, mut db database.DB) !&SessionMiddleware

session_middleware is a convenience wrapper for new_session_middleware Provides consistent API with other middleware constructors

interface IMiddleware #

interface IMiddleware {
mut:
	// handle processes the request through this middleware
	// Returns the response from either this middleware or the next handler
	handle(mut ctx http.Context, next http.HandlerFunc) http.Response
}

IMiddleware is the interface all struct-based middleware must implement (v0.2.0+) This replaces the closure-based Middleware type to eliminate concurrent map cloning issues

Note: Methods use mut receiver to allow middleware to maintain internal mutable state (e.g., session stores with crypto state, rate limiters with counters)

fn (RateLimiter) cleanup_old_buckets #

fn (mut limiter RateLimiter) cleanup_old_buckets(max_idle time.Duration)

cleanup_old_buckets removes inactive buckets (call periodically)

struct AuthMiddleware #

struct AuthMiddleware {
	db           &vareldb.DB
	login_url    string = '/login'
	redirect_url string = '/dashboard'
}

AuthMiddleware configuration

struct CORSConfig #

struct CORSConfig {
pub:
	allowed_origins   []string = ['*']
	allowed_methods   []string = ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS', 'PATCH']
	allowed_headers   []string = ['*']
	exposed_headers   []string
	max_age           int = 3600
	allow_credentials bool
}

struct CORSMiddleware #

struct CORSMiddleware {
	config CORSConfig
}

CORSMiddleware handles Cross-Origin Resource Sharing headers Stateless middleware (no mutable state), but follows struct pattern for consistency

fn (CORSMiddleware) handle #

fn (mut mw CORSMiddleware) handle(mut ctx http.Context, next http.HandlerFunc) http.Response

handle implements IMiddleware.handle - adds CORS headers

struct CSRFConfig #

struct CSRFConfig {
pub:
	secret           string // Secret key for token generation (required)
	cookie_name      string = '_csrf'
	form_field_name  string = '_csrf_token'
	header_name      string = 'X-CSRF-Token'
	cookie_path      string = '/'
	cookie_domain    string
	cookie_max_age   int      = 86400 // 24 hours
	cookie_secure    bool     = true  // Require HTTPS
	cookie_http_only bool     = true
	cookie_same_site string   = 'Strict' // 'Strict', 'Lax', or 'None'
	safe_methods     []string = ['GET', 'HEAD', 'OPTIONS', 'TRACE']
	error_message    string   = 'CSRF token validation failed'
}

CSRFConfig configures CSRF protection

struct CSRFMiddleware #

struct CSRFMiddleware {
	config CSRFConfig
}

CSRFMiddleware handles CSRF (Cross-Site Request Forgery) protection Stateless middleware (no mutable state), but follows struct pattern for consistency

fn (CSRFMiddleware) handle #

fn (mut mw CSRFMiddleware) handle(mut ctx http.Context, next http.HandlerFunc) http.Response

handle implements IMiddleware.handle - protects against CSRF attacks

struct CompressionConfig #

struct CompressionConfig {
pub:
	level              int      = 6    // Compression level 1-9 (6 = default balance)
	min_size           int      = 1024 // Only compress responses >= 1KB
	compressible_types []string = [
	'text/html',
	'text/css',
	'text/plain',
	'text/javascript',
	'application/javascript',
	'application/json',
	'application/xml',
	'text/xml',
	'application/x-javascript',
]
	exclude_paths      []string // Paths to skip compression
}

CompressionConfig configures response compression

struct CompressionMiddleware #

struct CompressionMiddleware {
	config CompressionConfig
}

CompressionMiddleware handles response compression (gzip) Stateless middleware (no mutable state), but follows struct pattern for consistency

fn (CompressionMiddleware) handle #

fn (mut mw CompressionMiddleware) handle(mut ctx http.Context, next http.HandlerFunc) http.Response

handle implements IMiddleware.handle - compresses HTTP responses

struct DoubleSubmitConfig #

struct DoubleSubmitConfig {
pub:
	cookie_name     string   = '_csrf'
	header_name     string   = 'X-CSRF-Token'
	form_field_name string   = '_csrf_token'
	cookie_path     string   = '/'
	cookie_max_age  int      = 86400
	safe_methods    []string = ['GET', 'HEAD', 'OPTIONS', 'TRACE']
}

Double Submit Cookie pattern (alternative to signed tokens)

struct HealthCheckConfig #

struct HealthCheckConfig {
pub:
	health_path string = '/health' // Liveness probe path
	ready_path  string = '/ready'  // Readiness probe path
	// Custom readiness check function (return true if ready)
	readiness_check fn () bool = default_readiness_check
}

HealthCheckConfig configures health check behavior

struct HealthMiddleware #

struct HealthMiddleware {
	config HealthCheckConfig
}

HealthMiddleware handles health check endpoints for monitoring Stateless middleware (no mutable state), but follows struct pattern for consistency

fn (HealthMiddleware) handle #

fn (mut mw HealthMiddleware) handle(mut ctx http.Context, next http.HandlerFunc) http.Response

handle implements IMiddleware.handle - handles /health and /ready endpoints

struct LoggerConfig #

struct LoggerConfig {
pub:
	format      string = 'combined' // 'combined', 'common', 'dev'
	skip_paths  []string // Paths to skip logging
	time_format string = '2006-01-02 15:04:05'
}

struct LoggerMiddleware #

struct LoggerMiddleware {
	config LoggerConfig
}

LoggerMiddleware handles HTTP request logging Stateless middleware (no mutable state), but follows struct pattern for consistency

fn (LoggerMiddleware) handle #

fn (mut mw LoggerMiddleware) handle(mut ctx http.Context, next http.HandlerFunc) http.Response

handle implements IMiddleware.handle - logs each request

struct MethodOverrideConfig #

struct MethodOverrideConfig {
pub:
	// List of HTTP methods allowed for override (default: PUT, PATCH, DELETE)
	allowed_methods []string = ['PUT', 'PATCH', 'DELETE']

	// Form parameter name to check (default: _method)
	param_name string = '_method'

	// HTTP header name to check (default: X-HTTP-Method-Override)
	header_name string = 'X-HTTP-Method-Override'
}

MethodOverrideConfig configures the method override middleware

struct MethodOverrideMiddleware #

struct MethodOverrideMiddleware {
	config MethodOverrideConfig
}

MethodOverrideMiddleware allows HTML forms to simulate PUT, PATCH, DELETE Stateless middleware (no mutable state), but follows struct pattern for consistency

fn (MethodOverrideMiddleware) handle #

fn (mut mw MethodOverrideMiddleware) handle(mut ctx http.Context, next http.HandlerFunc) http.Response

handle implements IMiddleware.handle - overrides HTTP method for HTML forms

struct RateLimitConfig #

struct RateLimitConfig {
pub:
	requests_per_window int                          = 100              // Number of requests allowed
	window_duration     time.Duration                = time.minute      // Time window
	key_func            fn (mut http.Context) string = default_key_func // Function to extract rate limit key
	skip_successful     bool // Only count failed requests
	message             string = 'Rate limit exceeded. Please try again later.'
}

RateLimitConfig configures rate limiting behavior

struct RateLimitMiddleware #

struct RateLimitMiddleware {
mut:
	limiter RateLimiter
}

RateLimitMiddleware handles request rate limiting using token bucket algorithm STATEFUL middleware - maintains mutable buckets map across requests

fn (RateLimitMiddleware) handle #

fn (mut mw RateLimitMiddleware) handle(mut ctx http.Context, next http.HandlerFunc) http.Response

handle implements IMiddleware.handle - rate limits requests by key

fn (RateLimitMiddleware) cleanup_old_buckets #

fn (mut mw RateLimitMiddleware) cleanup_old_buckets(max_idle time.Duration)

cleanup_old_buckets removes inactive buckets (call periodically if needed)

struct RecoveryConfig #

struct RecoveryConfig {
pub:
	print_stack    bool = true
	development    bool
	custom_handler ?fn (mut http.Context, string) http.Response
}

struct RecoveryMiddleware #

struct RecoveryMiddleware {
	config RecoveryConfig
}

RecoveryMiddleware handles panic recovery and error handling Stateless middleware (no mutable state), but follows struct pattern for consistency

fn (RecoveryMiddleware) handle #

fn (mut mw RecoveryMiddleware) handle(mut ctx http.Context, next http.HandlerFunc) http.Response

handle implements IMiddleware.handle - recovers from errors/panics

struct RequestIDConfig #

struct RequestIDConfig {
pub:
	header    string = request_id_header
	generator ?fn () string
}

struct RequestIDMiddleware #

struct RequestIDMiddleware {
	config RequestIDConfig
}

RequestIDMiddleware adds unique request IDs for tracking Stateless middleware (no mutable state), but follows struct pattern for consistency

fn (RequestIDMiddleware) handle #

fn (mut mw RequestIDMiddleware) handle(mut ctx http.Context, next http.HandlerFunc) http.Response

handle implements IMiddleware.handle - adds unique request ID

struct SessionMiddleware #

struct SessionMiddleware {
mut:
	store  &session.PostgresStore // Database store (PostgreSQL)
	config session.Config
}

SessionMiddleware handles PostgreSQL-backed session management (v0.3.0) Sessions stored in PostgreSQL with JSONB data column Only session ID stored in cookie (HttpOnly, Secure)

fn (SessionMiddleware) handle #

fn (mut mw SessionMiddleware) handle(mut ctx http.Context, next http.HandlerFunc) http.Response

handle implements IMiddleware.handle - processes each request