1
0
Fork 0
mirror of https://github.com/actix/actix-web.git synced 2024-09-09 05:08:32 +00:00
actix-web/src/handler.rs

350 lines
9.1 KiB
Rust
Raw Normal View History

2017-10-07 04:48:14 +00:00
use std::marker::PhantomData;
2018-01-01 01:26:32 +00:00
use futures::future::{Future, ok, err};
2017-10-07 04:48:14 +00:00
2017-11-29 21:26:55 +00:00
use error::Error;
use httprequest::HttpRequest;
2017-10-24 06:25:32 +00:00
use httpresponse::HttpResponse;
2017-11-03 20:35:34 +00:00
2018-01-15 21:47:25 +00:00
/// Trait defines object that could be registered as route handler
2017-10-16 08:19:23 +00:00
#[allow(unused_variables)]
2017-11-29 21:26:55 +00:00
pub trait Handler<S>: 'static {
2017-11-29 23:07:49 +00:00
/// The type of value that handler will return.
2017-12-14 17:43:42 +00:00
type Result: Responder;
2017-11-29 21:26:55 +00:00
2017-10-10 06:07:32 +00:00
/// Handle request
2017-12-26 17:00:45 +00:00
fn handle(&mut self, req: HttpRequest<S>) -> Self::Result;
2017-10-07 04:48:14 +00:00
}
2017-12-14 17:43:42 +00:00
/// Trait implemented by types that generate responses for clients.
///
/// Types that implement this trait can be used as the return type of a handler.
pub trait Responder {
/// The associated item which can be returned.
type Item: Into<Reply>;
/// The associated error which can be returned.
type Error: Into<Error>;
2017-12-14 17:43:42 +00:00
/// Convert itself to `Reply` or `Error`.
fn respond_to(self, req: HttpRequest) -> Result<Self::Item, Self::Error>;
}
/// Trait implemented by types that can be extracted from request.
///
/// Types that implement this trait can be used with `Route::with()` method.
pub trait FromRequest<S>: Sized where S: 'static
{
type Result: Future<Item=Self, Error=Error>;
fn from_request(req: &HttpRequest<S>) -> Self::Result;
}
2018-03-11 16:36:54 +00:00
/// Combines two different responder types into a single type
2018-03-10 18:12:44 +00:00
///
/// ```rust
/// # extern crate actix_web;
/// # extern crate futures;
/// # use futures::future::Future;
/// use actix_web::AsyncResponder;
/// use futures::future::result;
/// use actix_web::{Either, Error, HttpRequest, HttpResponse, httpcodes};
///
/// type RegisterResult = Either<HttpResponse, Box<Future<Item=HttpResponse, Error=Error>>>;
///
2018-03-11 16:28:22 +00:00
///
2018-03-10 18:12:44 +00:00
/// fn index(req: HttpRequest) -> RegisterResult {
2018-03-11 16:28:22 +00:00
/// if is_a_variant() { // <- choose variant A
2018-03-10 18:12:44 +00:00
/// Either::A(
/// httpcodes::HttpBadRequest.with_body("Bad data"))
/// } else {
2018-03-11 21:50:13 +00:00
/// Either::B( // <- variant B
2018-03-10 18:12:44 +00:00
/// result(HttpResponse::Ok()
/// .content_type("text/html")
/// .body(format!("Hello!"))
/// .map_err(|e| e.into())).responder())
/// }
/// }
2018-03-11 16:28:22 +00:00
/// # fn is_a_variant() -> bool { true }
2018-03-10 18:12:44 +00:00
/// # fn main() {}
/// ```
2018-03-10 17:39:43 +00:00
#[derive(Debug)]
pub enum Either<A, B> {
/// First branch of the type
A(A),
/// Second branch of the type
B(B),
}
impl<A, B> Responder for Either<A, B>
where A: Responder, B: Responder
{
type Item = Reply;
type Error = Error;
fn respond_to(self, req: HttpRequest) -> Result<Reply, Error> {
match self {
Either::A(a) => match a.respond_to(req) {
Ok(val) => Ok(val.into()),
Err(err) => Err(err.into()),
},
Either::B(b) => match b.respond_to(req) {
Ok(val) => Ok(val.into()),
Err(err) => Err(err.into()),
},
}
}
}
2017-12-21 07:19:21 +00:00
#[doc(hidden)]
2018-01-15 21:47:25 +00:00
/// Convenience trait that convert `Future` object into `Boxed` future
2017-12-21 04:30:54 +00:00
pub trait AsyncResponder<I, E>: Sized {
fn responder(self) -> Box<Future<Item=I, Error=E>>;
}
impl<F, I, E> AsyncResponder<I, E> for F
where F: Future<Item=I, Error=E> + 'static,
I: Responder + 'static,
E: Into<Error> + 'static,
{
fn responder(self) -> Box<Future<Item=I, Error=E>> {
Box::new(self)
}
}
2017-11-29 21:26:55 +00:00
/// Handler<S> for Fn()
impl<F, R, S> Handler<S> for F
2017-11-27 05:18:38 +00:00
where F: Fn(HttpRequest<S>) -> R + 'static,
2017-12-14 17:43:42 +00:00
R: Responder + 'static
2017-10-15 21:17:41 +00:00
{
2017-11-29 21:26:55 +00:00
type Result = R;
2017-10-15 21:17:41 +00:00
2017-12-26 17:00:45 +00:00
fn handle(&mut self, req: HttpRequest<S>) -> R {
2017-11-29 21:26:55 +00:00
(self)(req)
2017-10-15 21:17:41 +00:00
}
}
2017-11-29 21:26:55 +00:00
/// Represents response process.
pub struct Reply(ReplyItem);
2017-11-29 03:49:17 +00:00
2017-11-30 23:13:56 +00:00
pub(crate) enum ReplyItem {
2017-12-16 00:24:15 +00:00
Message(HttpResponse),
2017-11-30 22:42:20 +00:00
Future(Box<Future<Item=HttpResponse, Error=Error>>),
2017-11-29 03:49:17 +00:00
}
2017-11-29 21:26:55 +00:00
impl Reply {
2017-11-29 03:49:17 +00:00
/// Create async response
2017-12-13 05:32:58 +00:00
#[inline]
2017-11-30 22:42:20 +00:00
pub fn async<F>(fut: F) -> Reply
where F: Future<Item=HttpResponse, Error=Error> + 'static
2017-11-29 03:49:17 +00:00
{
2017-11-30 22:42:20 +00:00
Reply(ReplyItem::Future(Box::new(fut)))
2017-11-29 03:49:17 +00:00
}
/// Send response
2017-12-13 05:32:58 +00:00
#[inline]
2017-11-30 23:13:56 +00:00
pub fn response<R: Into<HttpResponse>>(response: R) -> Reply {
2017-12-16 00:24:15 +00:00
Reply(ReplyItem::Message(response.into()))
2017-11-29 03:49:17 +00:00
}
2017-12-13 05:32:58 +00:00
#[inline]
2017-11-30 23:13:56 +00:00
pub(crate) fn into(self) -> ReplyItem {
self.0
2017-11-29 03:49:17 +00:00
}
2017-12-09 21:25:06 +00:00
#[cfg(test)]
pub(crate) fn as_response(&self) -> Option<&HttpResponse> {
match self.0 {
ReplyItem::Message(ref resp) => Some(resp),
_ => None,
}
}
2017-11-29 03:49:17 +00:00
}
2017-12-14 17:43:42 +00:00
impl Responder for Reply {
type Item = Reply;
type Error = Error;
2017-12-14 17:43:42 +00:00
fn respond_to(self, _: HttpRequest) -> Result<Reply, Error> {
Ok(self)
}
}
2017-12-14 17:43:42 +00:00
impl Responder for HttpResponse {
type Item = Reply;
type Error = Error;
2017-12-16 04:00:12 +00:00
#[inline]
2017-12-14 17:43:42 +00:00
fn respond_to(self, _: HttpRequest) -> Result<Reply, Error> {
2017-12-16 00:24:15 +00:00
Ok(Reply(ReplyItem::Message(self)))
2017-10-15 21:17:41 +00:00
}
}
2017-11-29 18:31:24 +00:00
impl From<HttpResponse> for Reply {
2017-12-16 04:00:12 +00:00
#[inline]
fn from(resp: HttpResponse) -> Reply {
2017-12-16 00:24:15 +00:00
Reply(ReplyItem::Message(resp))
2017-12-02 05:29:22 +00:00
}
}
2017-12-14 17:43:42 +00:00
impl<T: Responder, E: Into<Error>> Responder for Result<T, E>
2017-12-04 00:57:25 +00:00
{
2017-12-14 17:43:42 +00:00
type Item = <T as Responder>::Item;
2017-12-04 00:57:25 +00:00
type Error = Error;
2017-12-14 17:43:42 +00:00
fn respond_to(self, req: HttpRequest) -> Result<Self::Item, Self::Error> {
match self {
2017-12-14 17:43:42 +00:00
Ok(val) => match val.respond_to(req) {
2017-12-04 00:57:25 +00:00
Ok(val) => Ok(val),
Err(err) => Err(err.into()),
},
Err(err) => Err(err.into()),
}
}
}
impl<E: Into<Error>> From<Result<Reply, E>> for Reply {
#[inline]
fn from(res: Result<Reply, E>) -> Self {
2017-11-29 18:31:24 +00:00
match res {
Ok(val) => val,
2017-12-16 00:24:15 +00:00
Err(err) => Reply(ReplyItem::Message(err.into().into())),
}
}
}
impl<E: Into<Error>> From<Result<HttpResponse, E>> for Reply {
#[inline]
fn from(res: Result<HttpResponse, E>) -> Self {
match res {
Ok(val) => Reply(ReplyItem::Message(val)),
Err(err) => Reply(ReplyItem::Message(err.into().into())),
}
}
}
impl From<Box<Future<Item=HttpResponse, Error=Error>>> for Reply {
#[inline]
fn from(fut: Box<Future<Item=HttpResponse, Error=Error>>) -> Reply {
Reply(ReplyItem::Future(fut))
}
}
2018-03-26 22:58:30 +00:00
/// Convenience type alias
pub type FutureResponse<I, E=Error> = Box<Future<Item=I, Error=E>>;
impl<I, E> Responder for Box<Future<Item=I, Error=E>>
where I: Responder + 'static,
E: Into<Error> + 'static
2017-11-30 23:13:56 +00:00
{
type Item = Reply;
type Error = Error;
2017-12-16 04:00:12 +00:00
#[inline]
fn respond_to(self, req: HttpRequest) -> Result<Reply, Error> {
let fut = self.map_err(|e| e.into())
.then(move |r| {
match r.respond_to(req) {
Ok(reply) => match reply.into().0 {
ReplyItem::Message(resp) => ok(resp),
_ => panic!("Nested async replies are not supported"),
},
Err(e) => err(e),
}
});
Ok(Reply::async(fut))
2017-11-30 23:13:56 +00:00
}
}
2018-01-15 21:47:25 +00:00
/// Trait defines object that could be registered as resource route
2017-11-29 21:26:55 +00:00
pub(crate) trait RouteHandler<S>: 'static {
2017-12-26 17:00:45 +00:00
fn handle(&mut self, req: HttpRequest<S>) -> Reply;
2017-11-29 21:26:55 +00:00
}
/// Route handler wrapper for Handler
pub(crate)
struct WrapHandler<S, H, R>
where H: Handler<S, Result=R>,
2017-12-14 17:43:42 +00:00
R: Responder,
2017-11-29 21:26:55 +00:00
S: 'static,
{
h: H,
s: PhantomData<S>,
}
impl<S, H, R> WrapHandler<S, H, R>
where H: Handler<S, Result=R>,
2017-12-14 17:43:42 +00:00
R: Responder,
2017-11-29 21:26:55 +00:00
S: 'static,
{
pub fn new(h: H) -> Self {
2018-02-26 22:33:56 +00:00
WrapHandler{h, s: PhantomData}
2017-11-29 21:26:55 +00:00
}
}
impl<S, H, R> RouteHandler<S> for WrapHandler<S, H, R>
where H: Handler<S, Result=R>,
2017-12-14 17:43:42 +00:00
R: Responder + 'static,
2017-11-29 21:26:55 +00:00
S: 'static,
{
2017-12-26 17:00:45 +00:00
fn handle(&mut self, req: HttpRequest<S>) -> Reply {
2018-02-26 22:33:56 +00:00
let req2 = req.without_state();
2017-12-14 17:43:42 +00:00
match self.h.handle(req).respond_to(req2) {
Ok(reply) => reply.into(),
Err(err) => Reply::response(err.into()),
}
2017-11-29 21:26:55 +00:00
}
}
/// Async route handler
pub(crate)
2017-12-20 20:51:39 +00:00
struct AsyncHandler<S, H, F, R, E>
where H: Fn(HttpRequest<S>) -> F + 'static,
F: Future<Item=R, Error=E> + 'static,
R: Responder + 'static,
E: Into<Error> + 'static,
2017-11-29 21:26:55 +00:00
S: 'static,
{
2017-12-20 20:51:39 +00:00
h: Box<H>,
2017-11-29 21:26:55 +00:00
s: PhantomData<S>,
}
2017-12-20 20:51:39 +00:00
impl<S, H, F, R, E> AsyncHandler<S, H, F, R, E>
where H: Fn(HttpRequest<S>) -> F + 'static,
F: Future<Item=R, Error=E> + 'static,
R: Responder + 'static,
E: Into<Error> + 'static,
2017-11-29 21:26:55 +00:00
S: 'static,
{
2017-12-20 20:51:39 +00:00
pub fn new(h: H) -> Self {
AsyncHandler{h: Box::new(h), s: PhantomData}
2017-11-29 21:26:55 +00:00
}
}
2017-12-20 20:51:39 +00:00
impl<S, H, F, R, E> RouteHandler<S> for AsyncHandler<S, H, F, R, E>
where H: Fn(HttpRequest<S>) -> F + 'static,
F: Future<Item=R, Error=E> + 'static,
R: Responder + 'static,
E: Into<Error> + 'static,
2017-11-29 21:26:55 +00:00
S: 'static,
{
2017-12-26 17:00:45 +00:00
fn handle(&mut self, req: HttpRequest<S>) -> Reply {
2018-02-26 22:33:56 +00:00
let req2 = req.without_state();
2017-12-20 20:51:39 +00:00
let fut = (self.h)(req)
.map_err(|e| e.into())
.then(move |r| {
match r.respond_to(req2) {
Ok(reply) => match reply.into().0 {
ReplyItem::Message(resp) => ok(resp),
_ => panic!("Nested async replies are not supported"),
2017-12-20 21:23:50 +00:00
},
2017-12-20 20:51:39 +00:00
Err(e) => err(e),
}
});
Reply::async(fut)
2017-11-29 21:26:55 +00:00
}
}