1
0
Fork 0
mirror of https://gitlab.com/msrd0/gotham-restful.git synced 2025-04-19 22:44:38 +00:00

response can have a different mime type than json

This commit is contained in:
Dominic 2019-10-19 20:23:25 +02:00
parent bb5f58e97d
commit 656595711c
Signed by: msrd0
GPG key ID: DCC8C247452E98F9
2 changed files with 90 additions and 39 deletions

View file

@ -6,12 +6,40 @@ use serde::Serialize;
use serde_json::error::Error as SerdeJsonError; use serde_json::error::Error as SerdeJsonError;
use std::error::Error; use std::error::Error;
pub struct Response
{
pub status : StatusCode,
pub body : String,
pub mime : Option<Mime>
}
impl Response
{
pub fn json(status : StatusCode, body : String) -> Self
{
Self {
status,
body,
mime: Some(APPLICATION_JSON)
}
}
pub fn no_content() -> Self
{
Self {
status: StatusCode::NO_CONTENT,
body: String::new(),
mime: None
}
}
}
/// A trait provided to convert a resource's result to json. /// A trait provided to convert a resource's result to json.
pub trait ResourceResult pub trait ResourceResult
{ {
/// Turn this into a response that can be returned to the browser. This api will likely /// Turn this into a response that can be returned to the browser. This api will likely
/// change in the future. /// change in the future.
fn to_response(&self) -> Result<(StatusCode, String), SerdeJsonError>; fn to_response(&self) -> Result<Response, SerdeJsonError>;
/// Return a list of supported mime types. /// Return a list of supported mime types.
fn accepted_types() -> Option<Vec<Mime>> fn accepted_types() -> Option<Vec<Mime>>
@ -59,13 +87,13 @@ impl<T : ToString> From<T> for ResourceError
impl<R : ResourceType, E : Error> ResourceResult for Result<R, E> impl<R : ResourceType, E : Error> ResourceResult for Result<R, E>
{ {
fn to_response(&self) -> Result<(StatusCode, String), SerdeJsonError> fn to_response(&self) -> Result<Response, SerdeJsonError>
{ {
Ok(match self { Ok(match self {
Ok(r) => (StatusCode::OK, serde_json::to_string(r)?), Ok(r) => Response::json(StatusCode::OK, serde_json::to_string(r)?),
Err(e) => { Err(e) => {
let err : ResourceError = e.into(); let err : ResourceError = e.into();
(StatusCode::INTERNAL_SERVER_ERROR, serde_json::to_string(&err)?) Response::json(StatusCode::INTERNAL_SERVER_ERROR, serde_json::to_string(&err)?)
} }
}) })
} }
@ -119,9 +147,9 @@ impl<T> From<T> for Success<T>
impl<T : ResourceType> ResourceResult for Success<T> impl<T : ResourceType> ResourceResult for Success<T>
{ {
fn to_response(&self) -> Result<(StatusCode, String), SerdeJsonError> fn to_response(&self) -> Result<Response, SerdeJsonError>
{ {
Ok((StatusCode::OK, serde_json::to_string(&self.0)?)) Ok(Response::json(StatusCode::OK, serde_json::to_string(&self.0)?))
} }
fn accepted_types() -> Option<Vec<Mime>> fn accepted_types() -> Option<Vec<Mime>>
@ -169,9 +197,9 @@ impl From<()> for NoContent
impl ResourceResult for NoContent impl ResourceResult for NoContent
{ {
/// This will always be a _204 No Content_ together with an empty string. /// This will always be a _204 No Content_ together with an empty string.
fn to_response(&self) -> Result<(StatusCode, String), SerdeJsonError> fn to_response(&self) -> Result<Response, SerdeJsonError>
{ {
Ok((Self::default_status(), "".to_string())) Ok(Response::no_content())
} }
/// Returns the schema of the `()` type. /// Returns the schema of the `()` type.
@ -191,15 +219,15 @@ impl ResourceResult for NoContent
impl<E : Error> ResourceResult for Result<NoContent, E> impl<E : Error> ResourceResult for Result<NoContent, E>
{ {
fn to_response(&self) -> Result<(StatusCode, String), SerdeJsonError> fn to_response(&self) -> Result<Response, SerdeJsonError>
{ {
Ok(match self { match self {
Ok(_) => (Self::default_status(), "".to_string()), Ok(nc) => nc.to_response(),
Err(e) => { Err(e) => {
let err : ResourceError = e.into(); let err : ResourceError = e.into();
(StatusCode::INTERNAL_SERVER_ERROR, serde_json::to_string(&err)?) Ok(Response::json(StatusCode::INTERNAL_SERVER_ERROR, serde_json::to_string(&err)?))
}
} }
})
} }
#[cfg(feature = "openapi")] #[cfg(feature = "openapi")]
@ -236,44 +264,49 @@ mod test
fn resource_result_ok() fn resource_result_ok()
{ {
let ok : Result<Msg, MsgError> = Ok(Msg::default()); let ok : Result<Msg, MsgError> = Ok(Msg::default());
let (status, json) = ok.to_response().expect("didn't expect error response"); let res = ok.to_response().expect("didn't expect error response");
assert_eq!(status, StatusCode::OK); assert_eq!(res.status, StatusCode::OK);
assert_eq!(json, r#"{"msg":""}"#); assert_eq!(res.body, r#"{"msg":""}"#);
assert_eq!(res.mime, Some(APPLICATION_JSON));
} }
#[test] #[test]
fn resource_result_err() fn resource_result_err()
{ {
let err : Result<Msg, MsgError> = Err(MsgError::default()); let err : Result<Msg, MsgError> = Err(MsgError::default());
let (status, json) = err.to_response().expect("didn't expect error response"); let res = err.to_response().expect("didn't expect error response");
assert_eq!(status, StatusCode::INTERNAL_SERVER_ERROR); assert_eq!(res.status, StatusCode::INTERNAL_SERVER_ERROR);
assert_eq!(json, format!(r#"{{"error":true,"message":"{}"}}"#, err.unwrap_err())); assert_eq!(res.body, format!(r#"{{"error":true,"message":"{}"}}"#, err.unwrap_err()));
assert_eq!(res.mime, Some(APPLICATION_JSON));
} }
#[test] #[test]
fn success_always_successfull() fn success_always_successfull()
{ {
let success : Success<Msg> = Msg::default().into(); let success : Success<Msg> = Msg::default().into();
let (status, json) = success.to_response().expect("didn't expect error response"); let res = success.to_response().expect("didn't expect error response");
assert_eq!(status, StatusCode::OK); assert_eq!(res.status, StatusCode::OK);
assert_eq!(json, r#"{"msg":""}"#); assert_eq!(res.body, r#"{"msg":""}"#);
assert_eq!(res.mime, Some(APPLICATION_JSON));
} }
#[test] #[test]
fn no_content_has_empty_json() fn no_content_has_empty_response()
{ {
let no_content = NoContent::default(); let no_content = NoContent::default();
let (status, json) = no_content.to_response().expect("didn't expect error response"); let res = no_content.to_response().expect("didn't expect error response");
assert_eq!(status, StatusCode::NO_CONTENT); assert_eq!(res.status, StatusCode::NO_CONTENT);
assert_eq!(json, ""); assert_eq!(res.body, "");
assert_eq!(res.mime, None);
} }
#[test] #[test]
fn no_content_result() fn no_content_result()
{ {
let no_content = NoContent::default(); let no_content : Result<NoContent, MsgError> = Ok(NoContent::default());
let res_def = no_content.to_response().expect("didn't expect error response"); let res = no_content.to_response().expect("didn't expect error response");
let res_err = Result::<NoContent, MsgError>::Ok(no_content).to_response().expect("didn't expect error response"); assert_eq!(res.status, StatusCode::NO_CONTENT);
assert_eq!(res_def, res_err); assert_eq!(res.body, "");
assert_eq!(res.mime, None);
} }
} }

View file

@ -1,6 +1,6 @@
use crate::{ use crate::{
resource::*, resource::*,
result::{ResourceError, ResourceResult}, result::{ResourceError, ResourceResult, Response},
ResourceType, ResourceType,
StatusCode StatusCode
}; };
@ -14,7 +14,7 @@ use futures::{
use gotham::{ use gotham::{
extractor::QueryStringExtractor, extractor::QueryStringExtractor,
handler::{HandlerFuture, IntoHandlerError}, handler::{HandlerFuture, IntoHandlerError},
helpers::http::response::create_response, helpers::http::response::{create_empty_response, create_response},
pipeline::chain::PipelineHandleChain, pipeline::chain::PipelineHandleChain,
router::{ router::{
builder::*, builder::*,
@ -23,7 +23,11 @@ use gotham::{
}, },
state::{FromState, State} state::{FromState, State}
}; };
use hyper::Body; use hyper::{
header::CONTENT_TYPE,
Body,
Method
};
use mime::{Mime, APPLICATION_JSON}; use mime::{Mime, APPLICATION_JSON};
use serde::de::DeserializeOwned; use serde::de::DeserializeOwned;
use std::panic::RefUnwindSafe; use std::panic::RefUnwindSafe;
@ -108,6 +112,20 @@ pub trait DrawResourceRoutes
Handler : ResourceDelete<ID, Res>; Handler : ResourceDelete<ID, Res>;
} }
fn response_from(res : Response, state : &State) -> hyper::Response<Body>
{
let mut r = create_empty_response(state, res.status);
if let Some(mime) = res.mime
{
r.headers_mut().insert(CONTENT_TYPE, mime.as_ref().parse().unwrap());
}
if Method::borrow_from(state) != Method::HEAD
{
*r.body_mut() = res.body.into();
}
r
}
fn to_handler_future<F, R>(mut state : State, get_result : F) -> Box<HandlerFuture> fn to_handler_future<F, R>(mut state : State, get_result : F) -> Box<HandlerFuture>
where where
F : FnOnce(&mut State) -> R, F : FnOnce(&mut State) -> R,
@ -115,9 +133,9 @@ where
{ {
let res = get_result(&mut state).to_response(); let res = get_result(&mut state).to_response();
match res { match res {
Ok((status, body)) => { Ok(res) => {
let res = create_response(&state, status, APPLICATION_JSON, body); let r = response_from(res, &state);
Box::new(ok((state, res))) Box::new(ok((state, r)))
}, },
Err(e) => Box::new(err((state, e.into_handler_error()))) Err(e) => Box::new(err((state, e.into_handler_error())))
} }
@ -154,9 +172,9 @@ where
let res = get_result(&mut state, body).to_response(); let res = get_result(&mut state, body).to_response();
match res { match res {
Ok((status, body)) => { Ok(res) => {
let res = create_response(&state, status, APPLICATION_JSON, body); let r = response_from(res, &state);
ok((state, res)) ok((state, r))
}, },
Err(e) => err((state, e.into_handler_error())) Err(e) => err((state, e.into_handler_error()))
} }