53 lines
1.2 KiB
Rust
53 lines
1.2 KiB
Rust
#[derive(Debug)]
|
|
pub struct Url<'a> {
|
|
path_segments: Vec<&'a str>,
|
|
query_params: QueryParams<'a>,
|
|
}
|
|
|
|
pub type QueryParam<'a> = (&'a str, &'a str);
|
|
|
|
pub type QueryParams<'a> = Vec<QueryParam<'a>>;
|
|
|
|
impl Url<'_> {
|
|
pub fn parse(url: &str) -> Url {
|
|
let mut parts = url.splitn(2, '?');
|
|
|
|
let path = parts.next().unwrap_or_default();
|
|
let query = parts.next();
|
|
|
|
Url {
|
|
path_segments: extract_path_segments(path),
|
|
query_params: extract_query_params(query),
|
|
}
|
|
}
|
|
|
|
pub fn path_segments(&self) -> &[&str] {
|
|
self.path_segments.as_slice()
|
|
}
|
|
|
|
pub fn query_params(&self) -> &QueryParams {
|
|
&self.query_params
|
|
}
|
|
}
|
|
|
|
fn extract_path_segments(path: &str) -> Vec<&str> {
|
|
path.split('/').skip(1).collect()
|
|
}
|
|
|
|
fn extract_query_params(query: Option<&str>) -> Vec<QueryParam> {
|
|
query
|
|
.clone()
|
|
.map(|q| {
|
|
q.split('&')
|
|
.filter_map(|part| {
|
|
if let [key, val] = part.splitn(2, '=').collect::<Vec<&str>>()[..] {
|
|
Some((key, val))
|
|
} else {
|
|
None
|
|
}
|
|
})
|
|
.collect()
|
|
})
|
|
.unwrap_or_default()
|
|
}
|