rust_web_server/url/
mod.rs1#[cfg(test)]
10mod tests;
11#[cfg(test)]
12mod example;
13pub mod path;
14
15use std::collections::HashMap;
16use url_build_parse::{build_url, UrlAuthority, UrlComponents, UrlUserInfo};
17use url_search_params::{build_url_search_params, encode_uri_component, parse_url_search_params};
18use url_search_params::decode_uri_component;
19
20pub struct URL;
22
23impl URL {
24 pub fn percent_encode(component: &str) -> String {
25 encode_uri_component(component)
26 }
27
28 pub fn percent_decode(component: &str) -> String {
29 decode_uri_component(component)
30 }
31
32 pub fn build_query(params: HashMap<String, String>) -> String {
33 build_url_search_params(params)
34 }
35
36 pub fn parse_query(component: &str) -> HashMap<String, String> {
37 parse_url_search_params(component)
38 }
39
40 pub fn build(components: UrlComponents) -> Result<String, String> {
41 build_url(components)
42 }
43
44 pub fn parse(url: &str) -> Result<UrlComponents, String> {
45 parse_url(url)
46 }
47
48 pub fn parse_request_target(target: &str) -> Result<UrlComponents, String> {
53 if !target.starts_with('/') {
54 return Err(format!("not an origin-form request target: {:?}", target));
55 }
56 parse_url(&format!("http://localhost{}", target))
57 }
58
59 pub(crate) fn request_target_path(target: &str) -> Option<&str> {
64 if !target.starts_with('/') {
65 return None;
66 }
67 Some(&target[..target.find(['?', '#']).unwrap_or(target.len())])
68 }
69}
70
71fn parse_url(url: &str) -> Result<UrlComponents, String> {
76 let (scheme, rest) = url.split_once(':').ok_or("unable to identify scheme")?;
77 if rest.is_empty() {
78 return Err("error: remaining url is empty".to_string());
79 }
80 let mut components = UrlComponents::new();
81 components.scheme = scheme.to_string();
82
83 let mut remaining = rest;
85 if let Some(after) = rest.strip_prefix("//") {
86 let end = after.find(['/', '?', '#']).unwrap_or(after.len());
87 components.authority = Some(parse_authority(&after[..end])?);
88 remaining = &after[end..];
89 }
90
91 let path_end = remaining.find(['?', '#']).unwrap_or(remaining.len());
93 components.path = remaining[..path_end].to_string();
94 remaining = &remaining[path_end..];
95
96 if let Some(after) = remaining.strip_prefix('?') {
97 let query_end = after.find('#').unwrap_or(after.len());
98 components.query = Some(parse_url_search_params(&after[..query_end]));
99 remaining = &after[query_end..];
100 }
101 if let Some(fragment) = remaining.strip_prefix('#') {
102 components.fragment = Some(fragment.to_string());
103 }
104 Ok(components)
105}
106
107fn parse_authority(authority: &str) -> Result<UrlAuthority, String> {
109 let (user_info, host_port) = match authority.split_once('@') {
110 Some((user_info, host_port)) => {
111 let user_info = match user_info.split_once(':') {
112 Some((username, password)) => UrlUserInfo {
113 username: username.to_string(),
114 password: Some(password.to_string()),
115 },
116 None => UrlUserInfo { username: user_info.to_string(), password: None },
117 };
118 (Some(user_info), host_port)
119 }
120 None => (None, authority),
121 };
122
123 let (host, port_str) = if host_port.starts_with('[') {
124 let close = host_port.find(']').ok_or("unterminated IPv6 host")?;
125 let after = &host_port[close + 1..];
126 let port = match after.strip_prefix(':') {
127 Some(port) => Some(port),
128 None if after.is_empty() => None,
129 None => return Err(format!("unexpected characters after IPv6 host: {:?}", after)),
130 };
131 (&host_port[..=close], port)
132 } else {
133 match host_port.split_once(':') {
134 Some((host, port)) => (host, Some(port)),
135 None => (host_port, None),
136 }
137 };
138
139 let port = match port_str {
140 Some(port) => Some(port.parse::<usize>().map_err(|_| format!("invalid port: {:?}", port))?),
141 None => None,
142 };
143 Ok(UrlAuthority { user_info, host: host.to_string(), port })
144}
145