craweb/
lib.rs

1pub mod macros;
2pub mod models;
3pub mod server;
4
5mod utils {
6    use crate::models::RequestMethod;
7    use std::collections::HashMap;
8
9    #[allow(dead_code)]
10    /// Gets the query from the provided URL.
11    ///
12    /// ## Example
13    /// ```
14    /// let query = utils::get_url_query("https://some.url?and=some&query=params#bla=bla"); // -> HashMap<&str, &str>; size: 3
15    /// assert_eq!(query.len(), 3); // -> true
16    /// ```
17    pub fn get_url_query(url: &str) -> HashMap<&str, &str> {
18        let mut queries: HashMap<&str, &str> = HashMap::new();
19        let mut query: Vec<&str> = url.split(&['?', '&', '#'][..]).collect();
20        query.remove(0); // removing URI
21
22        for part in query {
23            let name_value: Vec<&str> = part.split("=").collect();
24            // drop checking for invalid query parts (like test=)
25            if name_value.len() == 2 {
26                queries.insert(name_value[0], name_value[1]);
27            }
28        }
29
30        return queries;
31    }
32
33    /// This function gets inputted request method in string
34    /// and returns the same field from the `RequestMethod` enum.
35    ///
36    /// ## Example
37    /// ```
38    /// let enum_method = get_request_method("GET"); // -> RequestMethod::GET
39    /// assert_eq!(enum_method, RequestMethod::GET); // -> true
40    /// ```
41    pub fn get_request_method(string_method: &str) -> anyhow::Result<RequestMethod> {
42        match string_method {
43            "GET" => Ok(RequestMethod::GET),
44            "HEAD" => Ok(RequestMethod::HEAD),
45            "POST" => Ok(RequestMethod::POST),
46            "PUT" => Ok(RequestMethod::PUT),
47            "DELETE" => Ok(RequestMethod::DELETE),
48            "CONNECT" => Ok(RequestMethod::CONNECT),
49            "OPTIONS" => Ok(RequestMethod::OPTIONS),
50            "TRACE" => Ok(RequestMethod::TRACE),
51            "PATCH" => Ok(RequestMethod::PATCH),
52            &_ => Err(anyhow::anyhow!("Unknown request method")),
53        }
54    }
55}
56
57#[cfg(test)]
58mod tests {
59    use crate::models::RequestMethod;
60
61    #[test]
62    fn test_getting_query() {
63        let query = crate::utils::get_url_query("https://some.url?and=some&query=params#bla=bla");
64        assert_eq!(query.len(), 3);
65    }
66
67    #[test]
68    fn test_getting_method() {
69        assert!(matches!(
70            crate::utils::get_request_method("GET").unwrap(),
71            RequestMethod::GET
72        ));
73        assert!(matches!(
74            crate::utils::get_request_method("POST").unwrap(),
75            RequestMethod::POST
76        ));
77    }
78}