Middleware

Production-ready middleware for CORS, compression, security headers, logging, panic recovery, and more.

Overview

Middleware in ALOS wraps handlers to add pre/post processing. The signature is:

go
type MiddlewareFunc func(HandlerFunc) HandlerFunc

Apply middleware globally with Use() or per-group:

go
s.Router.Use(core.Recovery())
s.Router.Use(core.Logger())

api := s.Router.Group("/api", core.RequestID())

s.Router.Build()

Middleware executes in the order registered. The chain is pre-computed at build time for zero per-request overhead.

Built-in Middleware

Recovery

Catches panics and returns 500 with stack trace logging.

Logger

Logs method, path, status code, and response time.

CORS

Cross-origin resource sharing with hot-reload config.

Security Headers

HSTS, X-Frame-Options, XSS protection, CSP referrer.

Compress

gzip/deflate response compression with min-size threshold.

Response Cache

In-memory GET response cache with TTL, gzip-once, and bounded eviction.

Real IP

Extracts client IP from X-Forwarded-For / X-Real-IP.

Request ID

Adds a unique X-Request-ID header to every request.

Timeout

Aborts handlers after a deadline and returns 504.

Body Limit

Rejects request bodies exceeding a byte threshold (413).

Allow Methods

Restricts routes to specific HTTP methods (405).

Basic Auth

HTTP Basic Authentication with constant-time comparison.

Header

Injects a static response header on every request.

If (Conditional)

Apply middleware only when a predicate returns true.

Rate Limiting

Per-route token bucket rate limiting with custom key functions.

JWT Auth

HMAC-SHA256 JWT validation with zero external dependencies.

Sessions

Cookie-based sessions with pluggable store and auto-cleanup.

CSRF Protection

Double-submit cookie pattern with constant-time validation.

Recovery

Catches panics in handlers and returns a 500 Internal Server Error instead of crashing the server:

go
s.Router.Use(core.Recovery())

s.Router.GET("/panic", func(req *core.Request, resp *core.Response) {
    panic("something went wrong")
})

Always register Recovery() first. It must wrap all other middleware to catch panics from any layer in the chain.

Logger

Logs each request with method, path, status code, and duration:

go
s.Router.Use(core.Logger())

CORS

ALOS provides a runtime-swappable CORS engine. Configure origins, methods, and headers:

go
s.SetCORS(core.CORSConfig{
    AllowOrigins:     []string{"https://app.example.com", "https://admin.example.com"},
    AllowMethods:     []string{"GET", "POST", "PUT", "DELETE"},
    AllowHeaders:     []string{"Content-Type", "Authorization"},
    ExposeHeaders:    []string{"X-Request-ID"},
    AllowCredentials: true,
    MaxAge:           3600,
})

s.Router.Use(s.CORS.Middleware())

Hot-Reload CORS

Update CORS configuration at runtime without restarting. Uses lock-free atomic snapshots:

go
s.CORS.Update(core.CORSConfig{
    AllowOrigins: []string{"*"},
    AllowMethods: []string{"GET"},
})

Configuration Options

Option Type Description
AllowOrigins []string Allowed origins. Use "*" for all.
AllowMethods []string Allowed HTTP methods.
AllowHeaders []string Allowed request headers.
ExposeHeaders []string Headers visible to the browser.
AllowCredentials bool Allow cookies/auth headers.
MaxAge int Preflight cache duration (seconds).

Security Headers

Add essential security headers to all responses:

go
s.Router.Use(core.SecurityHeaders(core.DefaultSecurityHeaders()))

s.Router.Use(core.SecurityHeaders(core.SecurityHeadersConfig{
    ContentTypeNosniff: true,
    XFrameOptions:      "DENY",
    XSSProtection:      true,
    HSTSMaxAge:         63072000,
    HSTSSubdomains:     true,
    HSTSPreload:        true,
    ReferrerPolicy:     "strict-origin-when-cross-origin",
}))

This adds the following headers to every response:

  • X-Content-Type-Options: nosniff
  • X-Frame-Options: DENY
  • X-XSS-Protection: 1; mode=block
  • Strict-Transport-Security: max-age=63072000; includeSubDomains; preload
  • Referrer-Policy: strict-origin-when-cross-origin

Compression

Automatically compress responses with gzip or deflate based on Accept-Encoding:

go
s.Router.Use(core.Compress(core.CompressConfig{
    Level:   6,
    MinSize: 512,
}))

Responses below MinSize bytes are sent uncompressed to avoid overhead on small payloads.

Response Cache

Caches successful GET responses in memory and serves later identical requests straight from the cache without invoking the handler. When gzip is enabled the compressed copy is built once and reused, so a body is only ever compressed a single time. The store is backed by lock-free ALOS typed maps and is bounded so it cannot grow without limit under load.

go
s.Router.Use(core.Cache(core.CacheConfig{
    TTL:         60 * time.Second,
    Gzip:        true,
    IgnoreQuery: false,
}))

Configuration Options

OptionTypeDescription
TTLtime.DurationHow long an entry stays cached. Default 60s.
Methods[]stringWhich methods to cache. Default ["GET"]; set e.g. ["GET","HEAD"] for more.
IgnoreQueryboolWhen true the query string is left out of the cache key, so /p?a=1 and /p?a=2 share one entry. Default false.
GzipboolStore a gzip copy and serve it to clients sending Accept-Encoding: gzip (with Content-Encoding and Vary). Compressed once on the miss. Default false.
GzipMinBytesintMinimum body size to gzip. Default 512.
GzipLevelintgzip level 1-9. Default 6.
MaxEntriesintMaximum number of cached entries; the oldest are evicted beyond this. Default 10000.
MaxBodyBytesintResponses with a body larger than this are not cached. Default 1 MiB.
SweepIntervaltime.DurationHow often expired entries are swept out. Default 15s.
CacheableStatusfunc(int) boolPredicate choosing which status codes are cacheable. Default caches 200 only.

Cache GET only, share entries across query strings, and keep pre-gzipped copies:

go
s.Router.Use(core.Cache(core.CacheConfig{
    TTL:         5 * time.Minute,
    Methods:     []string{"GET"},
    IgnoreQuery: true,
    Gzip:        true,
    MaxEntries:  50000,
}))

A response is never cached when it sets Cache-Control: no-store, no-cache or private, carries a Set-Cookie header, is already content-encoded, is streamed, or is larger than MaxBodyBytes. The cache is bounded by MaxEntries + MaxBodyBytes plus a TTL sweep, so it cannot become an unbounded memory sink under load.

Timeout

Aborts handler execution after a deadline and returns 504 Gateway Timeout:

go
s.Router.Use(core.Timeout(5 * time.Second))

Apply different timeouts per route group:

go
api := s.Router.Group("/api", core.Timeout(10 * time.Second))
uploads := s.Router.Group("/upload", core.Timeout(60 * time.Second))

Timeout applies to the total handler execution time, not to request reading or response writing.

Body Limit

Rejects requests with bodies larger than the specified byte limit with 413 Payload Too Large:

go
s.Router.Use(core.BodyLimit(10 * 1024 * 1024))

Different limits per group:

go
api := s.Router.Group("/api", core.BodyLimit(1 * 1024 * 1024))
uploads := s.Router.Group("/upload", core.BodyLimit(100 * 1024 * 1024))

Allow Methods

Restricts a route group to specific HTTP methods. Returns 405 Method Not Allowed for anything else:

go
readOnly := s.Router.Group("/public",
    core.AllowMethods("GET", "HEAD"),
)

readOnly.GET("/info", infoHandler)
readOnly.GET("/status", statusHandler)

Combine with other middleware:

go
admin := s.Router.Group("/admin",
    core.AllowMethods("GET", "POST"),
    core.BasicAuth(core.BasicAuthConfig{
        Users: map[string]string{"admin": "secret"},
    }),
)

Basic Auth

HTTP Basic Authentication. Uses constant-time password comparison to prevent timing attacks. Returns 401 with WWW-Authenticate header on failure:

go
s.Router.Use(core.BasicAuth(core.BasicAuthConfig{
    Users: map[string]string{
        "admin":     "supersecret",
        "readonly":  "viewonly",
    },
    Realm: "Admin Panel",
}))

Protect only specific groups:

go
admin := s.Router.Group("/admin", core.BasicAuth(core.BasicAuthConfig{
    Users: map[string]string{"admin": "password"},
    Realm: "Admin",
}))

admin.GET("/dashboard", dashboardHandler)
admin.POST("/settings", settingsHandler)
Field Type Description
Users map[string]string Username to password pairs
Realm string Realm shown in the browser prompt

Real IP

When behind a reverse proxy, extract the real client IP from proxy headers:

go
s.Router.Use(core.RealIP())

s.Router.GET("/ip", func(req *core.Request, resp *core.Response) {
    resp.String(req.RemoteAddr)
})

Checks X-Forwarded-For and X-Real-IP headers (in that order). Pass trusted proxy CIDRs (e.g. core.RealIP("10.0.0.0/8")) to honor the headers only from those peers. To apply the same client-IP resolution server-wide without adding middleware, set ProxyMode: true in the server Config. It rewrites RemoteAddr at ingress so rate limiting, logging, and handlers all see the real client.

Request ID

Adds a unique X-Request-ID header to every request for distributed tracing:

go
s.Router.Use(core.RequestID())

