Skip to content

Commit

Permalink
Properly clone the request for ServeDir's fallback (#258)
Browse files Browse the repository at this point in the history
  • Loading branch information
sandhose committed Apr 28, 2022
1 parent 8f4d27c commit 241a52f
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 9 deletions.
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

0 comments on commit 241a52f

Please sign in to comment.