impl http body + fix start line unit tests

This commit is contained in:
landrigun 2023-02-15 11:11:55 +00:00
parent 9332ae0d5d
commit 6cadabb483
5 changed files with 55 additions and 3 deletions

View File

@ -6,5 +6,6 @@ edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies] [dependencies]
json = "0.12.4"
lazy_static = "1.4.0" lazy_static = "1.4.0"
regex = "1" regex = "1"

46
src/body.rs Normal file
View File

@ -0,0 +1,46 @@
const NULL_CHAR: &'static str = "\0";
#[derive(Debug)]
pub struct HTTPBody {
data: json::JsonValue,
}
/// HTTPBody represents an HTTP request body
/// for simplicity, only json body is allowed
impl HTTPBody {
fn new(data: json::JsonValue) -> HTTPBody {
HTTPBody { data }
}
pub fn get_data(&self) -> &json::JsonValue {
&self.data
}
}
impl TryFrom<&str> for HTTPBody {
type Error = String;
fn try_from(body: &str) -> Result<HTTPBody, Self::Error> {
let body = body.replace(NULL_CHAR, "");
match json::parse(&body) {
Ok(v) => Ok(HTTPBody::new(v)),
Err(e) => Err(format!("during request body parsing details={}", e)),
}
}
}
#[test]
fn test_from_str() {
let test_cases: [(&str, bool); 2] = [
(r#"{"access_token":"toto","refresh_token":"tutu"}"#, true),
("", false),
];
for (value, is_valid) in test_cases {
let res = HTTPBody::try_from(value);
if is_valid {
assert!(res.is_ok());
continue;
}
assert!(res.is_err());
}
}

View File

@ -4,8 +4,10 @@
//! see: https://developer.mozilla.org/en-US/docs/Web/HTTP/Messages //! see: https://developer.mozilla.org/en-US/docs/Web/HTTP/Messages
//! NOTE: only few parts of the specification has been implemented //! NOTE: only few parts of the specification has been implemented
mod body;
mod start_line; mod start_line;
mod version; mod version;
pub use body::HTTPBody;
pub use start_line::HTTPStartLine; pub use start_line::HTTPStartLine;
pub use version::HTTPVersion; pub use version::HTTPVersion;

View File

@ -25,7 +25,7 @@ impl<'a> HTTPStartLine<'a> {
fn parse(start_line: &'a str) -> Result<Self, &str> { fn parse(start_line: &'a str) -> Result<Self, &str> {
let parts: Vec<&str> = start_line.split(" ").collect(); let parts: Vec<&str> = start_line.split(" ").collect();
if parts.len() < 3 { if parts.len() != 3 {
return Err("unable to parse the start correctly"); return Err("unable to parse the start correctly");
} }
@ -92,8 +92,11 @@ fn test_parse() {
assert_eq!(expect.method, st.method); assert_eq!(expect.method, st.method);
assert_eq!(expect.target, st.target); assert_eq!(expect.target, st.target);
assert_eq!(expect.target, st.target); assert_eq!(expect.version, st.version);
continue;
} }
assert!(res.is_err());
} }
} }

View File

@ -1,4 +1,4 @@
#[derive(Debug)] #[derive(Debug, PartialEq)]
pub enum HTTPVersion { pub enum HTTPVersion {
Http1_0, Http1_0,
Http1_1, Http1_1,