use Body::from_file in serve_dir
-use crate::http::Mime;
use crate::log;
use crate::{Body, Endpoint, Request, Response, Result, StatusCode};
-use async_std::fs::File;
-use async_std::io::BufReader;
-
use std::ffi::OsStr;
use std::path::{Path, PathBuf};
@@ -44,36 +40,9 @@ impl<State> Endpoint<State> for ServeDir {
log::warn!("Unauthorized attempt to read: {:?}", file_path);
return Ok(Response::new(StatusCode::Forbidden));
}
-
- let file = match File::open(&file_path).await {
- Err(error) => {
- return if error.kind() == async_std::io::ErrorKind::NotFound {
- log::warn!("File not found: {:?}", file_path);
- Ok(Response::new(StatusCode::NotFound))
- } else {
- log::warn!("Could not open {:?}", file_path);
- Ok(Response::new(StatusCode::InternalServerError))
- }
- }
- Ok(file) => file,
- };
-
- let len = if let Ok(metadata) = file.metadata().await {
- metadata.len() as usize
- } else {
- log::warn!("Could not retrieve metadata");
- return Ok(Response::new(StatusCode::InternalServerError));
- };
-
- let body = Body::from_reader(BufReader::new(file), Some(len));
- // TODO: fix related bug where async-h1 crashes on large files
+ let body = Body::from_file(&file_path).await?;
let mut res = Response::new(StatusCode::Ok);
res.set_body(body);
-
- if let Some(content_type) = mime_guess::from_path(&file_path).first() {
- res = res.set_mime(content_type.to_string().parse::<Mime>().unwrap());
- }
-
Ok(res)
})
}
