feat: add support for .html prefixing when request path doesn't exist (#180)
* Added support for path serving with html wrapping
* Elide explicit 'a lifetime
---------
Co-authored-by: Jose Quintana <joseluisquintana20@gmail.com>
Diff
src/static_files.rs | 44 +++++++++++++++++++++++++++++++++++++++++++-
1 file changed, 43 insertions(+), 1 deletion(-)
@@ -138,11 +138,32 @@ pub async fn handle<'a>(opts: &HandleOpts<'a>) -> Result<(Response<Body>, bool),
Ok((resp, is_precompressed))
}
fn prefix_file_html_metadata(file_path: &mut PathBuf) -> (&mut PathBuf, Option<Metadata>) {
tracing::debug!("file: appending .html to the path");
if let Some(filename) = file_path.file_name() {
let owned_filename = filename.to_os_string();
let mut owned_filename_with_html = owned_filename.clone();
owned_filename_with_html.push(".html");
file_path.set_file_name(owned_filename_with_html);
if let Ok(meta_res) = file_metadata(file_path.as_ref()) {
let (meta, _) = meta_res;
return (file_path, Some(meta));
} else {
file_path.set_file_name(owned_filename);
}
}
(file_path, None)
}
async fn composed_file_metadata<'a>(
file_path: &'a mut PathBuf,
mut file_path: &'a mut PathBuf,
headers: &'a HeaderMap<HeaderValue>,
compression_static: bool,
) -> Result<(&'a PathBuf, Metadata, bool, Option<(PathBuf, &'a str)>), StatusCode> {
@@ -170,12 +191,33 @@ async fn composed_file_metadata<'a>(
if let Ok(meta_res) = file_metadata(file_path.as_ref()) {
(meta, _) = meta_res
} else {
file_path.pop();
let new_meta: Option<Metadata>;
(file_path, new_meta) = prefix_file_html_metadata(file_path);
if let Some(new_meta) = new_meta {
meta = new_meta;
} else {
file_path.push("index.html");
}
}
}
Ok((file_path, meta, is_dir, None))
}
Err(err) => {
if err == StatusCode::NOT_FOUND {
let new_meta: Option<Metadata>;
(file_path, new_meta) = prefix_file_html_metadata(file_path);
if let Some(new_meta) = new_meta {
return Ok((file_path, new_meta, false, None));
}
}
if compression_static && !tried_precompressed {
if let Some((path, meta, ext)) =