url_parse/core/
path.rs

1use crate::core::Parser;
2use crate::utils::Utils;
3
4impl Parser {
5    /// Extract the path as a vector from the url.
6    ///
7    /// # Example
8    /// ```rust
9    /// use url_parse::core::Parser;
10    /// let input = "https://www.example.co.uk:443/blog/article/search?docid=720&hl=en#dayone";
11    /// let result = Parser::new(None).path(input).unwrap();
12    /// let expected = vec!["blog", "article", "search"];
13    /// assert_eq!(result, expected);
14    /// ```
15    pub fn path<'a>(&self, input: &'a str) -> Option<Vec<&'a str>> {
16        let input = Utils::substring_from_path_begin(self, input).unwrap_or("");
17        let input = Utils::substring_after_port(self, input);
18        let input = match input.chars().next() {
19            Some('/') => &input[1..],
20            _ => input,
21        };
22        let position_questionmark = input.find('?');
23        let path_string = match position_questionmark {
24            Some(v) => &input[..v],
25            None => input,
26        };
27        return Some(path_string.split('/').collect());
28    }
29}
30
31#[cfg(test)]
32mod tests {
33    use super::*;
34
35    #[test]
36    fn test_path_works_when_partial_url() {
37        let input = "https://www.example.co.uk/blog/article/search?docid=720&hl=en#dayone";
38        let result = Parser::new(None).path(input).unwrap();
39        let expected = vec!["blog", "article", "search"];
40        assert_eq!(result, expected);
41    }
42
43    #[test]
44    fn test_path_works_when_partial_url_starts_with_slash() {
45        let input = "https://www.example.co.uk/blog/article/search?docid=720&hl=en#dayone";
46        let result = Parser::new(None).path(input).unwrap();
47        let expected = vec!["blog", "article", "search"];
48        assert_eq!(result, expected);
49    }
50
51    #[test]
52    fn test_path_works_when_typical() {
53        let input = "https://www.example.co.uk:443/blog/article/search?docid=720&hl=en#dayone";
54        let result = Parser::new(None).path(input).unwrap();
55        let expected = vec!["blog", "article", "search"];
56        assert_eq!(result, expected);
57    }
58
59    #[test]
60    fn test_path_works_when_no_port() {
61        let input = "https://www.example.co.uk/blog/article/search?docid=720&hl=en#dayone";
62        let result = Parser::new(None).path(input).unwrap();
63        let expected = vec!["blog", "article", "search"];
64        assert_eq!(result, expected);
65    }
66}