pub struct RequestIdMiddleware { /* private fields */ }Expand description
Middleware that adds unique request IDs to requests and responses.
This middleware:
- Checks for an existing X-Request-ID header from the client
- If present and valid, uses it; otherwise generates a new ID
- Stores the ID in request extensions for handlers to access
- Adds the ID to response headers
§Example
ⓘ
use fastapi_core::middleware::RequestIdMiddleware;
let mut stack = MiddlewareStack::new();
stack.push(RequestIdMiddleware::new());
// In your handler:
async fn handler(ctx: &RequestContext, req: &Request) -> Response {
if let Some(request_id) = req.get_extension::<RequestId>() {
println!("Request ID: {}", request_id);
}
Response::ok()
}Implementations§
Source§impl RequestIdMiddleware
impl RequestIdMiddleware
Sourcepub fn new() -> RequestIdMiddleware
pub fn new() -> RequestIdMiddleware
Creates a new request ID middleware with default configuration.
Examples found in repository?
examples/getting_started.rs (line 77)
34fn main() {
35 println!("Getting Started Guide - Code Validation\n");
36
37 // === Basic App Example ===
38 println!("1. Basic app with two routes:");
39 let app = App::builder()
40 .get("/", hello)
41 .get("/health", health)
42 .build();
43
44 println!(" Routes: {}", app.route_count());
45 let client = TestClient::new(app);
46
47 let response = client.get("/").send();
48 println!(
49 " GET / -> {} ({})",
50 response.status().as_u16(),
51 response.text()
52 );
53 if !check_eq(response.status().as_u16(), 200, "GET / should return 200") {
54 return;
55 }
56 if !check_eq(response.text(), "Hello, World!", "GET / should return body") {
57 return;
58 }
59
60 let response = client.get("/health").send();
61 println!(
62 " GET /health -> {} ({})",
63 response.status().as_u16(),
64 response.text()
65 );
66 if !check_eq(
67 response.status().as_u16(),
68 200,
69 "GET /health should return 200",
70 ) {
71 return;
72 }
73
74 // === App with Middleware ===
75 println!("\n2. App with middleware:");
76 let app = App::builder()
77 .middleware(RequestIdMiddleware::new())
78 .middleware(SecurityHeaders::new())
79 .get("/", hello)
80 .build();
81
82 let client = TestClient::new(app);
83 let response = client.get("/").send();
84 println!(" GET / -> {}", response.status().as_u16());
85 if !check_eq(
86 response.status().as_u16(),
87 200,
88 "GET / with middleware should return 200",
89 ) {
90 return;
91 }
92
93 // === App with Configuration ===
94 println!("\n3. App with configuration:");
95 let config = AppConfig::new()
96 .name("My API")
97 .version("1.0.0")
98 .debug(true)
99 .max_body_size(10 * 1024 * 1024)
100 .request_timeout_ms(30_000);
101
102 let app = App::builder().config(config).get("/", hello).build();
103
104 println!(" App name: {}", app.config().name);
105 println!(" Version: {}", app.config().version);
106 if !check_eq(
107 app.config().name.as_str(),
108 "My API",
109 "Config name should match",
110 ) {
111 return;
112 }
113 if !check_eq(
114 app.config().version.as_str(),
115 "1.0.0",
116 "Config version should match",
117 ) {
118 return;
119 }
120
121 // === 404 for unknown routes ===
122 println!("\n4. 404 for unknown routes:");
123 let app = App::builder().get("/", hello).build();
124
125 let client = TestClient::new(app);
126 let response = client.get("/nonexistent").send();
127 println!(" GET /nonexistent -> {}", response.status().as_u16());
128 if !check_eq(
129 response.status().as_u16(),
130 404,
131 "Unknown routes should return 404",
132 ) {
133 return;
134 }
135
136 println!("\nAll getting started examples validated successfully!");
137}Sourcepub fn with_config(config: RequestIdConfig) -> RequestIdMiddleware
pub fn with_config(config: RequestIdConfig) -> RequestIdMiddleware
Creates a new request ID middleware with the given configuration.
Trait Implementations§
Source§impl Clone for RequestIdMiddleware
impl Clone for RequestIdMiddleware
Source§fn clone(&self) -> RequestIdMiddleware
fn clone(&self) -> RequestIdMiddleware
Returns a duplicate of the value. Read more
1.0.0 · Source§fn clone_from(&mut self, source: &Self)
fn clone_from(&mut self, source: &Self)
Performs copy-assignment from
source. Read moreSource§impl Debug for RequestIdMiddleware
impl Debug for RequestIdMiddleware
Source§impl Default for RequestIdMiddleware
impl Default for RequestIdMiddleware
Source§fn default() -> RequestIdMiddleware
fn default() -> RequestIdMiddleware
Returns the “default value” for a type. Read more
Source§impl Middleware for RequestIdMiddleware
impl Middleware for RequestIdMiddleware
Source§fn before<'a>(
&'a self,
_ctx: &'a RequestContext,
req: &'a mut Request,
) -> Pin<Box<dyn Future<Output = ControlFlow> + Send + 'a>>
fn before<'a>( &'a self, _ctx: &'a RequestContext, req: &'a mut Request, ) -> Pin<Box<dyn Future<Output = ControlFlow> + Send + 'a>>
Called before the handler executes. Read more
Auto Trait Implementations§
impl Freeze for RequestIdMiddleware
impl RefUnwindSafe for RequestIdMiddleware
impl Send for RequestIdMiddleware
impl Sync for RequestIdMiddleware
impl Unpin for RequestIdMiddleware
impl UnsafeUnpin for RequestIdMiddleware
impl UnwindSafe for RequestIdMiddleware
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Mutably borrows from an owned value. Read more
Source§impl<T> CloneToUninit for Twhere
T: Clone,
impl<T> CloneToUninit for Twhere
T: Clone,
Source§impl<T> Instrument for T
impl<T> Instrument for T
Source§fn instrument(self, _span: NoopSpan) -> Self
fn instrument(self, _span: NoopSpan) -> Self
Instruments this future with a span (no-op when disabled).
Source§fn in_current_span(self) -> Self
fn in_current_span(self) -> Self
Instruments this future with the current span (no-op when disabled).