mirror of
https://github.com/actix/actix-extras.git
synced 2025-06-25 09:59:21 +02:00
added Json response support
This commit is contained in:
@ -34,7 +34,8 @@ extern crate percent_encoding;
|
||||
extern crate actix;
|
||||
extern crate h2 as http2;
|
||||
|
||||
// extern crate redis_async;
|
||||
#[cfg(test)]
|
||||
#[macro_use] extern crate serde_derive;
|
||||
|
||||
#[cfg(feature="tls")]
|
||||
extern crate native_tls;
|
||||
@ -81,7 +82,7 @@ pub use application::Application;
|
||||
pub use httprequest::{HttpRequest, UrlEncoded};
|
||||
pub use httpresponse::HttpResponse;
|
||||
pub use payload::{Payload, PayloadItem};
|
||||
pub use route::{Reply, FromRequest};
|
||||
pub use route::{Reply, Json, FromRequest};
|
||||
pub use resource::Resource;
|
||||
pub use recognizer::Params;
|
||||
pub use server::HttpServer;
|
||||
|
36
src/route.rs
36
src/route.rs
@ -2,6 +2,8 @@ use std::marker::PhantomData;
|
||||
|
||||
use actix::Actor;
|
||||
use futures::Future;
|
||||
use serde_json;
|
||||
use serde::Serialize;
|
||||
|
||||
use error::Error;
|
||||
use context::{HttpContext, IoContext};
|
||||
@ -223,3 +225,37 @@ impl<S, R, F> RouteHandler<S> for AsyncHandler<S, R, F>
|
||||
Reply::async((self.f)(req))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
pub struct Json<T: Serialize> (pub T);
|
||||
|
||||
impl<T: Serialize> FromRequest for Json<T> {
|
||||
type Item = HttpResponse;
|
||||
type Error = Error;
|
||||
|
||||
fn from_request(self, _: HttpRequest) -> Result<HttpResponse, Error> {
|
||||
let body = serde_json::to_string(&self.0)?;
|
||||
|
||||
Ok(HttpResponse::Ok()
|
||||
.content_type("application/json")
|
||||
.body(body)?)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use http::header;
|
||||
|
||||
#[derive(Serialize)]
|
||||
struct MyObj {
|
||||
name: &'static str,
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_json() {
|
||||
let json = Json(MyObj{name: "test"});
|
||||
let resp = json.from_request(HttpRequest::default()).unwrap();
|
||||
assert_eq!(resp.headers().get(header::CONTENT_TYPE).unwrap(), "application/json");
|
||||
}
|
||||
}
|
||||
|
Reference in New Issue
Block a user