1
0
mirror of https://github.com/actix/actix-website synced 2025-01-22 16:15:56 +01:00

Merge pull request #132 from JohnTitor/update-links

Update most examples to v2
This commit is contained in:
Yuki Okushi 2019-12-29 16:31:29 +09:00 committed by GitHub
commit 4b216230d5
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
91 changed files with 475 additions and 461 deletions

View File

@ -15,7 +15,7 @@ baseURL = "https://actix.rs"
weight = 1 weight = 1
[params] [params]
actixVersion = "0.7" actixVersion = "0.9"
actixWebVersion = "1.0" actixWebVersion = "2.0"
actixWebMinRustVersion = "1.36" actixWebMinRustVersion = "1.39"
actixMinRustVersion = "1.31" actixMinRustVersion = "1.39"

View File

@ -126,6 +126,6 @@ Each `ServiceConfig` can have it's own `data`, `routes`, and `services`
[usingappprefix]: /docs/url-dispatch/index.html#using-an-application-prefix-to-compose-applications [usingappprefix]: /docs/url-dispatch/index.html#using-an-application-prefix-to-compose-applications
[stateexample]: https://github.com/actix/examples/blob/master/state/src/main.rs [stateexample]: https://github.com/actix/examples/blob/master/state/src/main.rs
[guardtrait]: https://docs.rs/actix-web/1.0.2/actix_web/guard/trait.Guard.html [guardtrait]: https://docs.rs/actix-web/2/actix_web/guard/trait.Guard.html
[guardfuncs]: https://docs.rs/actix-web/1.0.2/actix_web/guard/index.html#functions [guardfuncs]: https://docs.rs/actix-web/2/actix_web/guard/index.html#functions
[guardheader]: ((https://docs.rs/actix-web/1.0.2/actix_web/guard/fn.Header.html [guardheader]: https://docs.rs/actix-web/2/actix_web/guard/fn.Header.html

View File

@ -134,9 +134,9 @@ This is a basic example using `middleware::Logger`:
{{< include-example example="errors" file="logging.rs" section="logging" >}} {{< include-example example="errors" file="logging.rs" section="logging" >}}
[actixerror]: https://docs.rs/actix-web/1.0.2/actix_web/error/struct.Error.html [actixerror]: https://docs.rs/actix-web/2/actix_web/error/struct.Error.html
[errorhelpers]: https://docs.rs/actix-web/1.0.2/actix_web/trait.ResponseError.html [errorhelpers]: https://docs.rs/actix-web/2/actix_web/trait.ResponseError.html
[failure]: https://github.com/rust-lang-nursery/failure [failure]: https://github.com/rust-lang-nursery/failure
[responseerror]: https://docs.rs/actix-web/1.0.2/actix_web/error/trait.ResponseError.html [responseerror]: https://docs.rs/actix-web/2/actix_web/error/trait.ResponseError.html
[responseerrorimpls]: https://docs.rs/actix-web/1.0.2/actix_web/error/trait.ResponseError.html#foreign-impls [responseerrorimpls]: https://docs.rs/actix-web/2/actix_web/error/trait.ResponseError.html#foreign-impls
[stderror]: https://doc.rust-lang.org/std/error/trait.Error.html [stderror]: https://doc.rust-lang.org/std/error/trait.Error.html

View File

@ -127,13 +127,13 @@ number of requests processed per thread. A proper implementation would use `Arc`
> request handling processes would block. If you need to share or update some state > request handling processes would block. If you need to share or update some state
> from multiple threads, consider using the [actix][actix] actor system. > from multiple threads, consider using the [actix][actix] actor system.
[pathstruct]: (https://docs.rs/actix-web/1.0.2/actix_web/dev/struct.Path.html [pathstruct]: https://docs.rs/actix-web/2/actix_web/dev/struct.Path.html
[querystruct]: https://docs.rs/actix-web/1.0.2/actix_web/web/struct.Query.html [querystruct]: https://docs.rs/actix-web/2/actix_web/web/struct.Query.html
[jsonstruct]: https://docs.rs/actix-web/1.0.2/actix_web/web/struct.Json.html [jsonstruct]: https://docs.rs/actix-web/2/actix_web/web/struct.Json.html
[jsonconfig]: https://docs.rs/actix-web/1.0.2/actix_web/web/struct.JsonConfig.html [jsonconfig]: https://docs.rs/actix-web/2/actix_web/web/struct.JsonConfig.html
[formconfig]: https://docs.rs/actix-web/1.0.2/actix_web/web/struct.FormConfig.html [formconfig]: https://docs.rs/actix-web/2/actix_web/web/struct.FormConfig.html
[datastruct]: https://docs.rs/actix-web/1.0.2/actix_web/web/struct.Data.html [datastruct]: https://docs.rs/actix-web/2/actix_web/web/struct.Data.html
[stringexample]: https://docs.rs/actix-web/1.0.2/actix_web/trait.FromRequest.html#example-2 [stringexample]: https://docs.rs/actix-web/2/actix_web/trait.FromRequest.html#example-2
[bytesexample]: https://docs.rs/actix-web/1.0.2/actix_web/trait.FromRequest.html#example-4 [bytesexample]: https://docs.rs/actix-web/2/actix_web/trait.FromRequest.html#example-4
[payloadexample]: https://docs.rs/actix-web/1.0.2/actix_web/web/struct.Payload.html [payloadexample]: https://docs.rs/actix-web/2/actix_web/web/struct.Payload.html
[actix]: https://actix.github.io/actix/actix/ [actix]: https://actix.github.io/actix/actix/

View File

@ -13,11 +13,11 @@ weight: 250
> Currently, only `rust-openssl` has support. > Currently, only `rust-openssl` has support.
`alpn` negotiation requires enabling the feature. When enabled, `HttpServer` provides the `alpn` negotiation requires enabling the feature. When enabled, `HttpServer` provides the
[bind_ssl][bindssl] method. [bind_openssl][bindopenssl] method.
```toml ```toml
[dependencies] [dependencies]
actix-web = { version = "{{< actix-version "actix-web" >}}", features = ["ssl"] } actix-web = { version = "{{< actix-version "actix-web" >}}", features = ["openssl"] }
openssl = { version = "0.10", features = ["v110"] } openssl = { version = "0.10", features = ["v110"] }
``` ```
{{< include-example example="http2" file="main.rs" section="main" >}} {{< include-example example="http2" file="main.rs" section="main" >}}
@ -30,6 +30,6 @@ connection and tls connection. [rfc section 3.4][rfcsection34].
[rfcsection32]: https://http2.github.io/http2-spec/#rfc.section.3.2 [rfcsection32]: https://http2.github.io/http2-spec/#rfc.section.3.2
[rfcsection34]: https://http2.github.io/http2-spec/#rfc.section.3.4 [rfcsection34]: https://http2.github.io/http2-spec/#rfc.section.3.4
[bindssl]: https://docs.rs/actix-web/1.0.2/actix_web/struct.HttpServer.html#method.bind_ssl [bindopenssl]: https://docs.rs/actix-web/2/actix_web/struct.HttpServer.html#method.bind_openssl
[tlsalpn]: https://tools.ietf.org/html/rfc7301 [tlsalpn]: https://tools.ietf.org/html/rfc7301
[examples]: https://github.com/actix/examples/tree/master/tls [examples]: https://github.com/actix/examples/tree/master/tls

View File

@ -127,11 +127,11 @@ into a response.
{{< include-example example="middleware" file="errorhandler.rs" section="error-handler" >}} {{< include-example example="middleware" file="errorhandler.rs" section="error-handler" >}}
[sessionobj]: https://docs.rs/actix-session/0.1.1/actix_session/struct.Session.html [sessionobj]: https://docs.rs/actix-session/0.3.0/actix_session/struct.Session.html
[requestsession]: https://docs.rs/actix-session/0.1.1/actix_session/struct.Session.html [requestsession]: https://docs.rs/actix-session/0.3.0/actix_session/struct.Session.html
[cookiesession]: https://docs.rs/actix-session/0.1.1/actix_session/struct.CookieSession.html [cookiesession]: https://docs.rs/actix-session/0.3.0/actix_session/struct.CookieSession.html
[actixsession]: https://docs.rs/actix-session/0.1.1/actix_session/ [actixsession]: https://docs.rs/actix-session/0.3.0/actix_session/
[envlogger]: https://docs.rs/env_logger/*/env_logger/ [envlogger]: https://docs.rs/env_logger/*/env_logger/
[servicetrait]: https://docs.rs/actix-web/1.0.2/actix_web/dev/trait.Service.html [servicetrait]: https://docs.rs/actix-web/2/actix_web/dev/trait.Service.html
[transformtrait]: https://docs.rs/actix-web/1.0.2/actix_web/dev/trait.Transform.html [transformtrait]: https://docs.rs/actix-web/2/actix_web/dev/trait.Transform.html
[wrap_fn]: https://docs.rs/actix-web/1.0.5/actix_web/struct.App.html#method.wrap_fn [wrap_fn]: https://docs.rs/actix-web/2/actix_web/struct.App.html#method.wrap_fn

View File

@ -78,10 +78,10 @@ In the following example, we read and print the request payload chunk by chunk:
{{< include-example example="requests" file="streaming.rs" section="streaming" >}} {{< include-example example="requests" file="streaming.rs" section="streaming" >}}
[examples]: https://github.com/actix/examples/tree/master/json/ [examples]: https://github.com/actix/examples/tree/master/json/
[multipartstruct]: https://docs.rs/actix-multipart/0.1.2/actix_multipart/struct.Multipart.html [multipartstruct]: https://docs.rs/actix-multipart/0.2/actix_multipart/struct.Multipart.html
[fieldstruct]: https://docs.rs/actix-multipart/0.1.2/actix_multipart/struct.Field.html [fieldstruct]: https://docs.rs/actix-multipart/0.2/actix_multipart/struct.Field.html
[multipartexample]: https://github.com/actix/examples/tree/master/multipart/ [multipartexample]: https://github.com/actix/examples/tree/master/multipart/
[urlencoded]: https://docs.rs/actix-web/1.0.2/actix_web/dev/struct.UrlEncoded.html [urlencoded]: https://docs.rs/actix-web/2/actix_web/dev/struct.UrlEncoded.html
[payloadextractor]: https://docs.rs/actix-web/1.0.2/actix_web/web/struct.Payload.html [payloadextractor]: https://docs.rs/actix-web/2/actix_web/web/struct.Payload.html
[multipartcrate]: https://crates.io/crates/actix-multipart [multipartcrate]: https://crates.io/crates/actix-multipart
[formencoded]:Jhttps://docs.rs/actix-web/1.0.2/actix_web/web/struct.Form.html [formencoded]:Jhttps://docs.rs/actix-web/2/actix_web/web/struct.Form.html

View File

@ -82,5 +82,5 @@ is enabled automatically.
{{< include-example example="responses" file="chunked.rs" section="chunked" >}} {{< include-example example="responses" file="chunked.rs" section="chunked" >}}
[responsebuilder]: https://docs.rs/actix-web/1.0.2/actix_web/dev/struct.HttpResponseBuilder.html [responsebuilder]: https://docs.rs/actix-web/2/actix_web/dev/struct.HttpResponseBuilder.html
[compressmidddleware]: https://docs.rs/actix-web/1.0.2/actix_web/middleware/struct.Compress.html [compressmidddleware]: https://docs.rs/actix-web/2/actix_web/middleware/struct.Compress.html

View File

@ -12,7 +12,7 @@ The [**HttpServer**][httpserverstruct] type is responsible for serving http requ
must have `Send` + `Sync` boundaries. More about that in the *multi-threading* section. must have `Send` + `Sync` boundaries. More about that in the *multi-threading* section.
To bind to a specific socket address, [`bind()`][bindmethod] must be used, and it may be To bind to a specific socket address, [`bind()`][bindmethod] must be used, and it may be
called multiple times. To bind ssl socket, [`bind_ssl()`][bindsslmethod] or called multiple times. To bind ssl socket, [`bind_openssl()`][bindopensslmethod] or
[`bind_rustls()`][bindrusttls] should be used. To start the http server, use one of the [`bind_rustls()`][bindrusttls] should be used. To start the http server, use one of the
start methods. start methods.
@ -117,13 +117,13 @@ are available on unix systems.
> It is possible to disable signal handling with > It is possible to disable signal handling with
[`HttpServer::disable_signals()`][disablesignals] method. [`HttpServer::disable_signals()`][disablesignals] method.
[httpserverstruct]: https://docs.rs/actix-web/1.0.2/actix_web/struct.HttpServer.html [httpserverstruct]: https://docs.rs/actix-web/2/actix_web/struct.HttpServer.html
[bindmethod]: https://docs.rs/actix-web/1.0.2/actix_web/struct.HttpServer.html#method.bind [bindmethod]: https://docs.rs/actix-web/2/actix_web/struct.HttpServer.html#method.bind
[bindsslmethod]: https://docs.rs/actix-web/1.0.2/actix_web/struct.HttpServer.html#method.bind_ssl [bindopensslmethod]: https://docs.rs/actix-web/2/actix_web/struct.HttpServer.html#method.bind_openssl
[bindrusttls]: https://docs.rs/actix-web/1.0.2/actix_web/struct.HttpServer.html#method.bind_rustls [bindrusttls]: https://docs.rs/actix-web/2/actix_web/struct.HttpServer.html#method.bind_rustls
[startmethod]: https://docs.rs/actix-web/1.0.2/actix_web/struct.HttpServer.html#method.start [startmethod]: https://docs.rs/actix-web/2/actix_web/struct.HttpServer.html#method.start
[workers]: https://docs.rs/actix-web/1.0.2/actix_web/struct.HttpServer.html#method.workers [workers]: https://docs.rs/actix-web/2/actix_web/struct.HttpServer.html#method.workers
[tlsalpn]: https://tools.ietf.org/html/rfc7301 [tlsalpn]: https://tools.ietf.org/html/rfc7301
[exampletls]: https://github.com/actix/examples/tree/master/tls [exampletls]: https://github.com/actix/examples/tree/master/tls
[shutdowntimeout]: https://docs.rs/actix-web/1.0.2/actix_web/struct.HttpServer.html#method.shutdown_timeout [shutdowntimeout]: https://docs.rs/actix-web/2/actix_web/struct.HttpServer.html#method.shutdown_timeout
[disablesignals]: https://docs.rs/actix-web/1.0.2/actix_web/struct.HttpServer.html#method.disable_signals [disablesignals]: https://docs.rs/actix-web/2/actix_web/struct.HttpServer.html#method.disable_signals

View File

@ -44,5 +44,5 @@ The Configuration can also be applied to directory service:
{{< include-example example="static-files" file="configuration_two.rs" section="config-two" >}} {{< include-example example="static-files" file="configuration_two.rs" section="config-two" >}}
[showfileslisting]: https://docs.rs/actix-files/0.1.2/actix_files/struct.Files.html [showfileslisting]: https://docs.rs/actix-files/0.2/actix_files/struct.Files.html
[indexfile]: https://docs.rs/actix-files/0.1.2/actix_files/struct.Files.html#method.index_file [indexfile]: https://docs.rs/actix-files/0.2/actix_files/struct.Files.html#method.index_file

View File

@ -407,24 +407,24 @@ with `App::service()` method.
{{< include-example example="url-dispatch" file="dhandler.rs" section="default" >}} {{< include-example example="url-dispatch" file="dhandler.rs" section="default" >}}
[handlersection]: ../handlers/ [handlersection]: ../handlers/
[approute]: https://docs.rs/actix-web/1.0.2/actix_web/struct.App.html#method.route [approute]: https://docs.rs/actix-web/2/actix_web/struct.App.html#method.route
[appservice]: https://docs.rs/actix-web/1.0.2/actix_web/struct.App.html?search=#method.service [appservice]: https://docs.rs/actix-web/2/actix_web/struct.App.html?search=#method.service
[webresource]: https://docs.rs/actix-web/1.0.2/actix_web/struct.Resource.html [webresource]: https://docs.rs/actix-web/2/actix_web/struct.Resource.html
[resourcehandler]: https://docs.rs/actix-web/1.0.2/actix_web/struct.Resource.html#method.route [resourcehandler]: https://docs.rs/actix-web/2/actix_web/struct.Resource.html#method.route
[route]: https://docs.rs/actix-web/1.0.2/actix_web/struct.Route.html [route]: https://docs.rs/actix-web/2/actix_web/struct.Route.html
[routeguard]: https://docs.rs/actix-web/1.0.2/actix_web/struct.Route.html#method.guard [routeguard]: https://docs.rs/actix-web/2/actix_web/struct.Route.html#method.guard
[routemethod]: https://docs.rs/actix-web/1.0.2/actix_web/struct.Route.html#method.method [routemethod]: https://docs.rs/actix-web/2/actix_web/struct.Route.html#method.method
[routeto]: https://docs.rs/actix-web/1.0.2/actix_web/struct.Route.html#method.to [routeto]: https://docs.rs/actix-web/2/actix_web/struct.Route.html#method.to
[routetoasync]: https://docs.rs/actix-web/1.0.2/actix_web/struct.Route.html#method.to_async [routetoasync]: https://docs.rs/actix-web/2/actix_web/struct.Route.html#method.to_async
[matchinfo]: https://docs.rs/actix-web/1.0.2/actix_web/struct.HttpRequest.html#method.match_info [matchinfo]: https://docs.rs/actix-web/2/actix_web/struct.HttpRequest.html#method.match_info
[pathget]: https://docs.rs/actix-web/1.0.2/actix_web/dev/struct.Path.html#method.get [pathget]: https://docs.rs/actix-web/2/actix_web/dev/struct.Path.html#method.get
[pathstruct]: https://docs.rs/actix-web/1.0.2/actix_web/dev/struct.Path.html [pathstruct]: https://docs.rs/actix-web/2/actix_web/dev/struct.Path.html
[query]: https://docs.rs/actix-web/1.0.2/actix_web/web/struct.Query.html [query]: https://docs.rs/actix-web/2/actix_web/web/struct.Query.html
[urlfor]: https://docs.rs/actix-web/1.0.2/actix_web/struct.HttpRequest.html#method.url_for [urlfor]: https://docs.rs/actix-web/2/actix_web/struct.HttpRequest.html#method.url_for
[urlobj]: https://docs.rs/url/1.7.2/url/struct.Url.html [urlobj]: https://docs.rs/url/1.7.2/url/struct.Url.html
[guardtrait]: https://docs.rs/actix-web/1.0.2/actix_web/guard/trait.Guard.html [guardtrait]: https://docs.rs/actix-web/2/actix_web/guard/trait.Guard.html
[guardfuncs]: https://docs.rs/actix-web/1.0.2/actix_web/guard/index.html#functions [guardfuncs]: https://docs.rs/actix-web/2/actix_web/guard/index.html#functions
[requestextensions]: https://docs.rs/actix-web/1.0.2/actix_web/struct.HttpRequest.html#method.extensions [requestextensions]: https://docs.rs/actix-web/2/actix_web/struct.HttpRequest.html#method.extensions
[implfromrequest]: https://docs.rs/actix-web/1.0.2/actix_web/trait.FromRequest.html [implfromrequest]: https://docs.rs/actix-web/2/actix_web/trait.FromRequest.html
[implresponder]: https://docs.rs/actix-web/1.0.2/actix_web/trait.Responder.html [implresponder]: https://docs.rs/actix-web/2/actix_web/trait.Responder.html
[pathextractor]: ../extractors [pathextractor]: ../extractors

View File

@ -18,7 +18,7 @@ The following is an example of a simple websocket echo server:
> An example chat server with the ability to chat over a websocket or tcp connection > An example chat server with the ability to chat over a websocket or tcp connection
> is available in [websocket-chat directory][chat] > is available in [websocket-chat directory][chat]
[message]: https://docs.rs/actix-web-actors/1.0.0/actix_web_actors/ws/enum.Message.html [message]: https://docs.rs/actix-web-actors/2/actix_web_actors/ws/enum.Message.html
[payload]: https://docs.rs/actix-web/1.0.2/actix_web/web/struct.Payload.html [payload]: https://docs.rs/actix-web/2/actix_web/web/struct.Payload.html
[examples]: https://github.com/actix/examples/tree/master/websocket/ [examples]: https://github.com/actix/examples/tree/master/websocket/
[chat]: https://github.com/actix/examples/tree/master/websocket-chat/ [chat]: https://github.com/actix/examples/tree/master/websocket-chat/

View File

@ -5,4 +5,5 @@ edition = "2018"
workspace = "../" workspace = "../"
[dependencies] [dependencies]
actix-web = "1.0" actix-web = "2.0"
actix-rt = "1.0"

View File

@ -1,12 +1,13 @@
// <setup> // <setup>
use actix_web::{web, App, Responder}; use actix_web::{web, App, Responder};
fn index() -> impl Responder { async fn index() -> impl Responder {
"Hello world!" "Hello world!"
} }
#[rustfmt::skip] #[rustfmt::skip]
pub fn main() { #[actix_rt::main]
async fn main() {
App::new().service( App::new().service(
web::scope("/app") web::scope("/app")
.route("/index.html", web::get().to(index))); .route("/index.html", web::get().to(index)));

View File

@ -5,7 +5,8 @@ struct State1;
struct State2; struct State2;
#[rustfmt::skip] #[rustfmt::skip]
pub fn main() { #[actix_rt::main]
async fn main() -> std::io::Result<()> {
HttpServer::new(|| { HttpServer::new(|| {
App::new() App::new()
.service( .service(
@ -17,9 +18,8 @@ pub fn main() {
.data(State2) .data(State2)
.route("/", web::to(|| HttpResponse::Ok()))) .route("/", web::to(|| HttpResponse::Ok())))
}) })
.bind("127.0.0.1:8088") .bind("127.0.0.1:8088")?
.unwrap()
.run() .run()
.unwrap(); .await
} }
// </combine> // </combine>

View File

@ -19,16 +19,16 @@ fn config(cfg: &mut web::ServiceConfig) {
); );
} }
pub fn main() { #[actix_rt::main]
async fn main() -> std::io::Result<()> {
HttpServer::new(|| { HttpServer::new(|| {
App::new() App::new()
.configure(config) .configure(config)
.service(web::scope("/api").configure(scoped_config)) .service(web::scope("/api").configure(scoped_config))
.route("/", web::get().to(|| HttpResponse::Ok().body("/"))) .route("/", web::get().to(|| HttpResponse::Ok().body("/")))
}) })
.bind("127.0.0.1:8088") .bind("127.0.0.1:8088")?
.unwrap()
.run() .run()
.unwrap(); .await
} }
// </config> // </config>

View File

@ -1,12 +1,13 @@
use actix_web::{web, App, HttpRequest, Responder}; use actix_web::{web, App, HttpRequest, Responder};
fn show_users(_req: HttpRequest) -> impl Responder { async fn show_users(_req: HttpRequest) -> impl Responder {
unimplemented!() "unimplemented!"
} }
#[rustfmt::skip] #[rustfmt::skip]
// <scope> // <scope>
pub fn main() { #[actix_rt::main]
async fn main() {
App::new() App::new()
.service( .service(
web::scope("/users") web::scope("/users")

View File

@ -7,7 +7,7 @@ struct AppState {
app_name: String, app_name: String,
} }
fn index(data: web::Data<AppState>) -> String { async fn index(data: web::Data<AppState>) -> String {
let app_name = &data.app_name; // <- get app_name let app_name = &data.app_name; // <- get app_name
format!("Hello {}!", app_name) // <- response with app_name format!("Hello {}!", app_name) // <- response with app_name
@ -19,7 +19,7 @@ struct AppStateWithCounter {
counter: Mutex<i32>, // <- Mutex is necessary to mutate safely across threads counter: Mutex<i32>, // <- Mutex is necessary to mutate safely across threads
} }
fn _index(data: web::Data<AppStateWithCounter>) -> String { async fn _index(data: web::Data<AppStateWithCounter>) -> String {
let mut counter = data.counter.lock().unwrap(); // <- get counter's MutexGuard let mut counter = data.counter.lock().unwrap(); // <- get counter's MutexGuard
*counter += 1; // <- access counter inside MutexGuard *counter += 1; // <- access counter inside MutexGuard
@ -28,25 +28,26 @@ fn _index(data: web::Data<AppStateWithCounter>) -> String {
// </setup_mutable> // </setup_mutable>
// <make_app_mutable> // <make_app_mutable>
fn _main() { #[actix_rt::main]
async fn _main() -> std::io::Result<()> {
let counter = web::Data::new(AppStateWithCounter { let counter = web::Data::new(AppStateWithCounter {
counter: Mutex::new(0), counter: Mutex::new(0),
}); });
HttpServer::new(move || { // move counter into the closure HttpServer::new(move || { // move counter into the closure
App::new() App::new()
.register_data(counter.clone()) // <- register the created data .app_data(counter.clone()) // <- register the created data
.route("/", web::get().to(_index)) .route("/", web::get().to(_index))
}) })
.bind("127.0.0.1:8088") .bind("127.0.0.1:8088")?
.unwrap()
.run() .run()
.unwrap(); .await
} }
// </make_app_mutable> // </make_app_mutable>
// <start_app> // <start_app>
pub fn main() { #[actix_rt::main]
async fn main() -> std::io::Result<()> {
HttpServer::new(|| { HttpServer::new(|| {
App::new() App::new()
.data(AppState { .data(AppState {
@ -54,9 +55,8 @@ pub fn main() {
}) })
.route("/", web::get().to(index)) .route("/", web::get().to(index))
}) })
.bind("127.0.0.1:8088") .bind("127.0.0.1:8088")?
.unwrap()
.run() .run()
.unwrap(); .await
} }
// </start_app> // </start_app>

View File

@ -1,7 +1,8 @@
use actix_web::{guard, web, App, HttpResponse, HttpServer}; use actix_web::{guard, web, App, HttpResponse, HttpServer};
// <vh> // <vh>
pub fn main() { #[actix_rt::main]
async fn main() -> std::io::Result<()> {
HttpServer::new(|| { HttpServer::new(|| {
App::new() App::new()
.service( .service(
@ -16,9 +17,8 @@ pub fn main() {
) )
.route("/", web::to(|| HttpResponse::Ok())) .route("/", web::to(|| HttpResponse::Ok()))
}) })
.bind("127.0.0.1:8088") .bind("127.0.0.1:8088")?
.unwrap()
.run() .run()
.unwrap(); .await
} }
// </vh> // </vh>

View File

@ -4,5 +4,6 @@ version = "1.0.0"
edition = "2018" edition = "2018"
[dependencies] [dependencies]
actix-web = "1.0" actix-web = "2.0"
actix-rt = "1.0"
listenfd = "0.3" listenfd = "0.3"

View File

@ -2,20 +2,21 @@
use actix_web::{web, App, HttpRequest, HttpServer, Responder}; use actix_web::{web, App, HttpRequest, HttpServer, Responder};
use listenfd::ListenFd; use listenfd::ListenFd;
fn index(_req: HttpRequest) -> impl Responder { async fn index(_req: HttpRequest) -> impl Responder {
"Hello World!" "Hello World!"
} }
fn main() { #[actix_rt::main]
async fn main() -> std::io::Result<()> {
let mut listenfd = ListenFd::from_env(); let mut listenfd = ListenFd::from_env();
let mut server = HttpServer::new(|| App::new().route("/", web::get().to(index))); let mut server = HttpServer::new(|| App::new().route("/", web::get().to(index)));
server = if let Some(l) = listenfd.take_tcp_listener(0).unwrap() { server = if let Some(l) = listenfd.take_tcp_listener(0).unwrap() {
server.listen(l).unwrap() server.listen(l)?
} else { } else {
server.bind("127.0.0.1:3000").unwrap() server.bind("127.0.0.1:3000")?
}; };
server.run().unwrap(); server.run().await
} }
// </autoreload> // </autoreload>

View File

@ -4,5 +4,6 @@ version = "1.0.0"
edition = "2018" edition = "2018"
[dependencies] [dependencies]
actix-web = "1.0" actix-web = "2.0"
actix-rt = "1.0"
serde = "1.0" serde = "1.0"

View File

@ -8,25 +8,25 @@ struct Register {
country: String, country: String,
} }
fn index() -> HttpResponse { async fn index() -> HttpResponse {
HttpResponse::Ok() HttpResponse::Ok()
.content_type("text/html; charset=utf-8") .content_type("text/html; charset=utf-8")
.body(include_str!("../static/form.html")) .body(include_str!("../static/form.html"))
} }
fn register(form: web::Form<Register>) -> impl Responder { async fn register(form: web::Form<Register>) -> impl Responder {
format!("Hello {} from {}!", form.username, form.country) format!("Hello {} from {}!", form.username, form.country)
} }
fn main() { #[actix_rt::main]
async fn main() -> std::io::Result<()> {
HttpServer::new(|| { HttpServer::new(|| {
App::new() App::new()
.route("/", web::get().to(index)) .route("/", web::get().to(index))
.route("/register", web::post().to(register)) .route("/register", web::post().to(register))
}) })
.bind("127.0.0.1:8088") .bind("127.0.0.1:8088")?
.unwrap()
.run() .run()
.unwrap(); .await
} }
// </easy-form-handling> // </easy-form-handling>

View File

@ -7,5 +7,4 @@ edition = "2018"
actix-web = "2.0" actix-web = "2.0"
actix-rt = "1.0" actix-rt = "1.0"
serde = "1.0" serde = "1.0"
futures = "0.3"
serde_json = "1.0" serde_json = "1.0"

View File

@ -4,5 +4,6 @@ version = "1.0.0"
edition = "2018" edition = "2018"
[dependencies] [dependencies]
actix-web = "1.0" actix-web = "2.0"
actix-rt = "1.0"
serde = "1.0" serde = "1.0"

View File

@ -7,23 +7,23 @@ struct Measurement {
temperature: f32, temperature: f32,
} }
fn hello_world() -> impl Responder { async fn hello_world() -> impl Responder {
"Hello World!" "Hello World!"
} }
fn current_temperature() -> impl Responder { async fn current_temperature() -> impl Responder {
web::Json(Measurement { temperature: 42.3 }) web::Json(Measurement { temperature: 42.3 })
} }
fn main() { #[actix_rt::main]
async fn main() -> std::io::Result<()> {
HttpServer::new(|| { HttpServer::new(|| {
App::new() App::new()
.service(web::resource("/").to(hello_world)) .service(web::resource("/").to(hello_world))
.service(web::resource("/temp").to(current_temperature)) .service(web::resource("/temp").to(current_temperature))
}) })
.bind("127.0.0.1:8088") .bind("127.0.0.1:8088")?
.unwrap()
.run() .run()
.unwrap(); .await
} }
// </flexible-responders> // </flexible-responders>

View File

@ -5,4 +5,5 @@ edition = "2018"
workspace = "../" workspace = "../"
[dependencies] [dependencies]
actix-web = "1.0" actix-web = "2.0"
actix-rt = "1.0"

View File

@ -1,11 +1,11 @@
// <setup> // <setup>
use actix_web::{web, App, HttpResponse, HttpServer, Responder}; use actix_web::{web, App, HttpResponse, HttpServer, Responder};
fn index() -> impl Responder { async fn index() -> impl Responder {
HttpResponse::Ok().body("Hello world!") HttpResponse::Ok().body("Hello world!")
} }
fn index2() -> impl Responder { async fn index2() -> impl Responder {
HttpResponse::Ok().body("Hello world again!") HttpResponse::Ok().body("Hello world again!")
} }
// </setup> // </setup>
@ -14,21 +14,21 @@ fn index2() -> impl Responder {
use actix_web::get; use actix_web::get;
#[get("/hello")] #[get("/hello")]
fn index3() -> impl Responder { async fn index3() -> impl Responder {
HttpResponse::Ok().body("Hey there!") HttpResponse::Ok().body("Hey there!")
} }
// </macro-attributes> // </macro-attributes>
// <main> // <main>
fn main() { #[actix_rt::main]
async fn main() -> std::io::Result<()> {
HttpServer::new(|| { HttpServer::new(|| {
App::new() App::new()
.route("/", web::get().to(index)) .route("/", web::get().to(index))
.route("/again", web::get().to(index2)) .route("/again", web::get().to(index2))
}) })
.bind("127.0.0.1:8088") .bind("127.0.0.1:8088")?
.unwrap()
.run() .run()
.unwrap(); .await
} }
// </main> // </main>

View File

@ -4,5 +4,6 @@ version = "1.0.0"
edition = "2018" edition = "2018"
[dependencies] [dependencies]
actix-web = { version = "1.0", features = ["ssl"] } actix-web = { version = "2.0", features = ["openssl"] }
actix-rt = "1.0"
openssl = { version = "0.10", features = ["v110"] } openssl = { version = "0.10", features = ["v110"] }

View File

@ -2,11 +2,12 @@
use actix_web::{web, App, HttpRequest, HttpServer, Responder}; use actix_web::{web, App, HttpRequest, HttpServer, Responder};
use openssl::ssl::{SslAcceptor, SslFiletype, SslMethod}; use openssl::ssl::{SslAcceptor, SslFiletype, SslMethod};
fn index(_req: HttpRequest) -> impl Responder { async fn index(_req: HttpRequest) -> impl Responder {
"Hello." "Hello."
} }
fn main() { #[actix_rt::main]
async fn main() -> std::io::Result<()> {
// load ssl keys // load ssl keys
// to create a self-signed temporary cert for testing: // to create a self-signed temporary cert for testing:
// `openssl req -x509 -newkey rsa:4096 -nodes -keyout key.pem -out cert.pem -days 365 -subj '/CN=localhost'` // `openssl req -x509 -newkey rsa:4096 -nodes -keyout key.pem -out cert.pem -days 365 -subj '/CN=localhost'`
@ -17,9 +18,8 @@ fn main() {
builder.set_certificate_chain_file("cert.pem").unwrap(); builder.set_certificate_chain_file("cert.pem").unwrap();
HttpServer::new(|| App::new().route("/", web::get().to(index))) HttpServer::new(|| App::new().route("/", web::get().to(index)))
.bind_ssl("127.0.0.1:8088", builder) .bind_openssl("127.0.0.1:8088", builder)?
.unwrap()
.run() .run()
.unwrap(); .await
} }
// </main> // </main>

View File

@ -4,4 +4,5 @@ version = "1.0.0"
edition = "2018" edition = "2018"
[dependencies] [dependencies]
actix-web = "1.0" actix-web = "2.0"
actix-rt = "1.0"

View File

@ -1,20 +1,20 @@
// <main-example> // <main-example>
use actix_web::{web, App, HttpRequest, HttpServer, Responder}; use actix_web::{web, App, HttpRequest, HttpServer, Responder};
fn greet(req: HttpRequest) -> impl Responder { async fn greet(req: HttpRequest) -> impl Responder {
let name = req.match_info().get("name").unwrap_or("World"); let name = req.match_info().get("name").unwrap_or("World");
format!("Hello {}!", &name) format!("Hello {}!", &name)
} }
fn main() { #[actix_rt::main]
async fn main() -> std::io::Result<()> {
HttpServer::new(|| { HttpServer::new(|| {
App::new() App::new()
.route("/", web::get().to(greet)) .route("/", web::get().to(greet))
.route("/{name}", web::get().to(greet)) .route("/{name}", web::get().to(greet))
}) })
.bind("127.0.0.1:8088") .bind("127.0.0.1:8088")?
.unwrap()
.run() .run()
.unwrap(); .await
} }
// </main-example> // </main-example>

View File

@ -4,8 +4,9 @@ version = "1.0.0"
edition = "2018" edition = "2018"
[dependencies] [dependencies]
actix-web = "1.0" actix-web = "2.0"
actix-service = "0.4" actix-rt = "1.0"
actix-session = "0.1" actix-service = "1.0"
futures = "0.1" actix-session = "0.3"
futures = "0.3.1"
env_logger = "0.6" env_logger = "0.6"

View File

@ -1,7 +1,8 @@
// <default-headers> // <default-headers>
use actix_web::{http, middleware, HttpResponse}; use actix_web::{http, middleware, HttpResponse};
pub fn main() { #[actix_rt::main]
async fn main() -> std::io::Result<()> {
use actix_web::{web, App, HttpServer}; use actix_web::{web, App, HttpServer};
HttpServer::new(|| { HttpServer::new(|| {
@ -16,9 +17,8 @@ pub fn main() {
), ),
) )
}) })
.bind("127.0.0.1:8088") .bind("127.0.0.1:8088")?
.unwrap()
.run() .run()
.unwrap(); .await
} }
// </default-headers> // </default-headers>

View File

@ -10,7 +10,8 @@ fn render_500<B>(mut res: dev::ServiceResponse<B>) -> Result<ErrorHandlerRespons
Ok(ErrorHandlerResponse::Response(res)) Ok(ErrorHandlerResponse::Response(res))
} }
pub fn main() { #[actix_rt::main]
async fn main() -> std::io::Result<()> {
use actix_web::{web, App, HttpServer}; use actix_web::{web, App, HttpServer};
HttpServer::new(|| { HttpServer::new(|| {
@ -25,9 +26,8 @@ pub fn main() {
.route(web::head().to(|| HttpResponse::MethodNotAllowed())), .route(web::head().to(|| HttpResponse::MethodNotAllowed())),
) )
}) })
.bind("127.0.0.1:8088") .bind("127.0.0.1:8088")?
.unwrap()
.run() .run()
.unwrap(); .await
} }
// </error-handler> // </error-handler>

View File

@ -2,7 +2,8 @@
use actix_web::middleware::Logger; use actix_web::middleware::Logger;
use env_logger; use env_logger;
pub fn main() { #[actix_rt::main]
async fn main() -> std::io::Result<()> {
use actix_web::{App, HttpServer}; use actix_web::{App, HttpServer};
std::env::set_var("RUST_LOG", "actix_web=info"); std::env::set_var("RUST_LOG", "actix_web=info");
@ -13,9 +14,8 @@ pub fn main() {
.wrap(Logger::default()) .wrap(Logger::default())
.wrap(Logger::new("%a %{User-Agent}i")) .wrap(Logger::new("%a %{User-Agent}i"))
}) })
.bind("127.0.0.1:8088") .bind("127.0.0.1:8088")?
.unwrap()
.run() .run()
.unwrap(); .await
} }
// </logger> // </logger>

View File

@ -5,10 +5,13 @@ pub mod user_sessions;
pub mod wrap_fn; pub mod wrap_fn;
// <simple> // <simple>
use std::pin::Pin;
use std::task::{Context, Poll};
use actix_service::{Service, Transform}; use actix_service::{Service, Transform};
use actix_web::{dev::ServiceRequest, dev::ServiceResponse, Error}; use actix_web::{dev::ServiceRequest, dev::ServiceResponse, Error};
use futures::future::{ok, FutureResult}; use futures::future::{ok, Ready};
use futures::{Future, Poll}; use futures::Future;
// There are two steps in middleware processing. // There are two steps in middleware processing.
// 1. Middleware initialization, middleware factory gets called with // 1. Middleware initialization, middleware factory gets called with
@ -30,7 +33,7 @@ where
type Error = Error; type Error = Error;
type InitError = (); type InitError = ();
type Transform = SayHiMiddleware<S>; type Transform = SayHiMiddleware<S>;
type Future = FutureResult<Self::Transform, Self::InitError>; type Future = Ready<Result<Self::Transform, Self::InitError>>;
fn new_transform(&self, service: S) -> Self::Future { fn new_transform(&self, service: S) -> Self::Future {
ok(SayHiMiddleware { service }) ok(SayHiMiddleware { service })
@ -50,34 +53,40 @@ where
type Request = ServiceRequest; type Request = ServiceRequest;
type Response = ServiceResponse<B>; type Response = ServiceResponse<B>;
type Error = Error; type Error = Error;
type Future = Box<dyn Future<Item = Self::Response, Error = Self::Error>>; type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>>>>;
fn poll_ready(&mut self) -> Poll<(), Self::Error> { fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
self.service.poll_ready() self.service.poll_ready(cx)
} }
fn call(&mut self, req: ServiceRequest) -> Self::Future { fn call(&mut self, req: ServiceRequest) -> Self::Future {
println!("Hi from start. You requested: {}", req.path()); println!("Hi from start. You requested: {}", req.path());
Box::new(self.service.call(req).and_then(|res| { let fut = self.service.call(req);
Box::pin(async move {
let res = fut.await?;
println!("Hi from response"); println!("Hi from response");
Ok(res) Ok(res)
})) })
} }
} }
// </simple> // </simple>
fn main() { #[actix_rt::main]
async fn main() -> std::io::Result<()> {
use actix_web::{web, App, HttpServer}; use actix_web::{web, App, HttpServer};
HttpServer::new(|| { HttpServer::new(|| {
App::new().wrap(SayHi).service( App::new().wrap(SayHi).service(
web::resource("/") web::resource("/")
.to(|| "Hello, middleware! Check the console where the server is run."), .to(|| async {
"Hello, middleware! Check the console where the server is run."
}),
) )
}) })
.bind("127.0.0.1:8088") .bind("127.0.0.1:8088")?
.unwrap()
.run() .run()
.unwrap(); .await
} }

