use crate::Result;
use std::fs;
#[derive(Debug, Clone)]
pub struct Request {
pub selector: String,
pub query: String,
pub root: String,
pub host: String,
pub port: u16,
}
impl Request {
pub fn from(host: &str, port: u16, root: &str) -> Result<Request> {
Ok(Request {
host: host.into(),
port,
root: fs::canonicalize(root)?.to_string_lossy().into(),
selector: String::new(),
query: String::new(),
})
}
pub fn file_path(&self) -> String {
format!(
"{}/{}",
self.root.to_string().trim_end_matches('/'),
self.selector.replace("..", ".").trim_start_matches('/')
)
}
pub fn relative_file_path(&self) -> String {
self.file_path().replace(&self.root, "")
}
pub fn parse_request(&mut self, line: &str) {
self.query.clear();
self.selector.clear();
if let Some((i, _)) = line
.chars()
.enumerate()
.find(|&(_, c)| c == '\t' || c == '?')
{
if line.len() > i {
self.query.push_str(&line[i + 1..]);
self.selector.push_str(&line[..i]);
return;
}
}
self.selector.push_str(line);
if let Some(last) = self.selector.chars().last() {
if last == '/' {
self.selector.pop();
}
}
}
}