Overview
Middleware in ALOS wraps handlers to add pre/post processing. The signature is:
type MiddlewareFunc func(HandlerFunc) HandlerFunc
Apply middleware globally with Use() or per-group:
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:
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:
s.Router.Use(core.Logger())
CORS
ALOS provides a runtime-swappable CORS engine. Configure origins, methods, and headers:
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:
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:
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: nosniffX-Frame-Options: DENYX-XSS-Protection: 1; mode=blockStrict-Transport-Security: max-age=63072000; includeSubDomains; preloadReferrer-Policy: strict-origin-when-cross-origin
Compression
Automatically compress responses with gzip or deflate based on Accept-Encoding:
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.
s.Router.Use(core.Cache(core.CacheConfig{ TTL: 60 * time.Second, Gzip: true, IgnoreQuery: false, }))
Configuration Options
| Option | Type | Description |
|---|---|---|
TTL | time.Duration | How long an entry stays cached. Default 60s. |
Methods | []string | Which methods to cache. Default ["GET"]; set e.g. ["GET","HEAD"] for more. |
IgnoreQuery | bool | When true the query string is left out of the cache key, so /p?a=1 and /p?a=2 share one entry. Default false. |
Gzip | bool | Store a gzip copy and serve it to clients sending Accept-Encoding: gzip (with Content-Encoding and Vary). Compressed once on the miss. Default false. |
GzipMinBytes | int | Minimum body size to gzip. Default 512. |
GzipLevel | int | gzip level 1-9. Default 6. |
MaxEntries | int | Maximum number of cached entries; the oldest are evicted beyond this. Default 10000. |
MaxBodyBytes | int | Responses with a body larger than this are not cached. Default 1 MiB. |
SweepInterval | time.Duration | How often expired entries are swept out. Default 15s. |
CacheableStatus | func(int) bool | Predicate choosing which status codes are cacheable. Default caches 200 only. |
Cache GET only, share entries across query strings, and keep pre-gzipped copies:
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:
s.Router.Use(core.Timeout(5 * time.Second))
Apply different timeouts per route group:
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:
s.Router.Use(core.BodyLimit(10 * 1024 * 1024))
Different limits per group:
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:
readOnly := s.Router.Group("/public", core.AllowMethods("GET", "HEAD"), ) readOnly.GET("/info", infoHandler) readOnly.GET("/status", statusHandler)
Combine with other middleware:
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:
s.Router.Use(core.BasicAuth(core.BasicAuthConfig{ Users: map[string]string{ "admin": "supersecret", "readonly": "viewonly", }, Realm: "Admin Panel", }))
Protect only specific groups:
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:
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:
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) })
Header
Injects a static response header on every request:
s.Router.Use(core.Header("X-Powered-By", "ALOS")) s.Router.Use(core.Header("X-Version", "1.0.0"))
Stack multiple headers:
api := s.Router.Group("/api", core.Header("X-API-Version", "v2"), core.Header("Cache-Control", "no-store"), )
Conditional (If)
Apply middleware only when a predicate function returns true. The inner middleware is skipped entirely when the predicate is false:
s.Router.Use(core.If( func(req *core.Request) bool { return req.Path != "/health" }, core.Logger(), ))
Skip auth for public routes:
s.Router.Use(core.If( func(req *core.Request) bool { return req.Header("Authorization") != "" }, AuthRequired(), ))
Compress only JSON responses:
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:
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).
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:
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
api := s.Router.Group("/api") api.Use(core.RateLimitMiddleware(core.RateLimitMiddlewareConfig{ MaxRequests: 100, Window: time.Minute, }))
Per-Route Rate Limit
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:
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:
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
api := s.Router.Group("/api", core.JWT(core.JWTConfig{ Secret: []byte("my-secret-key"), }))
Accessing Claims in a Handler
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
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:
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
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
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:
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
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
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:
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
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()) } } }