View File

@ -2,7 +2,7 @@
use actix_session::{CookieSession, Session}; use actix_session::{CookieSession, Session};
use actix_web::{web, App, Error, HttpResponse, HttpServer}; use actix_web::{web, App, Error, HttpResponse, HttpServer};
pub fn index(session: Session) -> Result<HttpResponse, Error> { async fn index(session: Session) -> Result<HttpResponse, Error> {
// access session data // access session data
if let Some(count) = session.get::<i32>("counter")? { if let Some(count) = session.get::<i32>("counter")? {
session.set("counter", count + 1)?; session.set("counter", count + 1)?;
@ -16,7 +16,8 @@ pub fn index(session: Session) -> Result<HttpResponse, Error> {
))) )))
} }
pub fn main() { #[actix_rt::main]
async fn main() -> std::io::Result<()> {
HttpServer::new(|| { HttpServer::new(|| {
App::new() App::new()
.wrap( .wrap(
@ -25,9 +26,8 @@ pub fn main() {
) )
.service(web::resource("/").to(index)) .service(web::resource("/").to(index))
}) })
.bind("127.0.0.1:8088") .bind("127.0.0.1:8088")?
.unwrap()
.run() .run()
.unwrap(); .await
} }
// </user-session> // </user-session>

View File

@ -1,9 +1,10 @@
// <wrap-fn> // <wrap-fn>
use actix_service::Service; use actix_service::Service;
use actix_web::{web, App}; use actix_web::{web, App};
use futures::future::Future; use futures::future::FutureExt;
fn main() { #[actix_rt::main]
async fn main() {
let app = App::new() let app = App::new()
.wrap_fn(|req, srv| { .wrap_fn(|req, srv| {
println!("Hi from start. You requested: {}", req.path()); println!("Hi from start. You requested: {}", req.path());
@ -14,7 +15,9 @@ fn main() {
}) })
.route( .route(
"/index.html", "/index.html",
web::get().to(|| "Hello, middleware!"), web::get().to(|| async {
"Hello, middleware!"
}),
); );
} }
// </wrap-fn> // </wrap-fn>

View File

@ -4,5 +4,6 @@ version = "1.0.0"
edition = "2018" edition = "2018"
[dependencies] [dependencies]
actix-web = "1.0" actix-web = "2.0"
actix-rt = "1.0"
serde = "1.0" serde = "1.0"

View File

@ -20,25 +20,25 @@ fn store_in_db(timestamp: f64, kind: &str, tags: &[String]) -> Event {
} }
} }
fn capture_event(evt: web::Json<Event>) -> impl Responder { async fn capture_event(evt: web::Json<Event>) -> impl Responder {
let new_event = store_in_db(evt.timestamp, &evt.kind, &evt.tags); let new_event = store_in_db(evt.timestamp, &evt.kind, &evt.tags);
format!("got event {}", new_event.id.unwrap()) format!("got event {}", new_event.id.unwrap())
} }
fn index() -> HttpResponse { async fn index() -> HttpResponse {
HttpResponse::Ok() HttpResponse::Ok()
.content_type("text/html; charset=utf-8") .content_type("text/html; charset=utf-8")
.body(include_str!("../static/form.html")) .body(include_str!("../static/form.html"))
} }
fn main() { #[actix_rt::main]
async fn main() -> std::io::Result<()> {
HttpServer::new(|| { HttpServer::new(|| {
App::new() App::new()
.route("/", web::get().to(index)) .route("/", web::get().to(index))
.route("/event", web::post().to(capture_event)) .route("/event", web::post().to(capture_event))
}) })
.bind("127.0.0.1:8088") .bind("127.0.0.1:8088")?
.unwrap()
.run() .run()
.unwrap(); .await
} }

