From 17f3fe2bda4859fc125cbdf34cc405cf782de1eb Mon Sep 17 00:00:00 2001 From: Martin Vilcans Date: Fri, 6 Aug 2021 11:39:13 +0200 Subject: [PATCH] HTTP 404 instead of empty response if not found (#1580) Fixes getzola/zola#1578 --- src/cmd/serve.rs | 26 +++++++++++++++----------- 1 file changed, 15 insertions(+), 11 deletions(-) diff --git a/src/cmd/serve.rs b/src/cmd/serve.rs index 37438e69..cfdc2257 100644 --- a/src/cmd/serve.rs +++ b/src/cmd/serve.rs @@ -111,7 +111,10 @@ async fn handle_request(req: Request, mut root: PathBuf) -> Result 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, mut root: PathBuf) -> Result 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 { .expect("Could not build Method Not Allowed response") } +fn io_error(err: std::io::Error) -> Response { + 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 { let not_found_path = RelativePath::new("404.html"); let content = SITE_CONTENT.read().unwrap().get(not_found_path).cloned();