Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Properly clone the request for ServeDir's fallback #258

Merged
merged 1 commit into from Apr 28, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
12 changes: 6 additions & 6 deletions tower-http/src/services/fs/serve_dir/mod.rs
Expand Up @@ -290,17 +290,17 @@ where
};

let fallback_and_request = self.fallback.as_mut().map(|fallback| {
let mut req = Request::new(body);
*req.method_mut() = req.method().clone();
*req.uri_mut() = req.uri().clone();
*req.headers_mut() = req.headers().clone();
*req.extensions_mut() = extensions;
let mut fallback_req = Request::new(body);
*fallback_req.method_mut() = req.method().clone();
*fallback_req.uri_mut() = req.uri().clone();
*fallback_req.headers_mut() = req.headers().clone();
*fallback_req.extensions_mut() = extensions;

// get the ready fallback and leave a non-ready clone in its place
let clone = fallback.clone();
let fallback = std::mem::replace(fallback, clone);

(fallback, req)
(fallback, fallback_req)
});

let buf_chunk_size = self.buf_chunk_size;
Expand Down
9 changes: 6 additions & 3 deletions tower-http/src/services/fs/serve_dir/tests.rs
Expand Up @@ -585,8 +585,11 @@ async fn last_modified() {

#[tokio::test]
async fn with_fallback_svc() {
async fn fallback<B>(_: Request<B>) -> io::Result<Response<Body>> {
Ok(Response::new(Body::from("from fallback")))
async fn fallback<B>(req: Request<B>) -> io::Result<Response<Body>> {
Ok(Response::new(Body::from(format!(
"from fallback {}",
req.uri().path()
))))
}

let svc = ServeDir::new("..").fallback(tower::service_fn(fallback));
Expand All @@ -600,7 +603,7 @@ async fn with_fallback_svc() {
assert_eq!(res.status(), StatusCode::OK);

let body = body_into_text(res.into_body()).await;
assert_eq!(body, "from fallback");
assert_eq!(body, "from fallback /doesnt-exist");
}

#[tokio::test]
Expand Down