Attribute Macro pre_process

#[pre_process]
Expand description

Define a pre-processing middleware.

§Example

Redirect requests to paths that end with a trailing / to the equivalent path without the trailing /:

use pavex::{pre_process, http::{HeaderValue, header::LOCATION}};
use pavex::middleware::Processing;
use pavex::request::RequestHead;
use pavex::Response;

#[pre_process]
pub fn redirect_to_normalized(head: &RequestHead) -> Processing {
    let Some(normalized_path) = head.target.path().strip_suffix('/') else {
        // No need to redirect, we continue processing the request.
        return Processing::Continue;
    };
    let location = HeaderValue::from_str(normalized_path).unwrap();
    let redirect = Response::temporary_redirect().insert_header(LOCATION, location);
    // Short-circuit the request processing pipeline and return a redirect response
    Processing::EarlyReturn(redirect)
}

§Guide

Check out the “Middlewares” section of Pavex’s guide for a thorough introduction to middlewares in Pavex applications.

§Registration

Use Blueprint::pre_process to register the middleware with your Blueprint.

The #[pre_process] macro generates a constant that you can use to refer to the middleware when invoking Blueprint::pre_process.

§Arguments

The sections below provide an exhaustive list of all the arguments and flags supported by the pre_process macro:

NameKindRequired
idArgumentNo

§id

By default, Pavex generates a constant named after your function (converted to UPPER_SNAKE_CASE) that you use when registering the middleware.

The id argument allows you to customize the name of the generated constant.

§Example

Using the default generated identifier:

use pavex::{pre_process, Blueprint, middleware::Processing};

#[pre_process]
pub fn redirect_to_normalized() -> Processing {
    Processing::Continue
}

let mut bp = Blueprint::new();
bp.pre_process(REDIRECT_TO_NORMALIZED);

Using a custom identifier:

use pavex::{pre_process, Blueprint, middleware::Processing, request::RequestHead};

#[pre_process(id = "TO_NORMALIZED")]
//            👆 Custom identifier
pub fn redirect_to_normalized(head: &RequestHead) -> Processing {
    // [...]
    Processing::Continue
}

let mut bp = Blueprint::new();
// Use the custom identifier when registering
bp.pre_process(TO_NORMALIZED);