From ef43aaefab2b429ed6b0ea695bad0d6f497f32b6 Mon Sep 17 00:00:00 2001 From: 29 <791603901@qq.com> Date: Sat, 27 Jul 2024 13:12:03 +0800 Subject: [PATCH] Fix `EmbeddedFilesEndpoint` not working for `index.html` in subdirectories (#825) --- poem/src/endpoint/embed.rs | 33 +++++++++++++++++++++++---------- 1 file changed, 23 insertions(+), 10 deletions(-) diff --git a/poem/src/endpoint/embed.rs b/poem/src/endpoint/embed.rs index d07aa8544f..c7165cb63d 100644 --- a/poem/src/endpoint/embed.rs +++ b/poem/src/endpoint/embed.rs @@ -83,16 +83,29 @@ impl Endpoint for EmbeddedFilesEndpoint { type Output = Response; async fn call(&self, req: Request) -> Result { - let mut path = req - .uri() - .path() - .trim_start_matches('/') - .trim_end_matches('/') - .to_string(); - if path.is_empty() { - path = "index.html".to_string(); + let path = req.uri().path().trim_start_matches('/'); + let original_path = req.original_uri().path(); + let original_end_with_slash = original_path.ends_with('/'); + + use header::LOCATION; + + if path.is_empty() && !original_end_with_slash { + Ok(Response::builder() + .status(StatusCode::FOUND) + .header(LOCATION, format!("{}/", original_path)) + .finish()) + } else if original_end_with_slash { + let path = format!("{}index.html", path); + EmbeddedFileEndpoint::::new(&path).call(req).await + } else if E::get(path).is_some() { + EmbeddedFileEndpoint::::new(path).call(req).await + } else if E::get(&format!("{}/index.html", path)).is_some() { + Ok(Response::builder() + .status(StatusCode::FOUND) + .header(LOCATION, format!("{}/", original_path)) + .finish()) + } else { + EmbeddedFileEndpoint::::new(path).call(req).await } - let path = path.as_ref(); - EmbeddedFileEndpoint::::new(path).call(req).await } }