http_type/http_url/
impl.rs

1use crate::*;
2use url::Url as UrlParser;
3
4/// Implements the `Default` trait for `HttpUrlComponents`.
5impl Default for HttpUrlComponents {
6    /// Returns a default `HttpUrlComponents` instance with all fields set to their default or empty values.
7    ///
8    /// # Returns
9    ///
10    /// A default `HttpUrlComponents` instance.
11    fn default() -> Self {
12        HttpUrlComponents {
13            protocol: Protocol::Unknown(String::new()),
14            host: None,
15            port: None,
16            path: None,
17            query: None,
18            fragment: None,
19        }
20    }
21}
22
23impl HttpUrlComponents {
24    /// Parses a URL string into its components.
25    ///
26    /// Extracts protocol, host, port, path, query and fragment from the URL string.
27    ///
28    /// # Arguments
29    ///
30    /// - `&str` - The URL string to parse.
31    ///
32    /// # Returns
33    ///
34    /// - `Result<HttpUrlComponents, HttpUrlError>` - Either the parsed components or an error.
35    pub fn parse(url_str: &str) -> Result<Self, HttpUrlError> {
36        let parsed_url: UrlParser =
37            UrlParser::parse(url_str).map_err(|_| HttpUrlError::InvalidUrl)?;
38        let res: Self = Self {
39            protocol: parsed_url
40                .scheme()
41                .to_string()
42                .parse::<Protocol>()
43                .unwrap_or_default(),
44            host: parsed_url.host_str().map(|h| h.to_string()),
45            port: parsed_url.port(),
46            path: Some(parsed_url.path().to_string()),
47            query: parsed_url.query().map(|q| q.to_string()),
48            fragment: parsed_url.fragment().map(|f| f.to_string()),
49        };
50        Ok(res)
51    }
52}