Skip to content

Commit

Permalink
Merge pull request #1500 from itowlson/handle-missing-leading-slash
Browse files Browse the repository at this point in the history
Tolerate component routes not starting with '/'
  • Loading branch information
itowlson authored May 17, 2023
2 parents e04f8cd + a670526 commit 2c776aa
Showing 1 changed file with 28 additions and 5 deletions.
33 changes: 28 additions & 5 deletions crates/http/src/routes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -165,11 +165,18 @@ impl RoutePattern {

/// Sanitizes the base and path and return a formed path.
pub fn sanitize_with_base<S: Into<String>>(base: S, path: S) -> String {
format!(
"{}{}",
Self::sanitize(base.into()),
Self::sanitize(path.into())
)
let path = Self::absolutize(path);

format!("{}{}", Self::sanitize(base.into()), Self::sanitize(path))
}

fn absolutize<S: Into<String>>(s: S) -> String {
let s = s.into();
if s.starts_with('/') {
s
} else {
format!("/{s}")
}
}

/// Strips the trailing slash from a string.
Expand Down Expand Up @@ -254,6 +261,22 @@ mod route_tests {
assert!(rp.matches("/base"));
}

#[test]
fn handles_missing_leading_slash() {
let rp = RoutePattern::from("/", "foo/bar");
assert!(rp.matches("/foo/bar"));
assert!(rp.matches("/foo/bar/"));
assert!(!rp.matches("/foo"));
assert!(!rp.matches("/foo/bar/thisshouldbefalse"));
assert!(!rp.matches("/abc"));

let rp = RoutePattern::from("/base", "foo");
assert!(rp.matches("/base/foo"));
assert!(rp.matches("/base/foo/"));
assert!(!rp.matches("/base/foo/bar"));
assert!(!rp.matches("/thishouldbefalse"));
}

#[test]
fn test_relative() -> Result<()> {
assert_eq!(
Expand Down

0 comments on commit 2c776aa

Please sign in to comment.