Getting captured Path
from extensions does not work
#2032
-
Bug ReportVersion
PlatformMacOS 13.0 DescriptionGetting capture path from extension does not work but getting MatchedPath does work. Is this expected? If so, would be great if this worked for #[derive(Clone)]
struct TestService;
impl Service<Request<Body>> for TestService {
type Response = Response;
type Error = Infallible;
type Future = Pin<Box<dyn Future<Output = Result<Response, Infallible>> + Send>>;
fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
Poll::Ready(Ok(()))
}
fn call(&mut self, req: Request<Body>) -> Self::Future {
let matched_path = req.extensions().get::<MatchedPath>().unwrap();
// let path = req.extensions().get::<Path<String>>().unwrap(); // returns None
let msg = format!("Result: {:?}", matched_path.as_str());
Box::pin(async move { Ok(msg.into_response())})
}
}
#[tokio::main]
async fn main() {
// build our application with a single route
let app = Router::new().route_service("/:id", TestService);
// run it with hyper on localhost:3000
axum::Server::bind(&"0.0.0.0:8081".parse().unwrap())
.serve(app.into_make_service())
.await
.unwrap();
} |
Beta Was this translation helpful? Give feedback.
Replies: 6 comments
-
It seems to work with |
Beta Was this translation helpful? Give feedback.
-
Are you looking for the whole request path? That would be |
Beta Was this translation helpful? Give feedback.
-
Not the whole request path but the captured value in the path. In the example above, I'd like the value of |
Beta Was this translation helpful? Give feedback.
-
Right, there is no way to do that without async at the moment. I think it would be easy enough to make it possible, but not sure if it's really worth it. In your example above, why do you want to extract the path outside the |
Beta Was this translation helpful? Give feedback.
-
That's just an example. I'm my application I'm using a Future that will be polled. |
Beta Was this translation helpful? Give feedback.
-
Yep that is expected. So you need to run the future from |
Beta Was this translation helpful? Give feedback.
Yep that is expected.
Path
needs to do more work thanMatchedPath
and we only wanna do that when you actually extract the path, rather than always do it up front.So you need to run the future from
Path::from_request_parts
as part of generating the response. I'd recommend usingaxum::middleware::from_fn
which makes it easy to run extractors.