http_type/http_url/impl.rs
1use crate::*;
2
3/// Implements the `std::error::Error` trait for `HttpUrlError`.
4impl std::error::Error for HttpUrlError {}
5
6/// Implements the `Display` trait for `HttpUrlError`, allowing it to be formatted as a string.
7impl Display for HttpUrlError {
8 /// Formats the `HttpUrlError` variant into a human-readable string.
9 ///
10 /// # Arguments
11 ///
12 /// - `f` - The formatter to write the string into.
13 ///
14 /// # Returns
15 ///
16 /// A `fmt::Result` indicating success or failure of the formatting operation.
17 #[inline(always)]
18 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
19 match self {
20 HttpUrlError::InvalidUrl => write!(f, "Invalid URL"),
21 HttpUrlError::Unknown => write!(f, "Unknown error"),
22 }
23 }
24}
25
26impl HttpUrlComponents {
27 /// Parses a URL string into its components.
28 ///
29 /// Extracts protocol, host, port, path, query and fragment from the URL string.
30 ///
31 /// # Arguments
32 ///
33 /// - `AsRef<str>` - The URL string to parse.
34 ///
35 /// # Returns
36 ///
37 /// - `Result<HttpUrlComponents, HttpUrlError>` - Either the parsed components or an error.
38 #[inline]
39 pub fn parse<U>(url_str: U) -> Result<Self, HttpUrlError>
40 where
41 U: AsRef<str>,
42 {
43 let parsed_url: Url = Url::parse(url_str.as_ref()).map_err(|_| HttpUrlError::InvalidUrl)?;
44 let res: Self = Self {
45 protocol: parsed_url
46 .scheme()
47 .to_string()
48 .parse::<Protocol>()
49 .unwrap_or_default(),
50 host: parsed_url.host_str().map(|h| h.to_string()),
51 port: parsed_url.port(),
52 path: Some(parsed_url.path().to_string()),
53 query: parsed_url.query().map(|q| q.to_string()),
54 fragment: parsed_url.fragment().map(|f| f.to_string()),
55 };
56 Ok(res)
57 }
58}