From e0d72b08cfa3658fa115b53f254243b82016a819 Mon Sep 17 00:00:00 2001 From: landrigun Date: Fri, 9 Sep 2022 14:02:16 +0100 Subject: [PATCH] feat: #1 impl an http body parser --- Cargo.lock | 7 ++++++ Cargo.toml | 1 + src/handlers/request.rs | 49 ++++++++++++++++++++++++++++++++++++++++- 3 files changed, 56 insertions(+), 1 deletion(-) diff --git a/Cargo.lock b/Cargo.lock index 0f7bf71..96a7984 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -274,6 +274,12 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "json" +version = "0.12.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "078e285eafdfb6c4b434e0d31e8cfcb5115b651496faca5749b88fafd4f23bfd" + [[package]] name = "kv-log-macro" version = "1.0.7" @@ -366,6 +372,7 @@ name = "simple-auth" version = "0.1.0" dependencies = [ "async-std", + "json", ] [[package]] diff --git a/Cargo.toml b/Cargo.toml index 8025190..6a3e1a1 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -6,6 +6,7 @@ edition = "2021" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] +json = "0.12.4" [dependencies.async-std] version = "1.6" diff --git a/src/handlers/request.rs b/src/handlers/request.rs index 583508c..1889967 100644 --- a/src/handlers/request.rs +++ b/src/handlers/request.rs @@ -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 for HTTPVersion { @@ -72,6 +75,31 @@ impl Into 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 { + 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), + } + } +}