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 metrics;
44mod pre_route_registry;
45mod rate_limit;
46mod registry;
47mod security_headers;
48
49pub use metrics::MetricsMiddleware;
50pub use security_headers::SecurityHeaders;
51
52pub use chain::MiddlewareChain;
53pub use pre_route_registry::{
54    get_pre_route_middleware, register_pre_route_middleware, BoxedPreRouteMiddleware,
55    PreRouteMiddleware,
56};
57pub use rate_limit::{Limit, LimiterResponse, RateLimiter, Throttle};
58pub use registry::get_global_middleware_info;
59pub use registry::register_global_middleware;
60pub use registry::MiddlewareRegistry;
61
62use crate::http::{Request, Response};
63use async_trait::async_trait;
64use std::future::Future;
65use std::pin::Pin;
66use std::sync::Arc;
67
68/// Type alias for the boxed future returned by middleware
69pub type MiddlewareFuture = Pin<Box<dyn Future<Output = Response> + Send>>;
70
71/// Type alias for the next handler in the middleware chain
72///
73/// Call `next(request).await` to pass control to the next middleware or the route handler.
74pub type Next = Arc<dyn Fn(Request) -> MiddlewareFuture + Send + Sync>;
75
76/// Type alias for boxed middleware handlers (internal use)
77pub type BoxedMiddleware = Arc<dyn Fn(Request, Next) -> MiddlewareFuture + Send + Sync>;
78
79/// Trait for implementing middleware
80///
81/// Middleware can inspect/modify requests, short-circuit responses, or pass control
82/// to the next middleware in the chain by calling `next(request).await`.
83///
84/// # Example
85///
86/// ```rust,ignore
87/// use ferro_rs::{async_trait, Middleware, Next, Request, Response, HttpResponse};
88///
89/// pub struct LoggingMiddleware;
90///
91/// #[async_trait]
92/// impl Middleware for LoggingMiddleware {
93///     async fn handle(&self, request: Request, next: Next) -> Response {
94///         println!("--> {} {}", request.method(), request.path());
95///         let response = next(request).await;
96///         println!("<-- complete");
97///         response
98///     }
99/// }
100/// ```
101#[async_trait]
102pub trait Middleware: Send + Sync {
103    /// Handle the request
104    ///
105    /// - Call `next(request).await` to pass control to the next middleware
106    /// - Return `Err(HttpResponse)` to short-circuit and respond immediately
107    /// - Modify the response after calling `next()` for post-processing
108    async fn handle(&self, request: Request, next: Next) -> Response;
109}
110
111/// Convert a Middleware trait object into a BoxedMiddleware
112pub fn into_boxed<M: Middleware + 'static>(middleware: M) -> BoxedMiddleware {
113    let middleware = Arc::new(middleware);
114    Arc::new(move |req, next| {
115        let mw = middleware.clone();
116        Box::pin(async move { mw.handle(req, next).await })
117    })
118}