http_type/http_url/
impl.rs

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