feat: #1 impl an http body parser

This commit is contained in:
2022-09-09 14:02:16 +01:00
parent 3afe437143
commit e0d72b08cf
3 changed files with 56 additions and 1 deletions
+48 -1
View File
@@ -1,11 +1,14 @@
//! request handles properly the incoming request
//! it will parse the request according to the HTTP message specifications
//! see: https://developer.mozilla.org/en-US/docs/Web/HTTP/Messages
//! NOTE: only few parts of the specification has been implemented
use json;
#[derive(Debug)]
pub enum HTTPVersion {
Http1,
//http2,
//Http2,
}
impl Into<String> for HTTPVersion {
@@ -72,6 +75,31 @@ impl Into<String> for HTTPStartLine {
}
}
/// HTTPBody represents http request body
/// for simplicity, only json body are accepted
pub struct HTTPBody {
data: json::JsonValue,
}
impl HTTPBody {
fn new(data: json::JsonValue) -> HTTPBody {
HTTPBody { data }
}
}
impl TryFrom<&str> for HTTPBody {
type Error = String;
fn try_from(body: &str) -> Result<HTTPBody, Self::Error> {
match json::parse(body) {
Ok(v) => Ok(HTTPBody::new(v)),
Err(e) => Err(format!(
"error occurred during request body parsing err={}",
e
)),
}
}
}
/// Request defined the HTTP request
#[derive(Debug)]
pub struct HTTPRequest {
@@ -156,3 +184,22 @@ fn test_handle_request() {
assert_eq!(http_request.is_valid(), is_valid);
}
}
#[test]
fn test_http_body() {
let test_cases: [(&str, bool); 3] = [
("hello, how are you ?", false),
("qsdfqsdffqsdffsq", false),
(
r#"{"access_token":"AAAAAAAAAAAA.BBBBBBBBBB.CCCCCCCCCC","refresh_token": "DDDDDDDDDDD.EEEEEEEEEEE.FFFFF"}"#,
true,
),
];
for (body, is_valid) in test_cases {
match HTTPBody::try_from(body) {
Ok(_) => assert!(is_valid),
Err(_) => assert!(!is_valid),
}
}
}