1
0
mirror of https://github.com/fafhrd91/actix-web synced 2024-11-30 18:44:35 +01:00

add api doc for Either

This commit is contained in:
Nikolay Kim 2018-03-10 10:12:44 -08:00
parent cad55f9c80
commit ac9eba8261
2 changed files with 63 additions and 1 deletions

View File

@ -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<HttpResponse, Box<Future<Item=HttpResponse, Error=Error>>>;
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

View File

@ -34,7 +34,32 @@ pub trait Responder {
fn respond_to(self, req: HttpRequest) -> Result<Self::Item, Self::Error>;
}
/// 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<HttpResponse, Box<Future<Item=HttpResponse, Error=Error>>>;
///
/// 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<A, B> {
/// First branch of the type