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

Fix ServeDir Bug #122

Merged
merged 4 commits into from
Aug 19, 2021
Merged
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 30 additions & 2 deletions tower-http/src/services/fs/serve_dir.rs
Original file line number Diff line number Diff line change
Expand Up @@ -86,8 +86,12 @@ impl<ReqBody> Service<Request<ReqBody>> for ServeDir {
HeaderValue::from_str(&append_slash_on_path(uri).to_string()).unwrap();
return Ok(Output::Redirect(location));
}
} else if append_index_html_on_directories && is_dir(&full_path).await {
full_path.push("index.html");
} else if is_dir(&full_path).await {
if append_index_html_on_directories {
full_path.push("index.html");
} else {
return Ok(Output::NotFound);
}
}

let guess = mime_guess::from_path(&full_path);
Expand Down Expand Up @@ -146,6 +150,7 @@ fn append_slash_on_path(uri: Uri) -> Uri {
enum Output {
File(File, HeaderValue),
Redirect(HeaderValue),
NotFound,
}

type BoxFuture<T> = Pin<Box<dyn Future<Output = T> + Send + Sync + 'static>>;
Expand Down Expand Up @@ -178,6 +183,15 @@ impl Future for ResponseFuture {
return Poll::Ready(Ok(res));
}

Ok(Output::NotFound) => {
let res = Response::builder()
.status(StatusCode::NOT_FOUND)
.body(empty_body())
.unwrap();

return Poll::Ready(Ok(res));
}

Err(err) => {
return Poll::Ready(
super::response_from_io_error(err).map(|res| res.map(ResponseBody)),
Expand Down Expand Up @@ -291,6 +305,20 @@ mod tests {
assert_eq!(location, "/src/");
}

#[tokio::test]
async fn empty_directory_without_index() {
let svc = ServeDir::new(".").append_index_html_on_directories(false);

let req = Request::new(Body::empty());
let res = svc.oneshot(req).await.unwrap();

assert_eq!(res.status(), StatusCode::NOT_FOUND);
assert!(res.headers().get(header::CONTENT_TYPE).is_none());

let body = body_into_text(res.into_body()).await;
assert!(body.is_empty());
}

async fn body_into_text<B>(body: B) -> String
where
B: HttpBody<Data = bytes::Bytes> + Unpin,
Expand Down