Struct aitch::Json [−][src]
pub struct Json<T>(pub T);
A wrapper, indicating a type should be automatically (de)serialized from/to a HTTP request/response body.
This feature requires a dependency on serde
. This dependency is enabled by default, but can
be disabled by removing the optional serde
feature on the aitch
crate.
To use a type with this wrapper, it must implement both serde::de::DeserializeOwned
and
serde::Serialize
. This is because Json<T>
can be used in both request/response bodies, and
because chains of handlers may choose to serialize/deserialize the type back into a stream of
bytes in order to process the requests. (See the Body
trait for more information).
Examples
The following example accepts a request with a JSON payload, and uses this to construct a JSON response:
extern crate aitch; extern crate http; extern crate serde; #[macro_use] extern crate serde_derive; use aitch::servers::hyper::Server; use aitch::{middlewares, Json, Responder, ResponseBuilder, Result}; use http::Request; #[derive(Serialize, Deserialize)] struct ReqParameters { message: String, } #[derive(Serialize, Deserialize)] struct RespBody { message: String, } fn handler(req: Request<Json<ReqParameters>>, mut resp: ResponseBuilder) -> impl Responder { let req_params = req.into_body().json(); let message = format!("You sent '{}'", req_params.message); let body = RespBody { message }; resp.header(http::header::CONTENT_TYPE, "application/json") .body(Json(body)) }
Methods
impl<T> Json<T>
[src]
impl<T> Json<T>
Trait Implementations
impl<T> Body for Json<T> where
T: DeserializeOwned + Serialize + Send + 'static,
[src]
impl<T> Body for Json<T> where
T: DeserializeOwned + Serialize + Send + 'static,
type Future = AndThen<Concat2<BodyStream>, Result<Json<T>>, fn(_: Bytes) -> Result<Json<T>>>
fn from_stream(stream: BodyStream) -> Self::Future
[src]
fn from_stream(stream: BodyStream) -> Self::Future
Consume a [BodyStream
] and return a future which resolves to Self
. Read more
fn into_stream(self) -> BodyStream
[src]
fn into_stream(self) -> BodyStream
Consume Self
and returns a [BodyStream
]. Read more
fn into_body<OtherBody: Body>(self) -> OtherBody::Future
[src]
fn into_body<OtherBody: Body>(self) -> OtherBody::Future
Convenience function to convert from one type implementing Body
to another.