use std::marker::PhantomData; use actix::Actor; use futures::Future; use serde_json; use serde::Serialize; use error::Error; use context::{HttpContext, IoContext}; use httprequest::HttpRequest; use httpresponse::HttpResponse; /// Trait defines object that could be regestered as route handler #[allow(unused_variables)] pub trait Handler: 'static { /// The type of value that handler will return. type Result: FromRequest; /// Handle request fn handle(&self, req: HttpRequest) -> Self::Result; } pub trait FromRequest { /// The associated item which can be returned. type Item: Into; /// The associated error which can be returned. type Error: Into; fn from_request(self, req: HttpRequest) -> Result; } /// Handler for Fn() impl Handler for F where F: Fn(HttpRequest) -> R + 'static, R: FromRequest + 'static { type Result = R; fn handle(&self, req: HttpRequest) -> R { (self)(req) } } /// Represents response process. pub struct Reply(ReplyItem); pub(crate) enum ReplyItem { Message(HttpResponse), Actor(Box), Future(Box>), } impl Reply { /// Create actor response pub fn actor(ctx: HttpContext) -> Reply where A: Actor>, S: 'static { Reply(ReplyItem::Actor(Box::new(ctx))) } /// Create async response pub fn async(fut: F) -> Reply where F: Future + 'static { Reply(ReplyItem::Future(Box::new(fut))) } /// Send response pub fn response>(response: R) -> Reply { Reply(ReplyItem::Message(response.into())) } pub(crate) fn into(self) -> ReplyItem { self.0 } } impl FromRequest for Reply { type Item = Reply; type Error = Error; fn from_request(self, _: HttpRequest) -> Result { Ok(self) } } impl FromRequest for HttpResponse { type Item = Reply; type Error = Error; fn from_request(self, _: HttpRequest) -> Result { Ok(Reply(ReplyItem::Message(self))) } } impl From for Reply { fn from(resp: HttpResponse) -> Reply { Reply(ReplyItem::Message(resp)) } } impl> FromRequest for Result { type Item = ::Item; type Error = Error; fn from_request(self, req: HttpRequest) -> Result { match self { Ok(val) => match val.from_request(req) { Ok(val) => Ok(val), Err(err) => Err(err.into()), }, Err(err) => Err(err.into()), } } } impl> From> for Reply { fn from(res: Result) -> Self { match res { Ok(val) => val, Err(err) => Reply(ReplyItem::Message(err.into().into())), } } } impl>, S: 'static> FromRequest for HttpContext { type Item = Reply; type Error = Error; fn from_request(self, _: HttpRequest) -> Result { Ok(Reply(ReplyItem::Actor(Box::new(self)))) } } impl>, S: 'static> From> for Reply { fn from(ctx: HttpContext) -> Reply { Reply(ReplyItem::Actor(Box::new(ctx))) } } impl FromRequest for Box> { type Item = Reply; type Error = Error; fn from_request(self, _: HttpRequest) -> Result { Ok(Reply(ReplyItem::Future(self))) } } /// Trait defines object that could be regestered as resource route pub(crate) trait RouteHandler: 'static { fn handle(&self, req: HttpRequest) -> Reply; } /// Route handler wrapper for Handler pub(crate) struct WrapHandler where H: Handler, R: FromRequest, S: 'static, { h: H, s: PhantomData, } impl WrapHandler where H: Handler, R: FromRequest, S: 'static, { pub fn new(h: H) -> Self { WrapHandler{h: h, s: PhantomData} } } impl RouteHandler for WrapHandler where H: Handler, R: FromRequest + 'static, S: 'static, { fn handle(&self, req: HttpRequest) -> Reply { let req2 = req.clone_without_state(); match self.h.handle(req).from_request(req2) { Ok(reply) => reply.into(), Err(err) => Reply::response(err.into()), } } } /// Async route handler pub(crate) struct AsyncHandler where F: Fn(HttpRequest) -> R + 'static, R: Future + 'static, S: 'static, { f: Box, s: PhantomData, } impl AsyncHandler where F: Fn(HttpRequest) -> R + 'static, R: Future + 'static, S: 'static, { pub fn new(f: F) -> Self { AsyncHandler{f: Box::new(f), s: PhantomData} } } impl RouteHandler for AsyncHandler where F: Fn(HttpRequest) -> R + 'static, R: Future + 'static, S: 'static, { fn handle(&self, req: HttpRequest) -> Reply { Reply::async((self.f)(req)) } } /// Json response helper /// /// The `Json` type allows you to respond with well-formed JSON data: simply return a value of /// type Json where T is the type of a structure to serialize into *JSON*. The /// type `T` must implement the `Serialize` trait from *serde*. /// /// ```rust /// # extern crate actix_web; /// # #[macro_use] extern crate serde_derive; /// # use actix_web::*; /// # /// #[derive(Serialize)] /// struct MyObj { /// name: String, /// } /// /// fn index(req: HttpRequest) -> Result> { /// Ok(Json(MyObj{name: req.match_info().query("name")?})) /// } /// # fn main() {} /// ``` pub struct Json (pub T); impl FromRequest for Json { type Item = HttpResponse; type Error = Error; fn from_request(self, _: HttpRequest) -> Result { 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"); } }