http_type/http_url/
impl.rs

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