ts_webapi/
uri.rs

1//! URI helpers
2
3use http::Uri;
4
5/// Extension trait for URIs
6pub trait UriExt {
7    /// Get the path segment by index:
8    ///
9    /// ```notrust
10    /// http://localhost:4000/some-route/sub-route
11    ///                      /|--------|/|-------|
12    ///                        index 0    index 1
13    /// ```
14    fn get_path_segment(&self, index: usize) -> Option<&str>;
15}
16
17impl UriExt for Uri {
18    fn get_path_segment(&self, index: usize) -> Option<&str> {
19        self.path().split('/').nth(index + 1)
20    }
21}
22
23#[cfg(test)]
24mod test {
25    use http::Uri;
26
27    use crate::uri::UriExt;
28
29    #[test]
30    fn gets_corect_path_segment() {
31        let uri = Uri::from_static("http://localhost:4000/some-route/some-sub-route//bad-route/");
32        assert_eq!(Some("some-route"), uri.get_path_segment(0));
33        assert_eq!(Some("some-sub-route"), uri.get_path_segment(1));
34        assert_eq!(Some(""), uri.get_path_segment(2));
35        assert_eq!(Some("bad-route"), uri.get_path_segment(3));
36        assert_eq!(Some(""), uri.get_path_segment(4));
37        assert_eq!(None, uri.get_path_segment(5));
38    }
39}