Skip to main content

ferro_rs/middleware/
mod.rs

1//! Middleware system for Ferro framework
2//!
3//! This module provides Laravel 12.x-style middleware support with:
4//! - Global middleware (runs on all routes)
5//! - Route group middleware (shared for a group of routes)
6//! - Per-route middleware (applied to individual routes)
7//! - Rate limiting middleware for API protection
8//!
9//! # Example
10//!
11//! ```rust,ignore
12//! use ferro_rs::{async_trait, Middleware, Next, Request, Response, HttpResponse};
13//!
14//! pub struct AuthMiddleware;
15//!
16//! #[async_trait]
17//! impl Middleware for AuthMiddleware {
18//!     async fn handle(&self, request: Request, next: Next) -> Response {
19//!         if request.header("Authorization").is_none() {
20//!             return Err(HttpResponse::text("Unauthorized").status(401));
21//!         }
22//!         next(request).await
23//!     }
24//! }
25//! ```
26//!
27//! # Rate Limiting
28//!
29//! ```rust,ignore
30//! use ferro::middleware::{RateLimiter, Limit, Throttle};
31//!
32//! // Register named limiter
33//! RateLimiter::define("api", |req| Limit::per_minute(60));
34//!
35//! // Apply to routes
36//! get!("/api/users", handler).middleware(Throttle::named("api"))
37//!
38//! // Inline limit
39//! get!("/health", handler).middleware(Throttle::per_minute(120))
40//! ```
41
42mod chain;
43mod cors;
44mod metrics;
45mod pre_route_registry;
46mod rate_limit;
47mod registry;
48mod security_headers;
49
50pub use cors::Cors;
51pub use metrics::MetricsMiddleware;
52pub use security_headers::SecurityHeaders;
53
54pub use chain::MiddlewareChain;
55pub use pre_route_registry::{
56    get_pre_route_middleware, register_pre_route_middleware, BoxedPreRouteMiddleware,
57    PreRouteMiddleware,
58};
59pub use rate_limit::{Limit, LimiterResponse, RateLimiter, Throttle};
60pub use registry::get_global_middleware_info;
61pub use registry::register_global_middleware;
62pub use registry::MiddlewareRegistry;
63
64use crate::http::{Request, Response};
65use async_trait::async_trait;
66use std::future::Future;
67use std::pin::Pin;
68use std::sync::Arc;
69
70/// Type alias for the boxed future returned by middleware
71pub type MiddlewareFuture = Pin<Box<dyn Future<Output = Response> + Send>>;
72
73/// Type alias for the next handler in the middleware chain
74///
75/// Call `next(request).await` to pass control to the next middleware or the route handler.
76pub type Next = Arc<dyn Fn(Request) -> MiddlewareFuture + Send + Sync>;
77
78/// Type alias for boxed middleware handlers (internal use)
79pub type BoxedMiddleware = Arc<dyn Fn(Request, Next) -> MiddlewareFuture + Send + Sync>;
80
81/// Trait for implementing middleware
82///
83/// Middleware can inspect/modify requests, short-circuit responses, or pass control
84/// to the next middleware in the chain by calling `next(request).await`.
85///
86/// # Example
87///
88/// ```rust,ignore
89/// use ferro_rs::{async_trait, Middleware, Next, Request, Response, HttpResponse};
90///
91/// pub struct LoggingMiddleware;
92///
93/// #[async_trait]
94/// impl Middleware for LoggingMiddleware {
95///     async fn handle(&self, request: Request, next: Next) -> Response {
96///         println!("--> {} {}", request.method(), request.path());
97///         let response = next(request).await;
98///         println!("<-- complete");
99///         response
100///     }
101/// }
102/// ```
103#[async_trait]
104pub trait Middleware: Send + Sync {
105    /// Handle the request
106    ///
107    /// - Call `next(request).await` to pass control to the next middleware
108    /// - Return `Err(HttpResponse)` to short-circuit and respond immediately
109    /// - Modify the response after calling `next()` for post-processing
110    async fn handle(&self, request: Request, next: Next) -> Response;
111}
112
113/// Convert a Middleware trait object into a BoxedMiddleware
114pub fn into_boxed<M: Middleware + 'static>(middleware: M) -> BoxedMiddleware {
115    let middleware = Arc::new(middleware);
116    Arc::new(move |req, next| {
117        let mw = middleware.clone();
118        Box::pin(async move { mw.handle(req, next).await })
119    })
120}