View File

@ -4,4 +4,5 @@ version = "1.0.0"
edition = "2018" edition = "2018"
[dependencies] [dependencies]
actix-web = "1.0" actix-web = "2.0"
actix-rt = "1.0"

View File

@ -8,17 +8,18 @@ struct AppState {
count: Arc<AtomicUsize>, count: Arc<AtomicUsize>,
} }
fn show_count(data: web::Data<AppState>) -> impl Responder { async fn show_count(data: web::Data<AppState>) -> impl Responder {
format!("count: {}", data.count.load(Ordering::Relaxed)) format!("count: {}", data.count.load(Ordering::Relaxed))
} }
fn add_one(data: web::Data<AppState>) -> impl Responder { async fn add_one(data: web::Data<AppState>) -> impl Responder {
data.count.fetch_add(1, Ordering::Relaxed); data.count.fetch_add(1, Ordering::Relaxed);
format!("count: {}", data.count.load(Ordering::Relaxed)) format!("count: {}", data.count.load(Ordering::Relaxed))
} }
pub fn main() { #[actix_rt::main]
async fn main() -> std::io::Result<()> {
use actix_web::{App, HttpServer}; use actix_web::{App, HttpServer};
let data = AppState { let data = AppState {
@ -31,9 +32,8 @@ pub fn main() {
.route("/", web::to(show_count)) .route("/", web::to(show_count))
.route("/add", web::to(add_one)) .route("/add", web::to(add_one))
}) })
.bind("127.0.0.1:8088") .bind("127.0.0.1:8088")?
.unwrap()
.run() .run()
.unwrap(); .await
} }
// </arc> // </arc>

