diff --git a/guide/src/qs_4.md b/guide/src/qs_4.md index 486e9df58..dd432d85a 100644 --- a/guide/src/qs_4.md +++ b/guide/src/qs_4.md @@ -235,6 +235,43 @@ fn main() { Both methods could be combined. (i.e Async response with streaming body) +## Different return types (Either) + +Sometimes you need to return different types of responses. For example +you can do error check and return error, otherwise return async response. +Or any result that requires two different types. +For this case [*Either*](../actix_web/enum.Either.html) type can be used. + +```rust +# extern crate actix_web; +# extern crate futures; +# use actix_web::*; +# use futures::future::Future; +use futures::future::result; +use actix_web::{Either, Error, HttpResponse, httpcodes}; + +type RegisterResult = Either>>; + +fn index(req: HttpRequest) -> RegisterResult { + if true { // <- choose variant A + Either::A( + httpcodes::HttpBadRequest.with_body("Bad data")) + } else { + Either::B( // <- variant B + result(HttpResponse::Ok() + .content_type("text/html") + .body(format!("Hello!")) + .map_err(|e| e.into())).responder()) + } +} + +fn main() { + Application::new() + .resource("/register", |r| r.f(index)) + .finish(); +} +``` + ## Tokio core handle Any actix web handler runs within properly configured diff --git a/src/handler.rs b/src/handler.rs index f529fd04c..cd16e164c 100644 --- a/src/handler.rs +++ b/src/handler.rs @@ -34,7 +34,32 @@ pub trait Responder { fn respond_to(self, req: HttpRequest) -> Result; } -/// Combines two different responders types into a single type. +/// Combines two different responders types into a single type +/// +/// ```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>>; +/// +/// fn index(req: HttpRequest) -> RegisterResult { +/// if true { // <- choose variant A +/// Either::A( +/// httpcodes::HttpBadRequest.with_body("Bad data")) +/// } else { +/// Either::B( // <- variant B +/// result(HttpResponse::Ok() +/// .content_type("text/html") +/// .body(format!("Hello!")) +/// .map_err(|e| e.into())).responder()) +/// } +/// } +/// # fn main() {} +/// ``` #[derive(Debug)] pub enum Either { /// First branch of the type