impl http body + fix start line unit tests
This commit is contained in:
parent
9332ae0d5d
commit
6cadabb483
@ -6,5 +6,6 @@ edition = "2021"
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
[dependencies]
|
||||
json = "0.12.4"
|
||||
lazy_static = "1.4.0"
|
||||
regex = "1"
|
||||
|
||||
46
src/body.rs
Normal file
46
src/body.rs
Normal 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());
|
||||
}
|
||||
}
|
||||
@ -4,8 +4,10 @@
|
||||
//! see: https://developer.mozilla.org/en-US/docs/Web/HTTP/Messages
|
||||
//! NOTE: only few parts of the specification has been implemented
|
||||
|
||||
mod body;
|
||||
mod start_line;
|
||||
mod version;
|
||||
|
||||
pub use body::HTTPBody;
|
||||
pub use start_line::HTTPStartLine;
|
||||
pub use version::HTTPVersion;
|
||||
|
||||
@ -25,7 +25,7 @@ impl<'a> HTTPStartLine<'a> {
|
||||
|
||||
fn parse(start_line: &'a str) -> Result<Self, &str> {
|
||||
let parts: Vec<&str> = start_line.split(" ").collect();
|
||||
if parts.len() < 3 {
|
||||
if parts.len() != 3 {
|
||||
return Err("unable to parse the start correctly");
|
||||
}
|
||||
|
||||
@ -92,8 +92,11 @@ fn test_parse() {
|
||||
|
||||
assert_eq!(expect.method, st.method);
|
||||
assert_eq!(expect.target, st.target);
|
||||
assert_eq!(expect.target, st.target);
|
||||
assert_eq!(expect.version, st.version);
|
||||
continue;
|
||||
}
|
||||
|
||||
assert!(res.is_err());
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@ -1,4 +1,4 @@
|
||||
#[derive(Debug)]
|
||||
#[derive(Debug, PartialEq)]
|
||||
pub enum HTTPVersion {
|
||||
Http1_0,
|
||||
Http1_1,
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user