Skip to main content

ResponseInterceptor

Trait ResponseInterceptor 

Source
pub trait ResponseInterceptor: Send + Sync {
    // Required method
    fn intercept<'a>(
        &'a self,
        ctx: &'a ResponseInterceptorContext<'a>,
        response: Response,
    ) -> BoxFuture<'a, Response>;

    // Provided method
    fn name(&self) -> &'static str { ... }
}
Expand description

A response interceptor that processes responses after handler execution.

Unlike the full Middleware trait, ResponseInterceptor only handles the post-handler phase, making it simpler to implement for response-only processing like:

  • Adding timing headers
  • Transforming response bodies
  • Adding debug information
  • Logging response details

§Example

use fastapi_core::middleware::{ResponseInterceptor, ResponseInterceptorContext};

struct TimingInterceptor {
    start_time: Instant,
}

impl ResponseInterceptor for TimingInterceptor {
    fn intercept(&self, ctx: &ResponseInterceptorContext, response: Response) -> Response {
        let elapsed = self.start_time.elapsed();
        response.header("X-Response-Time", format!("{}ms", elapsed.as_millis()).into_bytes())
    }
}

Required Methods§

Source

fn intercept<'a>( &'a self, ctx: &'a ResponseInterceptorContext<'a>, response: Response, ) -> BoxFuture<'a, Response>

Process a response after the handler has executed.

§Parameters
  • ctx: Context containing request information and timing data
  • response: The response from the handler or previous interceptors
§Returns

The modified response to pass to the next interceptor or return to client.

Provided Methods§

Source

fn name(&self) -> &'static str

Returns the interceptor name for debugging and logging.

Implementors§