s.Router.GET("/debug", func(req *core.Request, resp *core.Response) {
    id := req.Header("X-Request-ID")
    resp.String(id)
})

Conditional (If)

Apply middleware only when a predicate function returns true. The inner middleware is skipped entirely when the predicate is false:

go
s.Router.Use(core.If(
    func(req *core.Request) bool {
        return req.Path != "/health"
    },
    core.Logger(),
))

Skip auth for public routes:

go
s.Router.Use(core.If(
    func(req *core.Request) bool {
        return req.Header("Authorization") != ""
    },
    AuthRequired(),
))

Compress only JSON responses:

go
s.Router.Use(core.If(
    func(req *core.Request) bool {
        return req.Header("Accept") == "application/json"
    },
    core.Compress(core.CompressConfig{Level: 6, MinSize: 256}),
))

Chain Helper

Compose a handler with specific middleware without registering them globally. Useful for per-route middleware:

go
s.Router.GET("/admin/stats", core.Chain(
    statsHandler,
    AuthRequired(),
    core.Timeout(5 * time.Second),
))

This applies AuthRequired and Timeout only to the /admin/stats route, without affecting other routes. The middleware is applied in the order listed (outermost first).

go
s.Router.POST("/upload", core.Chain(
    uploadHandler,
    core.BodyLimit(50 * 1024 * 1024),
    core.Timeout(120 * time.Second),
))

s.Router.GET("/metrics", core.Chain(
    metricsHandler,
    core.BasicAuth(core.BasicAuthConfig{
        Users: map[string]string{"ops": "secret"},
    }),
))

Per-Route Rate Limiting

Apply independent rate limiters to specific route groups or individual routes. Each call to RateLimitMiddleware creates its own counter state, so different routes track limits separately:

go
func RateLimitMiddleware(cfg RateLimitMiddlewareConfig) MiddlewareFunc

Configuration

Field Type Description
MaxRequests int64 Maximum requests allowed per window
Window time.Duration Sliding window duration
KeyFunc func(*Request) string Extracts the rate limit key from the request. Defaults to client IP from RemoteAddr.

When a client exceeds the limit, the middleware returns 429 Too Many Requests with a Retry-After header indicating when the window resets. A background goroutine cleans up expired entries every 60 seconds.

Per-Group Rate Limit

go
api := s.Router.Group("/api")
api.Use(core.RateLimitMiddleware(core.RateLimitMiddlewareConfig{
    MaxRequests: 100,
    Window:      time.Minute,
}))

Per-Route Rate Limit

go
s.Router.GET("/login", core.Chain(loginHandler,
    core.RateLimitMiddleware(core.RateLimitMiddlewareConfig{
        MaxRequests: 5,
        Window:      time.Minute,
    }),
))

Custom Key Function

Rate limit by API key instead of IP address:

go
api.Use(core.RateLimitMiddleware(core.RateLimitMiddlewareConfig{
    MaxRequests: 1000,
    Window:      time.Hour,
    KeyFunc: func(req *core.Request) string {
        return req.Header("X-API-Key")
    },
}))

Each call to RateLimitMiddleware creates an independent limiter with its own counter map. Applying it to two different groups means each group tracks limits separately.

JWT Authentication

Validate HMAC-SHA256 JSON Web Tokens with zero external dependencies. Parses the token, verifies the signature, checks expiration, and stores claims in the request store:

go
func JWT(cfg JWTConfig) MiddlewareFunc

Configuration

Field Type Default Description
Secret []byte HMAC-SHA256 signing secret (required)
ContextKey string "jwt_claims" Key used to store claims in the request store
TokenLookup string "header:Authorization" Where to extract the token from. Formats: "header:Authorization", "query:token"

The middleware reads the token from the Authorization: Bearer <token> header by default. If the exp claim is present, it validates that the token has not expired. On success, claims are stored via req.Set(contextKey, claims).

Protecting API Routes

go
api := s.Router.Group("/api", core.JWT(core.JWTConfig{
    Secret: []byte("my-secret-key"),
}))

Accessing Claims in a Handler

go
api.GET("/profile", func(req *core.Request, resp *core.Response) {
    claims := core.JWTClaims(req)
    userID := claims["sub"].(string)
    resp.JSON([]byte(`{"user":"` + userID + `"}`))
})

Token from Query Parameter

go
ws := s.Router.Group("/ws", core.JWT(core.JWTConfig{
    Secret:      []byte("my-secret-key"),
    TokenLookup: "query:token",
}))

Use core.JWTClaims(req) as a convenience helper to retrieve map[string]any claims from the request store without manual type assertion.

Sessions

Cookie-based session management with a pluggable store interface. Ships with an in-memory store that includes automatic cleanup of expired sessions:

go
func Sessions(cfg SessionConfig) MiddlewareFunc

Configuration

