use std::marker::PhantomData; use std::result::Result as StdResult; use actix::Actor; use futures::Future; use error::Error; use context::HttpContext; use httprequest::HttpRequest; use httpresponse::HttpResponse; use task::{Task, IoContext}; /// 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: Into; /// Handle request fn handle(&self, req: HttpRequest) -> Self::Result; } /// Handler for Fn() impl Handler for F where F: Fn(HttpRequest) -> R + 'static, R: Into + 'static { type Result = R; fn handle(&self, req: HttpRequest) -> R { (self)(req) } } /// Represents response process. pub struct Reply(ReplyItem); 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 reply>(response: R) -> Reply { Reply(ReplyItem::Message(response.into())) } pub fn into(self, task: &mut Task) { match self.0 { ReplyItem::Message(msg) => { task.reply(msg) }, ReplyItem::Actor(ctx) => { task.context(ctx) } ReplyItem::Future(fut) => { task.async(fut) } } } } impl> From for Reply { fn from(item: T) -> Self { Reply(ReplyItem::Message(item.into())) } } impl> From> for Reply { fn from(res: StdResult) -> Self { match res { Ok(val) => val, Err(err) => err.into().into(), } } } impl>, S: 'static> From> for Reply { fn from(item: HttpContext) -> Self { Reply(ReplyItem::Actor(Box::new(item))) } } /// Trait defines object that could be regestered as resource route pub(crate) trait RouteHandler: 'static { /// Handle request fn handle(&self, req: HttpRequest, task: &mut Task); } /// Route handler wrapper for Handler pub(crate) struct WrapHandler where H: Handler, R: Into, S: 'static, { h: H, s: PhantomData, } impl WrapHandler where H: Handler, R: Into, S: 'static, { pub fn new(h: H) -> Self { WrapHandler{h: h, s: PhantomData} } } impl RouteHandler for WrapHandler where H: Handler, R: Into + 'static, S: 'static, { fn handle(&self, req: HttpRequest, task: &mut Task) { self.h.handle(req).into().into(task) } } /// Async route handler pub(crate) struct StreamHandler where F: Fn(HttpRequest) -> R + 'static, R: Future + 'static, S: 'static, { f: Box, s: PhantomData, } impl StreamHandler where F: Fn(HttpRequest) -> R + 'static, R: Future + 'static, S: 'static, { pub fn new(f: F) -> Self { StreamHandler{f: Box::new(f), s: PhantomData} } } impl RouteHandler for StreamHandler where F: Fn(HttpRequest) -> R + 'static, R: Future + 'static, S: 'static, { fn handle(&self, req: HttpRequest, task: &mut Task) { task.async((self.f)(req)) } }