View File

@ -8,18 +8,19 @@ struct AppState {
count: Cell<i32>, count: Cell<i32>,
} }
fn show_count(data: web::Data<AppState>) -> impl Responder { async fn show_count(data: web::Data<AppState>) -> impl Responder {
format!("count: {}", data.count.get()) format!("count: {}", data.count.get())
} }
fn add_one(data: web::Data<AppState>) -> impl Responder { async fn add_one(data: web::Data<AppState>) -> impl Responder {
let count = data.count.get(); let count = data.count.get();
data.count.set(count + 1); data.count.set(count + 1);
format!("count: {}", data.count.get()) format!("count: {}", data.count.get())
} }
fn main() { #[actix_rt::main]
async fn main() -> std::io::Result<()> {
use actix_web::{App, HttpServer}; use actix_web::{App, HttpServer};
let data = AppState { let data = AppState {
@ -32,9 +33,8 @@ fn main() {
.route("/", web::to(show_count)) .route("/", web::to(show_count))
.route("/add", web::to(add_one)) .route("/add", web::to(add_one))
}) })
.bind("127.0.0.1:8088") .bind("127.0.0.1:8088")?
.unwrap()
.run() .run()
.unwrap(); .await
} }
// </data> // </data>

View File

@ -4,4 +4,5 @@ version = "1.0.0"
edition = "2018" edition = "2018"
[dependencies] [dependencies]
actix-web = "1.0" actix-web = "2.0"
actix-rt = "1.0"