Field Type Default Description
CookieName string "alos_session" Name of the session cookie
MaxAge int 86400 Session lifetime in seconds (24 hours)
Secure bool false Send cookie only over HTTPS
HttpOnly bool true Prevent JavaScript access to the cookie
SameSite SameSite SameSite cookie attribute
Path string "/" Cookie path scope
Store SessionStore Storage backend (use NewMemorySessionStore() for built-in)

SessionStore Interface

go
type SessionStore interface {
    Get(id string) (map[string]any, bool)
    Save(id string, data map[string]any, maxAge int)
    Delete(id string)
}

Session Methods

Method Returns Description
Get(key) (any, bool) Retrieve a value by key
GetString(key) string Retrieve a string value (empty string if missing)
Set(key, value) Store a key-value pair
Delete(key) Remove a key from the session
Clear() Remove all keys from the session
ID() string Returns the session ID (32 random bytes, hex-encoded)

Login Flow Example

go
s.Router.Use(core.Sessions(core.SessionConfig{
    Store:    core.NewMemorySessionStore(),
    MaxAge:   3600,
    Secure:   true,
    HttpOnly: true,
}))

s.Router.POST("/login", func(req *core.Request, resp *core.Response) {
    sess := core.GetSession(req)
    sess.Set("user_id", "12345")
    sess.Set("role", "admin")
    resp.JSON([]byte(`{"status":"logged in"}`))
})

s.Router.GET("/dashboard", func(req *core.Request, resp *core.Response) {
    sess := core.GetSession(req)
    userID := sess.GetString("user_id")
    if userID == "" {
        resp.Status(401).JSON([]byte(`{"error":"not logged in"}`))
        return
    }
    resp.JSON([]byte(`{"user":"` + userID + `"}`))
})

Use core.GetSession(req) to retrieve the *Session from any handler. Session IDs are 32 random bytes (64 hex characters) generated via crypto/rand.

CSRF Protection

Prevents cross-site request forgery using the double-submit cookie pattern. A unique token is generated on the first request and stored in a cookie. Unsafe methods (POST, PUT, PATCH, DELETE) are validated by comparing the cookie token against a header or form field value using constant-time comparison:

go
func CSRF(cfg CSRFConfig) MiddlewareFunc

Configuration

Field Type Default Description
TokenLength int 32 Length of the random token in bytes
CookieName string "csrf_token" Name of the CSRF cookie
HeaderName string "X-CSRF-Token" Header checked for the token on unsafe methods
FormField string "csrf_token" Form field checked for the token on unsafe methods
Secure bool false Send cookie only over HTTPS
SameSite SameSite SameSite cookie attribute
MaxAge int 43200 Token lifetime in seconds (12 hours)
ErrorHandler func(*Request, *Response) Custom handler for CSRF validation failures (defaults to 403)

Protecting Form Submissions

go
s.Router.Use(core.CSRF(core.CSRFConfig{
    Secure: true,
}))

s.Router.GET("/form", func(req *core.Request, resp *core.Response) {
    token := core.CSRFToken(req)
    resp.HTML(`<form method="POST" action="/submit">` +
        `<input type="hidden" name="csrf_token" value="` + token + `">` +
        `<button type="submit">Send</button></form>`)
})

s.Router.POST("/submit", func(req *core.Request, resp *core.Response) {
    resp.JSON([]byte(`{"status":"ok"}`))
})

AJAX with CSRF Header

go
api := s.Router.Group("/api", core.CSRF(core.CSRFConfig{
    Secure: true,
}))

api.GET("/csrf-token", func(req *core.Request, resp *core.Response) {
    token := core.CSRFToken(req)
    resp.JSON([]byte(`{"token":"` + token + `"}`))
})

Use core.CSRFToken(req) to retrieve the current CSRF token for embedding in HTML forms or returning to JavaScript clients via an API endpoint. The token is validated from either the X-CSRF-Token header or the csrf_token form field.

Custom Middleware

Write your own middleware by returning a function that wraps the next handler:

go
func AuthRequired() core.MiddlewareFunc {
    return func(next core.HandlerFunc) core.HandlerFunc {
        return func(req *core.Request, resp *core.Response) {
            token := req.Header("Authorization")
            if token == "" {
                resp.Status(401).JSON([]byte(`{"error":"unauthorized"}`))
                return
            }

            next(req, resp)
        }
    }
}

api := s.Router.Group("/api", AuthRequired())

Timing Middleware Example

go
func Timer() core.MiddlewareFunc {
    return func(next core.HandlerFunc) core.HandlerFunc {
        return func(req *core.Request, resp *core.Response) {
            start := time.Now()
            next(req, resp)
            elapsed := time.Since(start)
            resp.SetHeader("X-Response-Time", elapsed.String())
        }
    }
}