Update uri parser to handle different accepted uri lengths

This commit is contained in:
flyingscorpio@clevo 2023-01-08 14:44:06 +01:00
parent 24bd6e50ef
commit b2da1dcb6a

View file

@ -1,6 +1,7 @@
//! Holds the elements pertaining to Ear, a listener object.
use core::str::Split;
use std::fmt::Display;
use std::io::{prelude::*, BufReader};
use std::net::{TcpListener, TcpStream};
@ -25,6 +26,12 @@ pub struct Request {
#[derive(Debug)]
pub struct ReqParseError(String);
impl Display for ReqParseError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.0)
}
}
impl Ear {
pub fn new() -> Self {
Self {
@ -51,7 +58,7 @@ impl Ear {
match parse_uri(&req) {
Ok(req) => handle_request(req, sender),
Err(req) => sender.send_bad_request(""),
Err(req) => sender.send_bad_request(format!("{}", req)),
};
}
}
@ -79,19 +86,22 @@ fn parse_uri(full_request: &str) -> Result<Request, ReqParseError> {
.filter(|val| !val.is_empty())
.collect::<Vec<&str>>();
if uri.len() != 3 || uri[0] != "api" {
Err(ReqParseError("Malformed URI".to_string()))
} else {
let section = uri[1].to_string();
let requested_data = uri[2].to_string();
if uri.is_empty() || uri[0] != "api" {
return Err(ReqParseError("Malformed URI".to_string()));
}
let request = Request {
match uri.len() {
2 => Ok(Request {
method,
section,
requested_data,
};
Ok(request)
section: uri[1].to_string(),
requested_data: "".to_string(),
}),
3 => Ok(Request {
method,
section: uri[1].to_string(),
requested_data: uri[2].to_string(),
}),
_ => Err(ReqParseError("Malformed URI".to_string())),
}
}