freechat/json-api/src/http.rs

37 lines
1.0 KiB
Rust

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)
}
#[inline]
pub fn extract_uid(values: &Value) -> u64 {
// pulling 'id' from user params is safe because the
// auth modules guarantees this to be there already
values.get("id").unwrap().as_u64().unwrap()
}