How can you get the matched route in middleware? #1505
-
I would like to emit metrics about the route, response code, and latency in a middleware function. But I'm having trouble figuring out how to get the matched path (and not the actual request path) for paths that match on wildcards. To be more specific, I have a route:
and a middleware function:
How can I get the matched path in the middleware function? I know there is an extractor for the matched path but I'm not sure how to use that here. |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments
-
You don't need to use the extractor, you can get the |
Beta Was this translation helpful? Give feedback.
-
This should also work if you're on 0.6.0-rc.x .layer(middleware::from_fn(move |matched_path, req, next| {
record_metrics(matched_path, req, next, metrics.clone())
}))
async fn record_metrics(
matched_path: MatchedPath,
req: Request<Body>,
next: Next<Body>,
metrics: Arc<Metrics>,
) -> Result<impl IntoResponse, (StatusCode, String)> {
...
} |
Beta Was this translation helpful? Give feedback.
You don't need to use the extractor, you can get the
MatchedPath
from the request extensions, as shown in the second example in the documentation.