HTTP 404 instead of empty response if not found
Fixes getzola/zola#1578
@@ -111,7 +111,10 @@ async fn handle_request(req: Request<Body>, mut root: PathBuf) -> Result<Respons
// otherwise `PathBuf` will interpret it as an absolute path
root.push(&decoded[1..]);
- let metadata = tokio::fs::metadata(root.as_path()).await?;
+ let metadata = match tokio::fs::metadata(root.as_path()).await {
+ Err(err) => return Ok(io_error(err)),
+ Ok(metadata) => metadata,
+ };
if metadata.is_dir() {
// if root is a directory, append index.html to try to read that instead
root.push("index.html");
@@ -120,16 +123,7 @@ async fn handle_request(req: Request<Body>, mut root: PathBuf) -> Result<Respons
let result = tokio::fs::read(&root).await;
let contents = match result {
- Err(err) => match err.kind() {
- std::io::ErrorKind::NotFound => return Ok(not_found()),
- std::io::ErrorKind::PermissionDenied => {
- return Ok(Response::builder()
- .status(StatusCode::FORBIDDEN)
- .body(Body::empty())
- .unwrap())
- }
- _ => panic!("{}", err),
- },
+ Err(err) => return Ok(io_error(err)),
Ok(contents) => contents,
};
@@ -176,6 +170,16 @@ fn method_not_allowed() -> Response<Body> {
.expect("Could not build Method Not Allowed response")
}
+fn io_error(err: std::io::Error) -> Response<Body> {
+ match err.kind() {
+ std::io::ErrorKind::NotFound => not_found(),
+ std::io::ErrorKind::PermissionDenied => {
+ Response::builder().status(StatusCode::FORBIDDEN).body(Body::empty()).unwrap()
+ }
+ _ => panic!("{}", err),
+ }
+}
+
fn not_found() -> Response<Body> {
let not_found_path = RelativePath::new("404.html");
let content = SITE_CONTENT.read().unwrap().get(not_found_path).cloned();
