Module middleware

Source
Expand description

§Middleware System

Torch’s middleware system allows you to intercept and modify HTTP requests and responses as they flow through your application. Middleware can be used for logging, authentication, CORS, rate limiting, and many other cross-cutting concerns.

§How Middleware Works

Middleware forms a chain where each middleware can:

  1. Inspect and modify the incoming request
  2. Call the next middleware in the chain (or the final handler)
  3. Inspect and modify the outgoing response
  4. Short-circuit the chain by returning early

§Examples

§Basic Logging Middleware

use torch_web::{App, Request, Response, middleware::Middleware};
use std::pin::Pin;
use std::future::Future;

struct Logger;

impl Middleware for Logger {
    fn call(
        &self,
        req: Request,
        next: Box<dyn Fn(Request) -> Pin<Box<dyn Future<Output = Response> + Send + 'static>> + Send + Sync>,
    ) -> Pin<Box<dyn Future<Output = Response> + Send + 'static>> {
        Box::pin(async move {
            println!("{} {}", req.method(), req.path());
            let response = next(req).await;
            println!("Response: {}", response.status_code());
            response
        })
    }
}

let app = App::new()
    .middleware(Logger)
    .get("/", |_req| async { Response::ok().body("Hello!") });

§Function-based Middleware

use torch_web::{App, Request, Response};

let app = App::new()
    .middleware(|req: Request, next| async move {
        // Add a custom header to all responses
        let mut response = next(req).await;
        response = response.header("X-Powered-By", "Torch");
        response
    })
    .get("/", |_req| async { Response::ok().body("Hello!") });

Structs§

MiddlewareStack
Organizes middleware into a processing pipeline

Traits§

Middleware
Trait for implementing middleware components.

Functions§

cors
Built-in middleware for CORS
logger
Built-in middleware for logging requests
security_headers
Built-in middleware for adding security headers

Type Aliases§

MiddlewareFn
Type alias for middleware functions.