Skip to content
Snippets Groups Projects
Commit 377b68cf authored by codecraft's avatar codecraft :crocodile:
Browse files

FIX: Uri Pretty print

parent 53a054d8
No related branches found
No related tags found
1 merge request!2Project Completed
...@@ -143,11 +143,7 @@ pub async fn handle_connection<T: AsyncRead + AsyncWrite + std::marker::Unpin>(m ...@@ -143,11 +143,7 @@ pub async fn handle_connection<T: AsyncRead + AsyncWrite + std::marker::Unpin>(m
if !route.uri.compare_uri(&request.uri) { if !route.uri.compare_uri(&request.uri) {
continue; continue;
} }
handled_response = Some((route.handler)( handled_response = Some((route.handler)(request.clone(), data.clone()));
request.clone()
,
data.clone(),
));
if let Some(Outcome::Forward(_)) = handled_response { if let Some(Outcome::Forward(_)) = handled_response {
continue; continue;
......
...@@ -248,18 +248,13 @@ impl Request { ...@@ -248,18 +248,13 @@ impl Request {
} }
#[cfg(test)] #[cfg(test)]
mod test { mod test {
use std::str::FromStr;
use crate::{ use crate::{
handling::{ handling::{
methods::Method, methods::Method,
request::{datatypes::ParseErrors, ParseFormError}, request::{datatypes::ParseErrors, ParseFormError},
routes::Data, routes::Data,
}, },
utils::{ utils::mime::Mime::{ApplicationXWwwFormUrlencoded, MultipartFormData},
mime::Mime::{ApplicationXWwwFormUrlencoded, MultipartFormData},
url_utils::Uri,
},
}; };
use super::Request; use super::Request;
......
...@@ -11,7 +11,7 @@ use tokio_native_tls::{native_tls::{Identity, self}, TlsAcceptor}; ...@@ -11,7 +11,7 @@ use tokio_native_tls::{native_tls::{Identity, self}, TlsAcceptor};
use crate::{ use crate::{
handlers::handler::handle_connection, handlers::handler::handle_connection,
handling::routes::Route, utils::{url_utils::Uri, vec_utils::remove_n}, handling::routes::Route, utils::url_utils::Uri,
}; };
#[cfg(feature = "secure")] #[cfg(feature = "secure")]
use crate::handling::response::{Response, Status}; use crate::handling::response::{Response, Status};
...@@ -40,22 +40,6 @@ pub struct Config { ...@@ -40,22 +40,6 @@ pub struct Config {
tls_acceptor: TlsAcceptor, tls_acceptor: TlsAcceptor,
} }
impl MountPoint {
pub fn compare_with_uri(&self, uri: &mut Uri) -> bool {
let mut uri_iter = uri.parts().iter();
let to_remove_after_finish = self.mountpoint.parts().len();
for part in self.mountpoint.parts().iter() {
let Some(part_uri) = uri_iter.next() else {
return false;
};
if part != part_uri {
return false;
}
}
remove_n(uri.mut_parts(), to_remove_after_finish);
true
}
}
impl<'a> Config { impl<'a> Config {
/// Utility that checks if the given mointpoint is already taken. takes in the uri of the to be /// Utility that checks if the given mointpoint is already taken. takes in the uri of the to be
...@@ -78,7 +62,7 @@ impl<'a> Config { ...@@ -78,7 +62,7 @@ impl<'a> Config {
return self; return self;
} }
routes.sort_by(|a, b| a.rank.cmp(&b.rank)); routes.sort_by(|a, b| a.rank.cmp(&b.rank));
let mut mount_message = format!(" >> \x1b[35m{}\x1b[0m\n", mountpoint); let mut mount_message = format!(" >> \x1b[35m{}\x1b[0m\n", mountpoint.to_pretty_print_string());
for (index, route) in routes.iter().enumerate() { for (index, route) in routes.iter().enumerate() {
let indent_sign = match index { let indent_sign = match index {
i if i == routes.len() - 1 => "└─", i if i == routes.len() - 1 => "└─",
...@@ -86,11 +70,10 @@ impl<'a> Config { ...@@ -86,11 +70,10 @@ impl<'a> Config {
}; };
mount_message += &format!( mount_message += &format!(
" \x1b[35m{indent_sign}\x1b[0m \x1b[36m(\x1b[0m{}\x1b[36m)\x1b[0m \x1b[32m{}\x1b[0m \x1b[34;4m{}\x1b[24m{}\x1b[0m\n", " \x1b[35m{indent_sign}\x1b[0m \x1b[36m(\x1b[0m{}\x1b[36m)\x1b[0m \x1b[32m{}\x1b[0m {}\n",
route.name.unwrap_or(""), route.name.unwrap_or(""),
route.method, route.method,
mountpoint, route.uri.to_pretty_print_string(&mountpoint)
route.uri
) )
} }
......
...@@ -5,6 +5,7 @@ use crate::utils::urlencoded::UrlEncodeData; ...@@ -5,6 +5,7 @@ use crate::utils::urlencoded::UrlEncodeData;
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone)] #[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone)]
pub struct Uri { pub struct Uri {
pub(super) parts: Vec<UrlEncodeData>, pub(super) parts: Vec<UrlEncodeData>,
pub raw: String,
} }
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone)] #[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone)]
......
use std::str::FromStr; use std::str::FromStr;
use crate::utils::{url_utils::datatypes::RawUriElement, urlencoded::UrlEncodeData}; use crate::{
setup::MountPoint,
utils::{url_utils::datatypes::RawUriElement, urlencoded::UrlEncodeData, vec_utils::remove_n},
};
use super::datatypes::{ParseUriError, RawUri, Uri}; use super::datatypes::{ParseUriError, RawUri, Uri};
impl MountPoint {
pub fn compare_with_uri(&self, uri: &mut Uri) -> bool {
if !uri.raw.starts_with(&self.mountpoint.raw) {
return false;
}
let to_remove_after_finish = self.mountpoint.parts.len();
remove_n(uri.mut_parts(), to_remove_after_finish);
true
}
}
impl Uri { impl Uri {
pub fn new(parts: Vec<&str>) -> Self { pub fn new(parts: Vec<&str>) -> Self {
Self { Self {
raw: "/".to_owned() + &parts.join("/"),
parts: parts.into_iter().map(UrlEncodeData::from_raw).collect(), parts: parts.into_iter().map(UrlEncodeData::from_raw).collect(),
} }
} }
...@@ -28,6 +43,18 @@ impl Uri { ...@@ -28,6 +43,18 @@ impl Uri {
} }
true true
} }
pub(crate) fn to_pretty_print_string(&self) -> String {
if self.parts.is_empty() {
"/".to_string()
} else {
let url = self
.parts
.iter()
.map(|part| part.encoded())
.collect::<Vec<_>>();
"/".to_string() + &url.join("/")
}
}
} }
impl RawUri { impl RawUri {
...@@ -35,7 +62,7 @@ impl RawUri { ...@@ -35,7 +62,7 @@ impl RawUri {
let mut result = Self { let mut result = Self {
infinte_end: false, infinte_end: false,
parts: Vec::with_capacity(parts.len()), parts: Vec::with_capacity(parts.len()),
raw_string: "/".to_owned() + &parts.join("/"), raw_string: parts.join("/"),
}; };
for part in parts { for part in parts {
if part.starts_with('<') && part.ends_with("..>") { if part.starts_with('<') && part.ends_with("..>") {
...@@ -52,15 +79,15 @@ impl RawUri { ...@@ -52,15 +79,15 @@ impl RawUri {
} }
result result
} }
pub fn compare_uri(self, uri: &Uri) -> bool { pub fn compare_uri(&self, uri: &Uri) -> bool {
let mut iter_comp = uri.parts.iter(); let mut iter_comp = uri.parts.iter();
let mut counter = 0; if uri.parts().len() != self.parts.len() && !self.infinte_end {
return false;
}
for element in self.parts.iter() { for element in self.parts.iter() {
counter += 1;
let Some(compare_element) = iter_comp.next() else { let Some(compare_element) = iter_comp.next() else {
return false; return false;
}; };
if *element == RawUriElement::Variable { if *element == RawUriElement::Variable {
continue; continue;
} }
...@@ -72,11 +99,19 @@ impl RawUri { ...@@ -72,11 +99,19 @@ impl RawUri {
return false; return false;
} }
} }
if counter > self.parts.len() && !self.infinte_end { if uri.parts.len() > self.parts.len() && self.infinte_end {
return false; return true;
} }
true true
} }
pub(crate) fn to_pretty_print_string(&self, is_after: &Uri) -> String {
let is_after = is_after.to_pretty_print_string();
if is_after == "/" {
format!("\x1b[34;4m/\x1b[24m{}\x1b[0m", self)
} else {
format!("\x1b[34;4m{is_after}/\x1b[24m{self}\x1b[0m")
}
}
} }
impl std::fmt::Display for RawUri { impl std::fmt::Display for RawUri {
...@@ -87,23 +122,22 @@ impl std::fmt::Display for RawUri { ...@@ -87,23 +122,22 @@ impl std::fmt::Display for RawUri {
impl std::fmt::Display for Uri { impl std::fmt::Display for Uri {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let url = self if self.parts.is_empty() {
.parts write!(f, "/")
.iter() } else {
.map(|part| part.encoded()) let url = self
.collect::<Vec<_>>(); .parts
write!(f, "/{}", url.join("/")) .iter()
.map(|part| part.encoded())
.collect::<Vec<_>>();
write!(f, "{}", url.join("/"))
}
} }
} }
impl FromStr for Uri { impl FromStr for Uri {
type Err = ParseUriError; type Err = ParseUriError;
fn from_str(s: &str) -> Result<Self, Self::Err> { fn from_str(s: &str) -> Result<Self, Self::Err> {
if s == "/" {
return Ok(Self {
parts: vec![UrlEncodeData::from_encoded("").unwrap()],
});
}
let split = s.split('/'); let split = s.split('/');
let mut result = Vec::new(); let mut result = Vec::new();
for sub in split { for sub in split {
...@@ -116,7 +150,10 @@ impl FromStr for Uri { ...@@ -116,7 +150,10 @@ impl FromStr for Uri {
UrlEncodeData::from_raw(sub) UrlEncodeData::from_raw(sub)
}); });
} }
Ok(Self { parts: result }) Ok(Self {
parts: result,
raw: s.to_string(),
})
} }
} }
...@@ -127,7 +164,7 @@ impl FromStr for RawUri { ...@@ -127,7 +164,7 @@ impl FromStr for RawUri {
let mut result = Self { let mut result = Self {
infinte_end: false, infinte_end: false,
parts: Vec::new(), parts: Vec::new(),
raw_string: parts.join("/"), raw_string: s.to_string(),
}; };
for part in parts { for part in parts {
if part.is_empty() { if part.is_empty() {
...@@ -145,6 +182,7 @@ impl FromStr for RawUri { ...@@ -145,6 +182,7 @@ impl FromStr for RawUri {
.parts .parts
.push(RawUriElement::Name(UrlEncodeData::from_raw(part))) .push(RawUriElement::Name(UrlEncodeData::from_raw(part)))
} }
println!("{:?}", result);
Ok(result) Ok(result)
} }
} }
......
...@@ -5,7 +5,8 @@ use http::handling::{ ...@@ -5,7 +5,8 @@ use http::handling::{
response::{Response, Outcome, Status}, response::{Response, Outcome, Status},
file_handlers::NamedFile}; file_handlers::NamedFile};
fn static_files_handler(request: Request<>, _data: Data) -> Outcome<Response, Status, Data> { fn static_files_handler(request: Request, _data: Data) -> Outcome<Response, Status, Data> {
println!("{:?} {}", request.uri, request.uri);
let response = static_files(&request.uri.to_string()); let response = static_files(&request.uri.to_string());
let response = match response { let response = match response {
Ok(dat) => Response { Ok(dat) => Response {
...@@ -56,7 +57,7 @@ async fn main() { ...@@ -56,7 +57,7 @@ async fn main() {
format: None, format: None,
handler: static_files_handler, handler: static_files_handler,
name: Some("static files"), name: Some("static files"),
uri: "".try_into().unwrap(), uri: "<file..>".try_into().unwrap(),
method: Method::Get, method: Method::Get,
rank: 0 rank: 0
}; };
......
...@@ -8,7 +8,7 @@ ...@@ -8,7 +8,7 @@
<body> <body>
<header> <header>
<nav> <nav>
<div>LOGO</div> <div><img src="/favicon.ico" alt="ICON" width="32" height="32" /></div>
<div> <div>
<div>Dashboard</div> <div>Dashboard</div>
<div>Books</div> <div>Books</div>
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment