From 808cd3ee77a5254f80e32f30ca6b759afdc3b44a Mon Sep 17 00:00:00 2001 From: landrigun Date: Thu, 13 Oct 2022 10:33:11 +0000 Subject: [PATCH] impl an HTTPMessage corresponding to the JSON response body --- src/http/message.rs | 77 +++++++++++++++++++++++++++++++++++++++++++++ src/http/mod.rs | 2 ++ 2 files changed, 79 insertions(+) create mode 100644 src/http/message.rs diff --git a/src/http/message.rs b/src/http/message.rs new file mode 100644 index 0000000..58f8c4f --- /dev/null +++ b/src/http/message.rs @@ -0,0 +1,77 @@ +use json; +use std::collections::HashMap; + +const JSON_DELIMITER: &'static str = ","; + +/// `HashMap` wrapper, represents the JSON response body +pub struct HTTPMessage { + message: HashMap, +} + +impl Default for HTTPMessage { + fn default() -> Self { + HTTPMessage { + message: HashMap::new(), + } + } +} + +/// try to convert `HTTPMessage` in `json::JsonValue` +impl TryInto for HTTPMessage { + type Error = String; + fn try_into(self) -> Result { + let message = format!(r#"{{{}}}"#, self.build_json()); + println!("message: {}", message); + match json::parse(&message) { + Ok(r) => Ok(r), + Err(e) => Err(format!( + "unable to parse the HTTPMessage correctly: {}, err={}", + message, e + )), + } + } +} + +impl HTTPMessage { + fn put(&mut self, key: &str, value: &str) { + self.message.insert(key.to_string(), value.to_string()); + } + + /// loops over all the HashMap keys, builds a JSON key value for each one and join them with `JSON_DELIMITER` + fn build_json(self) -> String { + let unstruct: Vec = self + .message + .keys() + .map(|k| format!(r#""{}":{:?}"#, k, self.message.get(k).unwrap())) + .collect(); + let joined = unstruct.join(JSON_DELIMITER); + joined + } +} + +#[test] +fn test_message() { + let mut http_message = HTTPMessage::default(); + http_message.put("username", "toto"); + http_message.put("password", "tata"); + + let mut json_result: Result = http_message.try_into(); + assert!(json_result.is_ok()); + + let mut json = json_result.unwrap(); + assert!(json.has_key("username")); + assert!(json.has_key("password")); + + let empty_http_message = HTTPMessage::default(); + json_result = empty_http_message.try_into(); + assert!(json_result.is_ok()); + + json = json_result.unwrap(); + assert_eq!("{}", json.dump().to_string()); + + let mut bad_http_message = HTTPMessage::default(); + bad_http_message.put("\"", ""); + + json_result = bad_http_message.try_into(); + assert!(json_result.is_err()); +} diff --git a/src/http/mod.rs b/src/http/mod.rs index f9dbf7c..8431d8f 100644 --- a/src/http/mod.rs +++ b/src/http/mod.rs @@ -1,9 +1,11 @@ //! http module includes tools to parse an HTTP request and build and HTTP response +pub mod message; pub mod request; pub mod response; pub mod router; +pub use message::HTTPMessage; pub use request::HTTPRequest; pub use response::{HTTPResponse, HTTPStatusCode}; pub use router::ROUTER;