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
This commit is contained in:
shockrah 2021-01-23 16:09:04 -08:00
parent 5a27ef07f1
commit 085bad75fd
2 changed files with 31 additions and 15 deletions

30
server-api/src/http.rs Normal file
View File

@ -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<Body>, 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<Value, serde_json::error::Error> {
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)
}

View File

@ -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<Value, serde_json::error::Error> {
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)
}