From 085bad75fd763bcbff1d81025d0236d5a9923c77 Mon Sep 17 00:00:00 2001 From: shockrah Date: Sat, 23 Jan 2021 16:09:04 -0800 Subject: [PATCH] Moving http relevant functions to a more proper module New json prepartion helper function http::set_json_body now public and usable. Code is straight ripped from working code so it should be fine though further testing still required --- server-api/src/http.rs | 30 ++++++++++++++++++++++++++++++ server-api/src/http_params.rs | 16 +--------------- 2 files changed, 31 insertions(+), 15 deletions(-) create mode 100644 server-api/src/http.rs diff --git a/server-api/src/http.rs b/server-api/src/http.rs new file mode 100644 index 0000000..f296771 --- /dev/null +++ b/server-api/src/http.rs @@ -0,0 +1,30 @@ +use serde_json::{self, Value}; +use hyper::http::HeaderValue; +use hyper::Response; +use hyper::Body; +use hyper::body::to_bytes; + +use std::u8; + +const APP_JSON_HEADER: &'static str = "application/json"; +const CONTENT_TYPE: &'static str = "Content-Type"; + +pub fn set_json_body(response: &mut Response, values: Value) { + response.headers_mut().insert( + CONTENT_TYPE, + HeaderValue::from_static(APP_JSON_HEADER)); + + *response.body_mut() = Body::from(values.to_string()); +} + +pub async fn parse_json_params(body_raw: &mut Body) -> Result { + let bytes: &[u8] = &*to_bytes(body_raw).await.unwrap(); // rarely fails + let values: Value; + if bytes.len() == 0 { + values = serde_json::from_str("{}")?; + } + else { + values = serde_json::from_slice(bytes)?; + } + Ok(values) +} \ No newline at end of file diff --git a/server-api/src/http_params.rs b/server-api/src/http_params.rs index aaaf99f..139597f 100644 --- a/server-api/src/http_params.rs +++ b/server-api/src/http_params.rs @@ -1,16 +1,2 @@ -use serde_json::{self, Value}; -use hyper::body::to_bytes; -use hyper::Body; -use std::u8; -pub async fn parse_params(body_raw: &mut Body) -> Result { - let bytes: &[u8] = &*to_bytes(body_raw).await.unwrap(); // rarely fails - let values: Value; - if bytes.len() == 0 { - values = serde_json::from_str("{}")?; - } - else { - values = serde_json::from_slice(bytes)?; - } - Ok(values) -} \ No newline at end of file +