aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorFuwn <[email protected]>2025-07-08 05:15:47 +0000
committerFuwn <[email protected]>2025-07-08 05:15:47 +0000
commit22299ccd501324fc348788c65e67e2080c705547 (patch)
treef047076b73899f793cd92a2a56830f1a790b0013
parentrefactor(router): Smarter trailing slash clipper (diff)
downloadwindmark-22299ccd501324fc348788c65e67e2080c705547.tar.xz
windmark-22299ccd501324fc348788c65e67e2080c705547.zip
feat(router): Add missing trailing slash corrector
-rw-r--r--examples/fix_path.rs5
-rw-r--r--src/router.rs26
-rw-r--r--src/router_option.rs6
3 files changed, 28 insertions, 9 deletions
diff --git a/examples/fix_path.rs b/examples/fix_path.rs
index e92376c..95761ea 100644
--- a/examples/fix_path.rs
+++ b/examples/fix_path.rs
@@ -22,7 +22,10 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
windmark::router::Router::new()
.set_private_key_file("windmark_private.pem")
.set_certificate_file("windmark_public.pem")
- .add_options(&[windmark::router_option::RouterOption::TrimTrailingSlashes])
+ .add_options(&[
+ windmark::router_option::RouterOption::TrimTrailingSlashes,
+ windmark::router_option::RouterOption::AddMissingTrailingSlash,
+ ])
.mount(
"/close",
windmark::success!("Visit '/close/'; you should be close enough!"),
diff --git a/src/router.rs b/src/router.rs
index a82ea1e..461d698 100644
--- a/src/router.rs
+++ b/src/router.rs
@@ -423,13 +423,25 @@ impl Router {
let mut path = url.path().to_string();
let mut route = self.routes.at(&path);
- if route.is_err()
- && self.options.contains(&RouterOption::TrimTrailingSlashes)
- && path.ends_with('/')
- && path != "/"
- {
- path = path.trim_end_matches('/').to_string();
- route = self.routes.at(&path);
+ if route.is_err() {
+ if self.options.contains(&RouterOption::TrimTrailingSlashes)
+ && path.ends_with('/')
+ && path != "/"
+ {
+ path = path.trim_end_matches('/').to_string();
+ route = self.routes.at(&path);
+ } else if self
+ .options
+ .contains(&RouterOption::AddMissingTrailingSlash)
+ && !path.ends_with('/')
+ {
+ let path_with_slash = format!("{path}/");
+
+ if self.routes.at(&path_with_slash).is_ok() {
+ path = path_with_slash;
+ route = self.routes.at(&path);
+ }
+ }
}
let peer_certificate = stream.ssl().peer_certificate();
diff --git a/src/router_option.rs b/src/router_option.rs
index c99f3ab..2672a42 100644
--- a/src/router_option.rs
+++ b/src/router_option.rs
@@ -1,6 +1,10 @@
/// Options that can be set for the `Router`
#[derive(Debug, PartialEq, Eq, Hash, Clone, Copy)]
pub enum RouterOption {
- /// Trim trailing slashes from the URL path
+ /// Trim trailing slashes from the URL path if it is present and a route
+ /// match exists
TrimTrailingSlashes,
+ /// Add a trailing slash to the URL path if it is missing and a route
+ /// match exists
+ AddMissingTrailingSlash,
}