From b2da1dcb6a38ad4b6a5fccf9078cd5489ea8d516 Mon Sep 17 00:00:00 2001 From: "flyingscorpio@clevo" Date: Sun, 8 Jan 2023 14:44:06 +0100 Subject: [PATCH] Update uri parser to handle different accepted uri lengths --- src/ear.rs | 34 ++++++++++++++++++++++------------ 1 file changed, 22 insertions(+), 12 deletions(-) diff --git a/src/ear.rs b/src/ear.rs index 1339cb3..17e50ec 100644 --- a/src/ear.rs +++ b/src/ear.rs @@ -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 { .filter(|val| !val.is_empty()) .collect::>(); - 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())), } }