Skip to main content

http_acl/utils/
url.rs

1//! URL utilities.
2
3use percent_encoding::percent_decode_str;
4use url::Url;
5
6/// Extracts the percent-decoded path from a full URL string, ready to pass to
7/// [`HttpAcl::is_url_path_allowed`](crate::HttpAcl::is_url_path_allowed).
8///
9/// Returns `None` if `url` isn't a valid URL, or if its path isn't valid UTF-8 once
10/// decoded.
11pub fn get_url_path(url: &str) -> Option<String> {
12    let url = Url::parse(url).ok()?;
13    let decoded = percent_decode_str(url.path()).decode_utf8().ok()?;
14    Some(decoded.into_owned())
15}
16
17#[cfg(test)]
18mod tests {
19    use super::*;
20
21    #[test]
22    fn test_get_url_path_decodes_percent_encoding() {
23        assert_eq!(
24            get_url_path("https://example.com/api/versions").as_deref(),
25            Some("/api/versions")
26        );
27        assert_eq!(
28            get_url_path("https://example.com/countries/vi%E1%BB%87t%20nam").as_deref(),
29            Some("/countries/việt nam")
30        );
31    }
32
33    #[test]
34    fn test_get_url_path_invalid_url() {
35        assert_eq!(get_url_path("not a url"), None);
36    }
37}