From 04515e469765322634883bb37e194981ff351b37 Mon Sep 17 00:00:00 2001 From: Nikolay Kim Date: Wed, 21 Mar 2018 21:02:04 -0700 Subject: [PATCH] update guide --- guide/src/qs_4.md | 40 +++++++++++++++++++++++++++++++++++++--- guide/src/qs_4_5.md | 4 ++-- 2 files changed, 39 insertions(+), 5 deletions(-) diff --git a/guide/src/qs_4.md b/guide/src/qs_4.md index 2f96ddd0..a1a752ca 100644 --- a/guide/src/qs_4.md +++ b/guide/src/qs_4.md @@ -187,17 +187,19 @@ return `Future` object that resolves to *Responder* type, i.e: # use actix_web::*; # use bytes::Bytes; # use futures::stream::once; -# use futures::future::{FutureResult, result}; -fn index(req: HttpRequest) -> FutureResult { +# use futures::future::{Future, result}; +fn index(req: HttpRequest) -> Box> { result(HttpResponse::Ok() .content_type("text/html") .body(format!("Hello!")) .map_err(|e| e.into())) + .responder() } -fn index2(req: HttpRequest) -> FutureResult<&'static str, Error> { +fn index2(req: HttpRequest) -> Box> { result(Ok("Welcome!")) + .responder() } fn main() { @@ -235,6 +237,38 @@ fn main() { Both methods could be combined. (i.e Async response with streaming body) +It is possible return `Result` which `Result::Item` type could be `Future`. +In this example `index` handler can return error immediately or return +future that resolves to a `HttpResponse`. + +```rust +# extern crate actix_web; +# extern crate futures; +# extern crate bytes; +# use actix_web::*; +# use bytes::Bytes; +# use futures::stream::once; +# use futures::future::{Future, result}; +fn index(req: HttpRequest) -> Result>, Error> { + if is_error() { + Err(error::ErrorBadRequest("bad request")) + } else { + Ok(Box::new( + result(HttpResponse::Ok() + .content_type("text/html") + .body(format!("Hello!")))) + .responder()) + } +} +# +# fn is_error() -> bool { true } +# fn main() { +# Application::new() +# .resource("/async", |r| r.route().f(index)) +# .finish(); +# } +``` + ## Different return types (Either) Sometimes you need to return different types of responses. For example diff --git a/guide/src/qs_4_5.md b/guide/src/qs_4_5.md index 01808c60..f4604271 100644 --- a/guide/src/qs_4_5.md +++ b/guide/src/qs_4_5.md @@ -109,7 +109,7 @@ fn index(req: HttpRequest) -> Result<&'static str, MyError> { ## Error helpers Actix provides set of error helper types. It is possible to use them to generate -specific error response. We can use helper types for first example with custom error. +specific error responses. We can use helper types for first example with custom error. ```rust # extern crate actix_web; @@ -124,7 +124,7 @@ struct MyError { fn index(req: HttpRequest) -> Result<&'static str> { let result: Result<&'static str, MyError> = Err(MyError{name: "test"}); - Ok(result.map_err(error::ErrorBadRequest)?) + Ok(result.map_err(|e| error::ErrorBadRequest(e))?) } # fn main() { # Application::new()