View File

@ -1,23 +1,23 @@
// <request-routing> // <request-routing>
use actix_web::{web, App, HttpRequest, HttpServer, Responder}; use actix_web::{web, App, HttpRequest, HttpServer, Responder};
fn index(_req: HttpRequest) -> impl Responder { async fn index(_req: HttpRequest) -> impl Responder {
"Hello from the index page." "Hello from the index page."
} }
fn hello(path: web::Path<String>) -> impl Responder { async fn hello(path: web::Path<String>) -> impl Responder {
format!("Hello {}!", &path) format!("Hello {}!", &path)
} }
fn main() { #[actix_rt::main]
async fn main() -> std::io::Result<()> {
HttpServer::new(|| { HttpServer::new(|| {
App::new() App::new()
.service(web::resource("/").to(index)) .service(web::resource("/").to(index))
.service(web::resource("/{name}").to(hello)) .service(web::resource("/{name}").to(hello))
}) })
.bind("127.0.0.1:8088") .bind("127.0.0.1:8088")?
.unwrap()
.run() .run()
.unwrap(); .await
} }
// </request-routing> // </request-routing>

View File

@ -6,7 +6,8 @@ edition = "2018"
[dependencies] [dependencies]
serde = "1.0" serde = "1.0"
serde_json = "1.0" serde_json = "1.0"
actix-web = "1.0" actix-web = "2.0"
futures = "0.1" actix-rt = "1.0"
futures = "0.3.1"
bytes = "0.4" bytes = "0.4"
actix-multipart = "0.1" actix-multipart = "0.2"

View File

@ -14,15 +14,15 @@ struct Info {
} }
/// extract `Info` using serde /// extract `Info` using serde
fn index(info: web::Json<Info>) -> Result<String> { async fn index(info: web::Json<Info>) -> Result<String> {
Ok(format!("Welcome {}!", info.username)) Ok(format!("Welcome {}!", info.username))
} }
fn main() { #[actix_rt::main]
async fn main() -> std::io::Result<()> {
HttpServer::new(|| App::new().route("/", web::post().to(index))) HttpServer::new(|| App::new().route("/", web::post().to(index)))
.bind("127.0.0.1:8088") .bind("127.0.0.1:8088")?
.unwrap()
.run() .run()
.unwrap(); .await
} }
// </json-request> // </json-request>

View File

@ -1,7 +1,7 @@
// <json-manual> // <json-manual>
use actix_web::{error, web, App, Error, HttpResponse}; use actix_web::{error, web, App, Error, HttpResponse};
use bytes::BytesMut; use bytes::BytesMut;
use futures::{Future, Stream}; use futures::StreamExt;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use serde_json; use serde_json;
@ -13,41 +13,30 @@ struct MyObj {
const MAX_SIZE: usize = 262_144; // max payload size is 256k const MAX_SIZE: usize = 262_144; // max payload size is 256k
pub fn index_manual( async fn index_manual(mut payload: web::Payload) -> Result<HttpResponse, Error> {
payload: web::Payload,
) -> impl Future<Item = HttpResponse, Error = Error> {
// payload is a stream of Bytes objects // payload is a stream of Bytes objects
payload let mut body = BytesMut::new();
// `Future::from_err` acts like `?` in that it coerces the error type from while let Some(chunk) = payload.next().await {
// the future into the final error type let chunk = chunk?;
.from_err() // limit max size of in-memory payload
// `fold` will asynchronously read each chunk of the request body and if (body.len() + chunk.len()) > MAX_SIZE {
// call supplied closure, then it resolves to result of closure return Err(error::ErrorBadRequest("overflow"));
.fold(BytesMut::new(), move |mut body, chunk| { }
// limit max size of in-memory payload body.extend_from_slice(&chunk);
if (body.len() + chunk.len()) > MAX_SIZE { }
Err(error::ErrorBadRequest("overflow"))
} else { // body is loaded, now we can deserialize serde-json
body.extend_from_slice(&chunk); let obj = serde_json::from_slice::<MyObj>(&body)?;
Ok(body) Ok(HttpResponse::Ok().json(obj)) // <- send response
}
})
// `Future::and_then` can be used to merge an asynchronous workflow with a
// synchronous workflow
.and_then(|body| {
// body is loaded, now we can deserialize serde-json
let obj = serde_json::from_slice::<MyObj>(&body)?;
Ok(HttpResponse::Ok().json(obj)) // <- send response
})
} }
// </json-manual> // </json-manual>
pub fn main() { #[actix_rt::main]
async fn main() -> std::io::Result<()> {
use actix_web::HttpServer; use actix_web::HttpServer;
HttpServer::new(|| App::new().route("/", web::post().to_async(index_manual))) HttpServer::new(|| App::new().route("/", web::post().to(index_manual)))
.bind("127.0.0.1:8088") .bind("127.0.0.1:8088")?
.unwrap()
.run() .run()
.unwrap(); .await
} }

View File

@ -1,26 +1,24 @@
// <streaming> // <streaming>
use actix_web::{error, web, Error, HttpResponse}; use actix_web::{error, web, Error, HttpResponse};
use futures::{future::result, Future, Stream}; use futures::{Future, Stream, StreamExt};
pub fn index(payload: web::Payload) -> Box<dyn Future<Item = HttpResponse, Error = Error>> { async fn index(mut body: web::Payload) -> Result<HttpResponse, Error> {
Box::new( let mut bytes = web::BytesMut::new();
payload while let Some(item) = body.next().await {
.from_err() bytes.extend_from_slice(&item?);
.fold((), |_, chunk| { }
println!("Chunk: {:?}", chunk);
result::<_, error::PayloadError>(Ok(())) println!("Chunk: {:?}", bytes);
}) Ok(HttpResponse::Ok().finish())
.map(|_| HttpResponse::Ok().into()),
)
} }
// </streaming> // </streaming>
pub fn main() { #[actix_rt::main]
async fn main() -> std::io::Result<()> {
use actix_web::{App, HttpServer}; use actix_web::{App, HttpServer};
HttpServer::new(|| App::new().route("/", web::post().to_async(index))) HttpServer::new(|| App::new().route("/", web::post().to(index)))
.bind("127.0.0.1:8088") .bind("127.0.0.1:8088")?
.unwrap()
.run() .run()
.unwrap(); .await
} }

View File

@ -7,17 +7,17 @@ struct FormData {
username: String, username: String,
} }
fn index(form: web::Form<FormData>) -> HttpResponse { async fn index(form: web::Form<FormData>) -> HttpResponse {
HttpResponse::Ok().body(format!("username: {}", form.username)) HttpResponse::Ok().body(format!("username: {}", form.username))
} }
// </urlencoded> // </urlencoded>
pub fn main() { #[actix_rt::main]
async fn main() -> std::io::Result<()> {
use actix_web::{App, HttpServer}; use actix_web::{App, HttpServer};
HttpServer::new(|| App::new().route("/", web::post().to(index))) HttpServer::new(|| App::new().route("/", web::post().to(index)))
.bind("127.0.0.1:8088") .bind("127.0.0.1:8088")?
.unwrap()
.run() .run()
.unwrap(); .await
} }

View File

@ -4,6 +4,8 @@ version = "1.0.0"
edition = "2018" edition = "2018"
[dependencies] [dependencies]
actix-web = "1.0" actix-web = "2.0"
actix-rt = "1.0"
futures = "0.3.1"
serde = "1.0" serde = "1.0"
serde_json = "1.0" serde_json = "1.0"

View File

