Skip to content

Commit

Permalink
HTTP 404 instead of empty response if not found
Browse files Browse the repository at this point in the history
  • Loading branch information
vilcans committed Aug 5, 2021
1 parent 905e7d5 commit 691f4e3
Showing 1 changed file with 15 additions and 11 deletions.
26 changes: 15 additions & 11 deletions src/cmd/serve.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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");
Expand All @@ -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,
};

Expand Down Expand Up @@ -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();
Expand Down

0 comments on commit 691f4e3

Please sign in to comment.