http_type/http_url/
impl.rs

1use crate::*;
2use url::Url as UrlParser;
3
4impl Default for HttpUrlComponents {
5    fn default() -> Self {
6        HttpUrlComponents {
7            protocol: Protocol::Unknown(String::new()),
8            host: None,
9            port: None,
10            path: None,
11            query: None,
12            fragment: None,
13        }
14    }
15}
16
17impl HttpUrlComponents {
18    /// Parses a URL string into a `HttpUrlComponents ` instance.
19    ///
20    /// This method attempts to parse a given URL string into its components such as
21    /// scheme, username, password, host, port, path, query, and fragment. If the URL
22    /// is invalid, it returns an `Error::InvalidUrl` error.
23    ///
24    /// # Parameters
25    /// - `url_str`: A string slice representing the URL to be parsed.
26    ///
27    /// # Returns
28    /// Returns a `Result` containing either a `HttpUrlComponents ` instance populated with the
29    /// parsed components or an `Error::InvalidUrl` if the parsing fails.
30    pub fn parse(url_str: &str) -> Result<Self, HttpUrlError> {
31        let parsed_url: UrlParser =
32            UrlParser::parse(url_str).map_err(|_| HttpUrlError::InvalidUrl)?;
33        let res: Self = Self {
34            protocol: parsed_url
35                .scheme()
36                .to_string()
37                .parse::<Protocol>()
38                .unwrap_or_default(),
39            host: parsed_url.host_str().map(|h| h.to_string()),
40            port: parsed_url.port(),
41            path: Some(parsed_url.path().to_string()),
42            query: parsed_url.query().map(|q| q.to_string()),
43            fragment: parsed_url.fragment().map(|f| f.to_string()),
44        };
45        Ok(res)
46    }
47}