@ -1,6 +1,7 @@
// <responder-trait> // <responder-trait>
use actix_web::{Error, HttpRequest, HttpResponse, Responder}; use actix_web::{Error, HttpRequest, HttpResponse, Responder};
use serde::Serialize; use serde::Serialize;
use futures::future::{ready, Ready};
#[derive(Serialize)] #[derive(Serialize)]
struct MyObj { struct MyObj {
@ -10,29 +11,29 @@ struct MyObj {
// Responder // Responder
impl Responder for MyObj { impl Responder for MyObj {
type Error = Error; type Error = Error;
type Future = Result<HttpResponse, Error>; type Future = Ready<Result<HttpResponse, Error>>;
fn respond_to(self, _req: &HttpRequest) -> Self::Future { fn respond_to(self, _req: &HttpRequest) -> Self::Future {
let body = serde_json::to_string(&self)?; let body = serde_json::to_string(&self).unwrap();
// Create response and set content type // Create response and set content type
Ok(HttpResponse::Ok() ready(Ok(HttpResponse::Ok()
.content_type("application/json") .content_type("application/json")
.body(body)) .body(body)))
} }
} }
fn index() -> impl Responder { async fn index() -> impl Responder {
MyObj { name: "user" } MyObj { name: "user" }
} }
// </responder-trait> // </responder-trait>
fn main() { #[actix_rt::main]
async fn main() -> std::io::Result<()> {
use actix_web::{web, App, HttpServer}; use actix_web::{web, App, HttpServer};
HttpServer::new(|| App::new().route("/", web::get().to(index))) HttpServer::new(|| App::new().route("/", web::get().to(index)))
.bind("127.0.0.1:8088") .bind("127.0.0.1:8088")?
.unwrap()
.run() .run()
.unwrap(); .await
} }

View File

@ -4,7 +4,8 @@ version = "1.0.0"
edition = "2018" edition = "2018"
[dependencies] [dependencies]
actix-web = "1.0" actix-web = "2.0"
actix-rt = "1.0"
serde = "1.0" serde = "1.0"
futures = "0.1" futures = "0.3.1"
bytes = "0.4" bytes = "0.4"

View File

@ -1,11 +1,12 @@
// <auto> // <auto>
use actix_web::{http::ContentEncoding, middleware, HttpResponse}; use actix_web::{http::ContentEncoding, middleware, HttpResponse};
fn index() -> HttpResponse { async fn index() -> HttpResponse {
HttpResponse::Ok().body("data") HttpResponse::Ok().body("data")
} }
pub fn main() { #[actix_rt::main]
async fn main() -> std::io::Result<()> {
use actix_web::{web, App, HttpServer}; use actix_web::{web, App, HttpServer};
HttpServer::new(|| { HttpServer::new(|| {
@ -13,9 +14,8 @@ pub fn main() {
.wrap(middleware::Compress::new(ContentEncoding::Br)) .wrap(middleware::Compress::new(ContentEncoding::Br))
.route("/", web::get().to(index)) .route("/", web::get().to(index))
}) })
.bind("127.0.0.1:8088") .bind("127.0.0.1:8088")?
.unwrap()
.run() .run()
.unwrap(); .await
} }
// </auto> // </auto>

View File

@ -1,13 +1,14 @@
// <brotli> // <brotli>
use actix_web::{http::ContentEncoding, middleware::BodyEncoding, HttpResponse}; use actix_web::{http::ContentEncoding, dev::BodyEncoding, HttpResponse};
fn index_br() -> HttpResponse { async fn index_br() -> HttpResponse {
HttpResponse::Ok() HttpResponse::Ok()
.encoding(ContentEncoding::Br) .encoding(ContentEncoding::Br)
.body("data") .body("data")
} }
pub fn main() { #[actix_rt::main]
async fn main() -> std::io::Result<()> {
use actix_web::{middleware, web, App, HttpServer}; use actix_web::{middleware, web, App, HttpServer};
HttpServer::new(|| { HttpServer::new(|| {
@ -15,9 +16,8 @@ pub fn main() {
.wrap(middleware::Compress::default()) .wrap(middleware::Compress::default())
.route("/", web::get().to(index_br)) .route("/", web::get().to(index_br))
}) })
.bind("127.0.0.1:8088") .bind("127.0.0.1:8088")?
.unwrap()
.run() .run()
.unwrap(); .await
} }
// </brotli> // </brotli>

View File

@ -1,11 +1,12 @@
// <brotli-two> // <brotli-two>
use actix_web::{http::ContentEncoding, middleware::BodyEncoding, HttpResponse}; use actix_web::{http::ContentEncoding, dev::BodyEncoding, HttpResponse};
fn index_br() -> HttpResponse { async fn index_br() -> HttpResponse {
HttpResponse::Ok().body("data") HttpResponse::Ok().body("data")
} }
pub fn main() { #[actix_rt::main]
async fn main() -> std::io::Result<()> {
use actix_web::{middleware, web, App, HttpServer}; use actix_web::{middleware, web, App, HttpServer};
HttpServer::new(|| { HttpServer::new(|| {
@ -13,9 +14,8 @@ pub fn main() {
.wrap(middleware::Compress::new(ContentEncoding::Br)) .wrap(middleware::Compress::new(ContentEncoding::Br))
.route("/", web::get().to(index_br)) .route("/", web::get().to(index_br))
}) })
.bind("127.0.0.1:8088") .bind("127.0.0.1:8088")?
.unwrap()
.run() .run()
.unwrap(); .await
} }
// </brotli-two> // </brotli-two>

View File

@ -1,11 +1,12 @@
// <compress> // <compress>
use actix_web::{middleware, HttpResponse}; use actix_web::{middleware, HttpResponse};
fn index_br() -> HttpResponse { async fn index_br() -> HttpResponse {
HttpResponse::Ok().body("data") HttpResponse::Ok().body("data")
} }
pub fn main() { #[actix_rt::main]
async fn main() -> std::io::Result<()> {
use actix_web::{web, App, HttpServer}; use actix_web::{web, App, HttpServer};
HttpServer::new(|| { HttpServer::new(|| {
@ -13,9 +14,8 @@ pub fn main() {
.wrap(middleware::Compress::default()) .wrap(middleware::Compress::default())
.route("/", web::get().to(index_br)) .route("/", web::get().to(index_br))
}) })
.bind("127.0.0.1:8088") .bind("127.0.0.1:8088")?
.unwrap()
.run() .run()
.unwrap(); .await
} }
// </compress> // </compress>

View File

@ -1,16 +1,17 @@
// <identity> // <identity>
use actix_web::{ use actix_web::{
http::ContentEncoding, middleware, middleware::BodyEncoding, HttpResponse, http::ContentEncoding, middleware, dev::BodyEncoding, HttpResponse,
}; };
fn index() -> HttpResponse { async fn index() -> HttpResponse {
HttpResponse::Ok() HttpResponse::Ok()
// v- disable compression // v- disable compression
.encoding(ContentEncoding::Identity) .encoding(ContentEncoding::Identity)
.body("data") .body("data")
} }
pub fn main() { #[actix_rt::main]
async fn main() -> std::io::Result<()> {
use actix_web::{web, App, HttpServer}; use actix_web::{web, App, HttpServer};
HttpServer::new(|| { HttpServer::new(|| {
@ -18,9 +19,8 @@ pub fn main() {
.wrap(middleware::Compress::default()) .wrap(middleware::Compress::default())
.route("/", web::get().to(index)) .route("/", web::get().to(index))
}) })
.bind("127.0.0.1:8088") .bind("127.0.0.1:8088")?
.unwrap()
.run() .run()
.unwrap(); .await
} }
// </identity> // </identity>

View File

@ -1,6 +1,6 @@
// <identity-two> // <identity-two>
use actix_web::{ use actix_web::{
http::ContentEncoding, middleware, middleware::BodyEncoding, HttpResponse, http::ContentEncoding, middleware, dev::BodyEncoding, HttpResponse,
}; };
static HELLO_WORLD: &[u8] = &[ static HELLO_WORLD: &[u8] = &[
@ -9,7 +9,7 @@ static HELLO_WORLD: &[u8] = &[
0x0c, 0x00, 0x00, 0x00, 0x0c, 0x00, 0x00, 0x00,
]; ];
pub fn index() -> HttpResponse { async fn index() -> HttpResponse {
HttpResponse::Ok() HttpResponse::Ok()
.encoding(ContentEncoding::Identity) .encoding(ContentEncoding::Identity)
.header("content-encoding", "gzip") .header("content-encoding", "gzip")
@ -17,7 +17,8 @@ pub fn index() -> HttpResponse {
} }
// </identity-two> // </identity-two>
pub fn main() { #[actix_rt::main]
async fn main() -> std::io::Result<()> {
use actix_web::{web, App, HttpServer}; use actix_web::{web, App, HttpServer};
HttpServer::new(|| { HttpServer::new(|| {
@ -25,8 +26,7 @@ pub fn main() {
.wrap(middleware::Compress::default()) .wrap(middleware::Compress::default())
.route("/", web::get().to(index)) .route("/", web::get().to(index))
}) })
.bind("127.0.0.1:8088") .bind("127.0.0.1:8088")?
.unwrap()
.run() .run()
.unwrap(); .await
} }

View File

@ -7,19 +7,19 @@ struct MyObj {
name: String, name: String,
} }
fn index(obj: web::Path<MyObj>) -> Result<HttpResponse> { async fn index(obj: web::Path<MyObj>) -> Result<HttpResponse> {
Ok(HttpResponse::Ok().json(MyObj { Ok(HttpResponse::Ok().json(MyObj {
name: obj.name.to_string(), name: obj.name.to_string(),
})) }))
} }
pub fn main() { #[actix_rt::main]
async fn main() -> std::io::Result<()> {
use actix_web::{App, HttpServer}; use actix_web::{App, HttpServer};
HttpServer::new(|| App::new().route(r"/a/{name}", web::get().to(index))) HttpServer::new(|| App::new().route(r"/a/{name}", web::get().to(index)))
.bind("127.0.0.1:8088") .bind("127.0.0.1:8088")?
.unwrap()
.run() .run()
.unwrap(); .await
} }
// </json-resp> // </json-resp>

View File

@ -9,7 +9,7 @@ pub mod json_resp;
// <builder> // <builder>
use actix_web::HttpResponse; use actix_web::HttpResponse;
fn index() -> HttpResponse { async fn index() -> HttpResponse {
HttpResponse::Ok() HttpResponse::Ok()
.content_type("plain/text") .content_type("plain/text")
.header("X-Hdr", "sample") .header("X-Hdr", "sample")
@ -17,12 +17,12 @@ fn index() -> HttpResponse {
} }
// </builder> // </builder>
pub fn main() { #[actix_rt::main]
async fn main() -> std::io::Result<()> {
use actix_web::{web, App, HttpServer}; use actix_web::{web, App, HttpServer};
HttpServer::new(|| App::new().route("/", web::get().to(index))) HttpServer::new(|| App::new().route("/", web::get().to(index)))
.bind("127.0.0.1:8088") .bind("127.0.0.1:8088")?
.unwrap()
.run() .run()
.unwrap(); .await
} }

View File

@ -5,8 +5,8 @@ workspace = "../"
edition = "2018" edition = "2018"
[dependencies] [dependencies]
actix-rt = "0.2" actix-rt = "1.0"
actix-web = { version = "1.0", features = ["ssl"] } actix-web = { version = "2.0", features = ["openssl"] }
futures = "0.1" futures = "0.3.1"
openssl = "0.10" openssl = "0.10"
actix-http = "0.2" actix-http = "1.0"

View File

@ -1,7 +1,8 @@
// <keep-alive> // <keep-alive>
use actix_web::{web, App, HttpResponse, HttpServer}; use actix_web::{web, App, HttpResponse, HttpServer};
pub fn main() { #[actix_rt::main]
async fn main() -> std::io::Result<()> {
let one = HttpServer::new(|| { let one = HttpServer::new(|| {
App::new().route("/", web::get().to(|| HttpResponse::Ok())) App::new().route("/", web::get().to(|| HttpResponse::Ok()))
}) })
@ -17,6 +18,6 @@ pub fn main() {
}) })
.keep_alive(None); // <- Disable keep-alive .keep_alive(None); // <- Disable keep-alive
one.bind("127.0.0.1:8088").unwrap().run().unwrap(); one.bind("127.0.0.1:8088")?.run().await
} }
// </keep-alive> // </keep-alive>

View File

@ -1,7 +1,7 @@
// <example> // <example>
use actix_web::{http, HttpRequest, HttpResponse}; use actix_web::{http, HttpRequest, HttpResponse};
pub fn index(req: HttpRequest) -> HttpResponse { async fn index(req: HttpRequest) -> HttpResponse {
HttpResponse::Ok() HttpResponse::Ok()
.connection_type(http::ConnectionType::Close) // <- Close connection .connection_type(http::ConnectionType::Close) // <- Close connection
.force_close() // <- Alternative method .force_close() // <- Alternative method

View File

@ -7,16 +7,13 @@ pub mod workers;
// <main> // <main>
use actix_web::{web, App, HttpResponse, HttpServer}; use actix_web::{web, App, HttpResponse, HttpServer};
fn main() { #[actix_rt::main]
let sys = actix_rt::System::new("example"); async fn main() -> std::io::Result<()> {
HttpServer::new(|| { HttpServer::new(|| {
App::new().route("/", web::get().to(|| HttpResponse::Ok())) App::new().route("/", web::get().to(|| HttpResponse::Ok()))
}) })
.bind("127.0.0.1:8088") .bind("127.0.0.1:8088")?
.unwrap() .run()
.start(); .await
let _ = sys.run();
} }
// </main> // </main>

View File

@ -1,7 +1,5 @@
use actix_rt;
use futures::Future;
// <signals> // <signals>
use actix_rt::System;
use actix_web::{web, App, HttpResponse, HttpServer}; use actix_web::{web, App, HttpResponse, HttpServer};
use std::sync::mpsc; use std::sync::mpsc;
use std::thread; use std::thread;
@ -10,7 +8,7 @@ pub fn main() {
let (tx, rx) = mpsc::channel(); let (tx, rx) = mpsc::channel();
thread::spawn(move || { thread::spawn(move || {
let sys = actix_rt::System::new("http-server"); let sys = System::new("http-server");
let addr = HttpServer::new(|| { let addr = HttpServer::new(|| {
App::new().route("/", web::get().to(|| HttpResponse::Ok())) App::new().route("/", web::get().to(|| HttpResponse::Ok()))
@ -18,24 +16,17 @@ pub fn main() {
.bind("127.0.0.1:8088") .bind("127.0.0.1:8088")
.unwrap() .unwrap()
.shutdown_timeout(60) // <- Set shutdown timeout to 60 seconds .shutdown_timeout(60) // <- Set shutdown timeout to 60 seconds
.start(); .run();
let _ = tx.send(addr); let _ = tx.send(addr);
let _ = sys.run();
}); });
let addr = rx.recv().unwrap(); let addr = rx.recv().unwrap();
let _ = addr let _ = System::new("`actix_server::ServerCommand::Pause`")
.pause() .block_on(addr.pause());
.wait() let _ = System::new("`actix_server::ServerCommand::Resume`")
.map(|_| println!("`actix_server::ServerCommand::Pause`")); .block_on(addr.resume());
let _ = addr let _ = System::new("`actix_server::ServerCommand::Stop`")
.resume() .block_on(addr.stop(true));
.wait()
.map(|_| println!("`actix_server::ServerCommand::Resume`"));
let _ = addr
.stop(true)
.wait()
.map(|_| println!("`actix_server::ServerCommand::Stop`"));
} }
// </signals> // </signals>

View File

@ -2,11 +2,12 @@
use actix_web::{web, App, HttpRequest, HttpServer, Responder}; use actix_web::{web, App, HttpRequest, HttpServer, Responder};
use openssl::ssl::{SslAcceptor, SslFiletype, SslMethod}; use openssl::ssl::{SslAcceptor, SslFiletype, SslMethod};
fn index(_req: HttpRequest) -> impl Responder { async fn index(_req: HttpRequest) -> impl Responder {
"Welcome!" "Welcome!"
} }
pub fn main() { #[actix_rt::main]
async fn main() -> std::io::Result<()> {
// load ssl keys // load ssl keys
// to create a self-signed temporary cert for testing: // to create a self-signed temporary cert for testing:
// `openssl req -x509 -newkey rsa:4096 -nodes -keyout key.pem -out cert.pem -days 365 -subj '/CN=localhost'` // `openssl req -x509 -newkey rsa:4096 -nodes -keyout key.pem -out cert.pem -days 365 -subj '/CN=localhost'`
@ -18,10 +19,9 @@ pub fn main() {
builder.set_certificate_chain_file("cert.pem").unwrap(); builder.set_certificate_chain_file("cert.pem").unwrap();
HttpServer::new(|| App::new().route("/", web::get().to(index))) HttpServer::new(|| App::new().route("/", web::get().to(index)))
.bind_ssl("127.0.0.1:8088", builder) .bind_openssl("127.0.0.1:8088", builder)?
.unwrap()
.run() .run()
.unwrap(); .await
} }
// </ssl> // </ssl>
// //

View File

@ -1,7 +1,8 @@
// <workers> // <workers>
use actix_web::{web, App, HttpResponse, HttpServer}; use actix_web::{web, App, HttpResponse, HttpServer};
pub fn main() { #[actix_rt::main]
async fn main() {
HttpServer::new(|| { HttpServer::new(|| {
App::new().route("/", web::get().to(|| HttpResponse::Ok())) App::new().route("/", web::get().to(|| HttpResponse::Ok()))
}) })

View File

@ -4,6 +4,7 @@ version = "1.0.0"
edition = "2018" edition = "2018"
[dependencies] [dependencies]
actix-web = "1.0" actix-web = "2.0"
actix-files = "0.1" actix-rt = "1.0"
actix-files = "0.2"
mime = "*" mime = "*"

View File

@ -3,7 +3,7 @@ use actix_files as fs;
use actix_web::http::header::{ContentDisposition, DispositionType}; use actix_web::http::header::{ContentDisposition, DispositionType};
use actix_web::{web, App, Error, HttpRequest, HttpServer}; use actix_web::{web, App, Error, HttpRequest, HttpServer};
fn index(req: HttpRequest) -> Result<fs::NamedFile, Error> { async fn index(req: HttpRequest) -> Result<fs::NamedFile, Error> {
let path: std::path::PathBuf = req.match_info().query("filename").parse().unwrap(); let path: std::path::PathBuf = req.match_info().query("filename").parse().unwrap();
let file = fs::NamedFile::open(path)?; let file = fs::NamedFile::open(path)?;
Ok(file Ok(file
@ -14,11 +14,11 @@ fn index(req: HttpRequest) -> Result<fs::NamedFile, Error> {
})) }))
} }
pub fn main() { #[actix_rt::main]
async fn main() -> std::io::Result<()> {
HttpServer::new(|| App::new().route("/{filename:.*}", web::get().to(index))) HttpServer::new(|| App::new().route("/{filename:.*}", web::get().to(index)))
.bind("127.0.0.1:8088") .bind("127.0.0.1:8088")?
.unwrap()
.run() .run()
.unwrap(); .await
} }
// </config-one> // </config-one>

View File

@ -2,7 +2,8 @@
use actix_files as fs; use actix_files as fs;
use actix_web::{App, HttpServer}; use actix_web::{App, HttpServer};
pub fn main() { #[actix_rt::main]
async fn main() -> std::io::Result<()> {
HttpServer::new(|| { HttpServer::new(|| {
App::new().service( App::new().service(
fs::Files::new("/static", ".") fs::Files::new("/static", ".")
@ -10,9 +11,8 @@ pub fn main() {
.use_last_modified(true), .use_last_modified(true),
) )
}) })
.bind("127.0.0.1:8088") .bind("127.0.0.1:8088")?
.unwrap()
.run() .run()
.unwrap(); .await
} }
// </config-two> // </config-two>

View File

@ -2,13 +2,13 @@
use actix_files as fs; use actix_files as fs;
use actix_web::{App, HttpServer}; use actix_web::{App, HttpServer};
pub fn main() { #[actix_rt::main]
async fn main() -> std::io::Result<()> {
HttpServer::new(|| { HttpServer::new(|| {
App::new().service(fs::Files::new("/static", ".").show_files_listing()) App::new().service(fs::Files::new("/static", ".").show_files_listing())
}) })
.bind("127.0.0.1:8088") .bind("127.0.0.1:8088")?
.unwrap()
.run() .run()
.unwrap(); .await
} }
// </directory> // </directory>

View File

@ -7,18 +7,18 @@ use actix_files::NamedFile;
use actix_web::{HttpRequest, Result}; use actix_web::{HttpRequest, Result};
use std::path::PathBuf; use std::path::PathBuf;
fn index(req: HttpRequest) -> Result<NamedFile> { async fn index(req: HttpRequest) -> Result<NamedFile> {
let path: PathBuf = req.match_info().query("filename").parse().unwrap(); let path: PathBuf = req.match_info().query("filename").parse().unwrap();
Ok(NamedFile::open(path)?) Ok(NamedFile::open(path)?)
} }
fn main() { #[actix_rt::main]
async fn main() -> std::io::Result<()> {
use actix_web::{web, App, HttpServer}; use actix_web::{web, App, HttpServer};
HttpServer::new(|| App::new().route("/{filename:.*}", web::get().to(index))) HttpServer::new(|| App::new().route("/{filename:.*}", web::get().to(index)))
.bind("127.0.0.1:8088") .bind("127.0.0.1:8088")?
.unwrap()
.run() .run()
.unwrap(); .await
} }
// </individual-file> // </individual-file>

View File

@ -5,8 +5,9 @@ edition = "2018"
workspace = "../" workspace = "../"
[dependencies] [dependencies]
actix = "0.8" actix = "0.9"
actix-web = "1.0" actix-rt = "1.0"
futures = "0.1" actix-web = "2.0"
futures = "0.3.1"
openssl = "0.10" openssl = "0.10"
serde = "1.0" serde = "1.0"

View File

@ -1,7 +1,8 @@
use actix_web::{guard, web, App, HttpResponse}; use actix_web::{guard, web, App, HttpResponse};
#[rustfmt::skip] #[rustfmt::skip]
pub fn main() { #[actix_rt::main]
async fn main() -> std::io::Result<()> {
use actix_web::HttpServer; use actix_web::HttpServer;
HttpServer::new(|| { HttpServer::new(|| {
@ -16,8 +17,7 @@ App::new().service(
) )
// </cfg> // </cfg>
}) })
.bind("127.0.0.1:8088") .bind("127.0.0.1:8088")?
.unwrap()
.run() .run()
.unwrap(); .await
} }

View File

@ -1,11 +1,12 @@
use actix_web::{guard, web, App, HttpRequest, HttpResponse, HttpServer, Responder}; use actix_web::{guard, web, App, HttpRequest, HttpResponse, HttpServer, Responder};
fn index(_req: HttpRequest) -> impl Responder { async fn index(_req: HttpRequest) -> impl Responder {
"Welcome!" "Welcome!"
} }
// <default> // <default>
pub fn main() { #[actix_rt::main]
async fn main() -> std::io::Result<()> {
HttpServer::new(|| { HttpServer::new(|| {
App::new() App::new()
.service(web::resource("/").route(web::get().to(index))) .service(web::resource("/").route(web::get().to(index)))
@ -15,9 +16,8 @@ pub fn main() {
.to(|| HttpResponse::MethodNotAllowed()), .to(|| HttpResponse::MethodNotAllowed()),
) )
}) })
.bind("127.0.0.1:8088") .bind("127.0.0.1:8088")?
.unwrap()
.run() .run()
.unwrap(); .await
} }
// </default> // </default>

View File

@ -9,7 +9,8 @@ impl Guard for ContentTypeHeader {
} }
} }
pub fn main() { #[actix_rt::main]
async fn main() -> std::io::Result<()> {
use actix_web::{web, App, HttpServer}; use actix_web::{web, App, HttpServer};
HttpServer::new(|| { HttpServer::new(|| {
@ -20,9 +21,8 @@ pub fn main() {
.to(|| HttpResponse::Ok()), .to(|| HttpResponse::Ok()),
) )
}) })
.bind("127.0.0.1:8088") .bind("127.0.0.1:8088")?
.unwrap()
.run() .run()
.unwrap(); .await
} }
// </guard> // </guard>

View File

@ -1,7 +1,8 @@
// <guard2> // <guard2>
use actix_web::{guard, web, App, HttpResponse, HttpServer}; use actix_web::{guard, web, App, HttpResponse, HttpServer};
pub fn main() { #[actix_rt::main]
async fn main() -> std::io::Result<()> {
HttpServer::new(|| { HttpServer::new(|| {
App::new().route( App::new().route(
"/", "/",
@ -10,9 +11,8 @@ pub fn main() {
.to(|| HttpResponse::MethodNotAllowed()), .to(|| HttpResponse::MethodNotAllowed()),
) )
}) })
.bind("127.0.0.1:8088") .bind("127.0.0.1:8088")?
.unwrap()
.run() .run()
.unwrap(); .await
} }
// </guard2> // </guard2>

View File

@ -16,19 +16,19 @@ pub mod urls;
// <main> // <main>
use actix_web::{web, App, HttpResponse, HttpServer}; use actix_web::{web, App, HttpResponse, HttpServer};
fn index() -> HttpResponse { async fn index() -> HttpResponse {
HttpResponse::Ok().body("Hello") HttpResponse::Ok().body("Hello")
} }
fn main() { #[actix_rt::main]
async fn main() -> std::io::Result<()> {
HttpServer::new(|| { HttpServer::new(|| {
App::new() App::new()
.route("/", web::get().to(index)) .route("/", web::get().to(index))
.route("/user", web::post().to(index)) .route("/user", web::post().to(index))
}) })
.bind("127.0.0.1:8088") .bind("127.0.0.1:8088")?
.unwrap()
.run() .run()
.unwrap(); .await
} }
// </main> // </main>

View File

@ -1,14 +1,15 @@
// <minfo> // <minfo>
use actix_web::{HttpRequest, HttpResponse, Result}; use actix_web::{HttpRequest, HttpResponse, Result};
fn index(req: HttpRequest) -> Result<String> { async fn index(req: HttpRequest) -> Result<String> {
let v1: u8 = req.match_info().get("v1").unwrap().parse().unwrap(); let v1: u8 = req.match_info().get("v1").unwrap().parse().unwrap();
let v2: u8 = req.match_info().query("v2").parse().unwrap(); let v2: u8 = req.match_info().query("v2").parse().unwrap();
let (v3, v4): (u8, u8) = req.match_info().load().unwrap(); let (v3, v4): (u8, u8) = req.match_info().load().unwrap();
Ok(format!("Values {} {} {} {}", v1, v2, v3, v4)) Ok(format!("Values {} {} {} {}", v1, v2, v3, v4))
} }
pub fn main() { #[actix_rt::main]
async fn main() -> std::io::Result<()> {
use actix_web::{web, App, HttpServer}; use actix_web::{web, App, HttpServer};
HttpServer::new(|| { HttpServer::new(|| {
@ -16,9 +17,8 @@ pub fn main() {
.route("/a/{v1}/{v2}/", web::get().to(index)) .route("/a/{v1}/{v2}/", web::get().to(index))
.route("", web::get().to(|| HttpResponse::Ok())) .route("", web::get().to(|| HttpResponse::Ok()))
}) })
.bind("127.0.0.1:8088") .bind("127.0.0.1:8088")?
.unwrap()
.run() .run()
.unwrap(); .await
} }
// </minfo> // </minfo>

View File

@ -1,11 +1,12 @@
// <norm> // <norm>
use actix_web::{middleware, HttpResponse}; use actix_web::{middleware, HttpResponse};
fn index() -> HttpResponse { async fn index() -> HttpResponse {
HttpResponse::Ok().body("Hello") HttpResponse::Ok().body("Hello")
} }
pub fn main() { #[actix_rt::main]
async fn main() -> std::io::Result<()> {
use actix_web::{web, App, HttpServer}; use actix_web::{web, App, HttpServer};
HttpServer::new(|| { HttpServer::new(|| {
@ -13,9 +14,8 @@ pub fn main() {
.wrap(middleware::NormalizePath) .wrap(middleware::NormalizePath)
.route("/resource/", web::to(index)) .route("/resource/", web::to(index))
}) })
.bind("127.0.0.1:8088") .bind("127.0.0.1:8088")?
.unwrap()
.run() .run()
.unwrap(); .await
} }
// </norm> // </norm>

View File

@ -7,16 +7,16 @@ fn index() -> HttpResponse {
// <norm> // <norm>
use actix_web::{http::Method, middleware, web, App, HttpServer}; use actix_web::{http::Method, middleware, web, App, HttpServer};
pub fn main() { #[actix_rt::main]
async fn main() -> std::io::Result<()> {
HttpServer::new(|| { HttpServer::new(|| {
App::new() App::new()
.wrap(middleware::NormalizePath) .wrap(middleware::NormalizePath)
.route("/resource/", web::get().to(index)) .route("/resource/", web::get().to(index))
.default_service(web::route().method(Method::GET)) .default_service(web::route().method(Method::GET))
}) })
.bind("127.0.0.1:8088") .bind("127.0.0.1:8088")?
.unwrap()
.run() .run()
.unwrap(); .await
} }
// </norm> // </norm>

View File

@ -1,11 +1,12 @@
// <path> // <path>
use actix_web::{web, Result}; use actix_web::{web, Result};
fn index(info: web::Path<(String, u32)>) -> Result<String> { async fn index(info: web::Path<(String, u32)>) -> Result<String> {
Ok(format!("Welcome {}! id: {}", info.0, info.1)) Ok(format!("Welcome {}! id: {}", info.0, info.1))
} }
pub fn main() { #[actix_rt::main]
async fn main() -> std::io::Result<()> {
use actix_web::{App, HttpServer}; use actix_web::{App, HttpServer};
HttpServer::new(|| { HttpServer::new(|| {
@ -14,9 +15,8 @@ pub fn main() {
web::get().to(index), web::get().to(index),
) )
}) })
.bind("127.0.0.1:8088") .bind("127.0.0.1:8088")?
.unwrap()
.run() .run()
.unwrap(); .await
} }
// </path> // </path>

View File

@ -8,11 +8,12 @@ struct Info {
} }
// extract path info using serde // extract path info using serde
fn index(info: web::Path<Info>) -> Result<String> { async fn index(info: web::Path<Info>) -> Result<String> {
Ok(format!("Welcome {}!", info.username)) Ok(format!("Welcome {}!", info.username))
} }
pub fn main() { #[actix_rt::main]
async fn main() -> std::io::Result<()> {
use actix_web::{App, HttpServer}; use actix_web::{App, HttpServer};
HttpServer::new(|| { HttpServer::new(|| {
@ -21,9 +22,8 @@ pub fn main() {
web::get().to(index), web::get().to(index),
) )
}) })
.bind("127.0.0.1:8088") .bind("127.0.0.1:8088")?
.unwrap()
.run() .run()
.unwrap(); .await
} }
// </path> // </path>

View File

@ -2,18 +2,18 @@
use actix_web::{HttpRequest, Result}; use actix_web::{HttpRequest, Result};
use std::path::PathBuf; use std::path::PathBuf;
fn index(req: HttpRequest) -> Result<String> { async fn index(req: HttpRequest) -> Result<String> {
let path: PathBuf = req.match_info().query("tail").parse().unwrap(); let path: PathBuf = req.match_info().query("tail").parse().unwrap();
Ok(format!("Path {:?}", path)) Ok(format!("Path {:?}", path))
} }
pub fn main() { #[actix_rt::main]
async fn main() -> std::io::Result<()> {
use actix_web::{web, App, HttpServer}; use actix_web::{web, App, HttpServer};
HttpServer::new(|| App::new().route(r"/a/{tail:.*}", web::get().to(index))) HttpServer::new(|| App::new().route(r"/a/{tail:.*}", web::get().to(index)))
.bind("127.0.0.1:8088") .bind("127.0.0.1:8088")?
.unwrap()
.run() .run()
.unwrap(); .await
} }
// </pbuf> // </pbuf>

View File

@ -1,15 +1,16 @@
use actix_web::{web, App, HttpResponse, HttpServer}; use actix_web::{web, App, HttpResponse, HttpServer};
// <scope> // <scope>
fn show_users() -> HttpResponse { async fn show_users() -> HttpResponse {
HttpResponse::Ok().body("Show users") HttpResponse::Ok().body("Show users")
} }
fn user_detail(path: web::Path<(u32,)>) -> HttpResponse { async fn user_detail(path: web::Path<(u32,)>) -> HttpResponse {
HttpResponse::Ok().body(format!("User detail: {}", path.0)) HttpResponse::Ok().body(format!("User detail: {}", path.0))
} }
pub fn main() { #[actix_rt::main]
async fn main() -> std::io::Result<()> {
HttpServer::new(|| { HttpServer::new(|| {
App::new().service( App::new().service(
web::scope("/users") web::scope("/users")
@ -17,9 +18,8 @@ pub fn main() {
.route("/show/{id}", web::get().to(user_detail)), .route("/show/{id}", web::get().to(user_detail)),
) )
}) })
.bind("127.0.0.1:8088") .bind("127.0.0.1:8088")?
.unwrap()
.run() .run()
.unwrap(); .await
} }
// </scope> // </scope>

View File

@ -1,14 +1,15 @@
// <ext> // <ext>
use actix_web::{HttpRequest, Responder}; use actix_web::{HttpRequest, Responder};
fn index(req: HttpRequest) -> impl Responder { async fn index(req: HttpRequest) -> impl Responder {
let url = req.url_for("youtube", &["oHg5SJYRHA0"]).unwrap(); let url = req.url_for("youtube", &["oHg5SJYRHA0"]).unwrap();
assert_eq!(url.as_str(), "https://youtube.com/watch/oHg5SJYRHA0"); assert_eq!(url.as_str(), "https://youtube.com/watch/oHg5SJYRHA0");
url.into_string() url.into_string()
} }
pub fn main() { #[actix_rt::main]
async fn main() -> std::io::Result<()> {
use actix_web::{web, App, HttpServer}; use actix_web::{web, App, HttpServer};
HttpServer::new(|| { HttpServer::new(|| {
@ -17,9 +18,8 @@ pub fn main() {
.external_resource("youtube", "https://youtube.com/watch/{video_id}") .external_resource("youtube", "https://youtube.com/watch/{video_id}")
.route("/", actix_web::web::get().to(index)) .route("/", actix_web::web::get().to(index))
}) })
.bind("127.0.0.1:8088") .bind("127.0.0.1:8088")?
.unwrap()
.run() .run()
.unwrap(); .await
} }
// </ext> // </ext>

View File

@ -1,7 +1,7 @@
// <url> // <url>
use actix_web::{guard, http::header, HttpRequest, HttpResponse, Result}; use actix_web::{guard, http::header, HttpRequest, HttpResponse, Result};
fn index(req: HttpRequest) -> Result<HttpResponse> { async fn index(req: HttpRequest) -> Result<HttpResponse> {
let url = req.url_for("foo", &["1", "2", "3"])?; // <- generate url for "foo" resource let url = req.url_for("foo", &["1", "2", "3"])?; // <- generate url for "foo" resource
Ok(HttpResponse::Found() Ok(HttpResponse::Found()
@ -9,7 +9,8 @@ fn index(req: HttpRequest) -> Result<HttpResponse> {
.finish()) .finish())
} }
pub fn main() { #[actix_rt::main]
async fn main() -> std::io::Result<()> {
use actix_web::{web, App, HttpServer}; use actix_web::{web, App, HttpServer};
HttpServer::new(|| { HttpServer::new(|| {
@ -22,9 +23,8 @@ pub fn main() {
) )
.route("/test/", web::get().to(index)) .route("/test/", web::get().to(index))
}) })
.bind("127.0.0.1:8088") .bind("127.0.0.1:8088")?
.unwrap()
.run() .run()
.unwrap(); .await
} }
// </url> // </url>

View File

@ -4,6 +4,7 @@ version = "1.0.0"
edition = "2018" edition = "2018"
[dependencies] [dependencies]
actix = "0.8" actix = "0.9"
actix-web = "1.0" actix-rt = "1.0"
actix-web-actors = "1.0" actix-web = "2.0"
actix-web-actors = "2.0"

View File

@ -11,29 +11,33 @@ impl Actor for MyWs {
} }
/// Handler for ws::Message message /// Handler for ws::Message message
impl StreamHandler<ws::Message, ws::ProtocolError> for MyWs { impl StreamHandler<Result<ws::Message, ws::ProtocolError>> for MyWs {
fn handle(&mut self, msg: ws::Message, ctx: &mut Self::Context) { fn handle(
&mut self,
msg: Result<ws::Message, ws::ProtocolError>,
ctx: &mut Self::Context,
) {
match msg { match msg {
ws::Message::Ping(msg) => ctx.pong(&msg), Ok(ws::Message::Ping(msg)) => ctx.pong(&msg),
ws::Message::Text(text) => ctx.text(text), Ok(ws::Message::Text(text)) => ctx.text(text),
ws::Message::Binary(bin) => ctx.binary(bin), Ok(ws::Message::Binary(bin)) => ctx.binary(bin),
_ => (), _ => (),
} }
} }
} }
fn index(req: HttpRequest, stream: web::Payload) -> Result<HttpResponse, Error> { async fn index(req: HttpRequest, stream: web::Payload) -> Result<HttpResponse, Error> {
let resp = ws::start(MyWs {}, &req, stream); let resp = ws::start(MyWs {}, &req, stream);
println!("{:?}", resp); println!("{:?}", resp);
resp resp
} }
fn main() { #[actix_rt::main]
async fn main() -> std::io::Result<()> {
HttpServer::new(|| App::new().route("/ws/", web::get().to(index))) HttpServer::new(|| App::new().route("/ws/", web::get().to(index)))
.bind("127.0.0.1:8088") .bind("127.0.0.1:8088")?
.unwrap()
.run() .run()
.unwrap(); .await
} }
// </websockets> // </websockets>