mirror of
https://github.com/actix/actix-website
synced 2025-06-27 15:39:02 +02:00
First pass at Handlers chapter.
This commit is contained in:
9
examples/async-handlers/Cargo.toml
Normal file
9
examples/async-handlers/Cargo.toml
Normal file
@ -0,0 +1,9 @@
|
||||
[package]
|
||||
name = "async-handlers"
|
||||
version = "0.1.0"
|
||||
edition = "2018"
|
||||
|
||||
[dependencies]
|
||||
actix-web = "0.7"
|
||||
futures = "0.1"
|
||||
bytes = "0.4"
|
24
examples/async-handlers/src/async_stream.rs
Normal file
24
examples/async-handlers/src/async_stream.rs
Normal file
@ -0,0 +1,24 @@
|
||||
fn is_error() -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
// <main>
|
||||
use actix_web::{error, App, Error, HttpRequest, HttpResponse};
|
||||
use futures::future::{result, Future};
|
||||
|
||||
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(Ok(HttpResponse::Ok()
|
||||
.content_type("text/html")
|
||||
.body(format!("Hello!"))))))
|
||||
}
|
||||
}
|
||||
// </main>
|
||||
|
||||
pub fn main() {
|
||||
App::new().resource("/", |r| r.route().f(index)).finish();
|
||||
}
|
25
examples/async-handlers/src/main.rs
Normal file
25
examples/async-handlers/src/main.rs
Normal file
@ -0,0 +1,25 @@
|
||||
mod async_stream;
|
||||
mod stream;
|
||||
// <main>
|
||||
use actix_web::{App, AsyncResponder, Error, HttpRequest, HttpResponse};
|
||||
use futures::future::{result, Future};
|
||||
|
||||
fn index(_req: &HttpRequest) -> Box<Future<Item = HttpResponse, Error = Error>> {
|
||||
result(Ok(HttpResponse::Ok()
|
||||
.content_type("text/html")
|
||||
.body(format!("Hello!"))))
|
||||
.responder()
|
||||
}
|
||||
|
||||
fn index2(_req: &HttpRequest) -> Box<Future<Item = &'static str, Error = Error>> {
|
||||
result(Ok("Welcome!")).responder()
|
||||
}
|
||||
|
||||
fn main() {
|
||||
App::new()
|
||||
.resource("/async", |r| r.route().a(index))
|
||||
.resource("/", |r| r.route().a(index2))
|
||||
// .resource("/", |r| r.route().f(async_stream::index))
|
||||
.finish();
|
||||
}
|
||||
// </main>
|
17
examples/async-handlers/src/stream.rs
Normal file
17
examples/async-handlers/src/stream.rs
Normal file
@ -0,0 +1,17 @@
|
||||
// <main>
|
||||
use actix_web::{App, Body, HttpRequest, HttpResponse};
|
||||
use bytes::Bytes;
|
||||
use futures::stream::once;
|
||||
|
||||
fn index(_req: &HttpRequest) -> HttpResponse {
|
||||
let body = once(Ok(Bytes::from_static(b"test")));
|
||||
|
||||
HttpResponse::Ok()
|
||||
.content_type("application/json")
|
||||
.body(Body::Streaming(Box::new(body)))
|
||||
}
|
||||
|
||||
pub fn main() {
|
||||
App::new().resource("/async", |r| r.f(index)).finish();
|
||||
}
|
||||
// </main>
|
Reference in New Issue
Block a user