Skip to main content

Module middleware

Module middleware 

Source
Expand description

Composable middleware pipeline.

Middleware is a single layer that wraps request dispatch. Implement it to add cross-cutting behaviour — logging, authentication, rate limiting, header injection — without editing the inner application.

WithMiddleware stacks one or more middleware layers around any Application. Layers run in registration order on the way in and in reverse order on the way out.

§Example

use rust_web_server::middleware::{Middleware, WithMiddleware};
use rust_web_server::application::Application;
use rust_web_server::request::Request;
use rust_web_server::response::Response;
use rust_web_server::server::ConnectionInfo;
use rust_web_server::app::App;
use rust_web_server::core::New;

pub struct LoggingMiddleware;

impl Middleware for LoggingMiddleware {
    fn handle(
        &self,
        request: &Request,
        connection: &ConnectionInfo,
        next: &dyn Application,
    ) -> Result<Response, String> {
        println!("{} {}", request.method, request.request_uri);
        let response = next.execute(request, connection)?;
        println!("  → {}", response.status_code);
        Ok(response)
    }
}

let app = WithMiddleware::new(App::new())
    .wrap(LoggingMiddleware);

Structs§

RateLimitLayer
Built-in middleware that enforces the process-wide rate limit (configured via RWS_CONFIG_RATE_LIMIT_MAX_REQUESTS and RWS_CONFIG_RATE_LIMIT_WINDOW_SECS).
WithMiddleware
An Application that applies a stack of Middleware layers before dispatching to an inner application.

Traits§

Middleware
A single middleware layer.