1
0
Fork 0
mirror of https://github.com/actix/actix-web.git synced 2024-10-21 09:23:54 +00:00

update guide

This commit is contained in:
Nikolay Kim 2018-03-21 21:02:04 -07:00
parent 93d99b5a49
commit 04515e4697
2 changed files with 39 additions and 5 deletions

View file

@ -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<HttpResponse, Error> {
# use futures::future::{Future, result};
fn index(req: HttpRequest) -> Box<Future<Item=HttpResponse, Error=Error>> {
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<Future<Item=&'static str, Error=Error>> {
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<Box<Future<Item=HttpResponse, Error=Error>>, 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

View file

@ -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()