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
[params]
actixVersion = "0.7"
actixWebVersion = "1.0"
actixWebMinRustVersion = "1.36"
actixMinRustVersion = "1.31"
actixVersion = "0.9"
actixWebVersion = "2.0"
actixWebMinRustVersion = "1.39"
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
[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
[guardfuncs]: https://docs.rs/actix-web/1.0.2/actix_web/guard/index.html#functions
[guardheader]: ((https://docs.rs/actix-web/1.0.2/actix_web/guard/fn.Header.html
[guardtrait]: https://docs.rs/actix-web/2/actix_web/guard/trait.Guard.html
[guardfuncs]: https://docs.rs/actix-web/2/actix_web/guard/index.html#functions
[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" >}}
[actixerror]: https://docs.rs/actix-web/1.0.2/actix_web/error/struct.Error.html
[errorhelpers]: https://docs.rs/actix-web/1.0.2/actix_web/trait.ResponseError.html
[actixerror]: https://docs.rs/actix-web/2/actix_web/error/struct.Error.html
[errorhelpers]: https://docs.rs/actix-web/2/actix_web/trait.ResponseError.html
[failure]: https://github.com/rust-lang-nursery/failure
[responseerror]: https://docs.rs/actix-web/1.0.2/actix_web/error/trait.ResponseError.html
[responseerrorimpls]: https://docs.rs/actix-web/1.0.2/actix_web/error/trait.ResponseError.html#foreign-impls
[responseerror]: https://docs.rs/actix-web/2/actix_web/error/trait.ResponseError.html
[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

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
> 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
[querystruct]: https://docs.rs/actix-web/1.0.2/actix_web/web/struct.Query.html
[jsonstruct]: https://docs.rs/actix-web/1.0.2/actix_web/web/struct.Json.html
[jsonconfig]: https://docs.rs/actix-web/1.0.2/actix_web/web/struct.JsonConfig.html
[formconfig]: https://docs.rs/actix-web/1.0.2/actix_web/web/struct.FormConfig.html
[datastruct]: https://docs.rs/actix-web/1.0.2/actix_web/web/struct.Data.html
[stringexample]: https://docs.rs/actix-web/1.0.2/actix_web/trait.FromRequest.html#example-2
[bytesexample]: https://docs.rs/actix-web/1.0.2/actix_web/trait.FromRequest.html#example-4
[payloadexample]: https://docs.rs/actix-web/1.0.2/actix_web/web/struct.Payload.html
[pathstruct]: https://docs.rs/actix-web/2/actix_web/dev/struct.Path.html
[querystruct]: https://docs.rs/actix-web/2/actix_web/web/struct.Query.html
[jsonstruct]: https://docs.rs/actix-web/2/actix_web/web/struct.Json.html
[jsonconfig]: https://docs.rs/actix-web/2/actix_web/web/struct.JsonConfig.html
[formconfig]: https://docs.rs/actix-web/2/actix_web/web/struct.FormConfig.html
[datastruct]: https://docs.rs/actix-web/2/actix_web/web/struct.Data.html
[stringexample]: https://docs.rs/actix-web/2/actix_web/trait.FromRequest.html#example-2
[bytesexample]: https://docs.rs/actix-web/2/actix_web/trait.FromRequest.html#example-4
[payloadexample]: https://docs.rs/actix-web/2/actix_web/web/struct.Payload.html
[actix]: https://actix.github.io/actix/actix/

View File

@ -13,11 +13,11 @@ weight: 250
> Currently, only `rust-openssl` has support.
`alpn` negotiation requires enabling the feature. When enabled, `HttpServer` provides the
[bind_ssl][bindssl] method.
[bind_openssl][bindopenssl] method.
```toml
[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"] }
```
{{< 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
[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
[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" >}}
[sessionobj]: https://docs.rs/actix-session/0.1.1/actix_session/struct.Session.html
[requestsession]: https://docs.rs/actix-session/0.1.1/actix_session/struct.Session.html
[cookiesession]: https://docs.rs/actix-session/0.1.1/actix_session/struct.CookieSession.html
[actixsession]: https://docs.rs/actix-session/0.1.1/actix_session/
[sessionobj]: https://docs.rs/actix-session/0.3.0/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.3.0/actix_session/struct.CookieSession.html
[actixsession]: https://docs.rs/actix-session/0.3.0/actix_session/
[envlogger]: https://docs.rs/env_logger/*/env_logger/
[servicetrait]: https://docs.rs/actix-web/1.0.2/actix_web/dev/trait.Service.html
[transformtrait]: https://docs.rs/actix-web/1.0.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
[servicetrait]: https://docs.rs/actix-web/2/actix_web/dev/trait.Service.html
[transformtrait]: https://docs.rs/actix-web/2/actix_web/dev/trait.Transform.html
[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" >}}
[examples]: https://github.com/actix/examples/tree/master/json/
[multipartstruct]: https://docs.rs/actix-multipart/0.1.2/actix_multipart/struct.Multipart.html
[fieldstruct]: https://docs.rs/actix-multipart/0.1.2/actix_multipart/struct.Field.html
[multipartstruct]: https://docs.rs/actix-multipart/0.2/actix_multipart/struct.Multipart.html
[fieldstruct]: https://docs.rs/actix-multipart/0.2/actix_multipart/struct.Field.html
[multipartexample]: https://github.com/actix/examples/tree/master/multipart/
[urlencoded]: https://docs.rs/actix-web/1.0.2/actix_web/dev/struct.UrlEncoded.html
[payloadextractor]: https://docs.rs/actix-web/1.0.2/actix_web/web/struct.Payload.html
[urlencoded]: https://docs.rs/actix-web/2/actix_web/dev/struct.UrlEncoded.html
[payloadextractor]: https://docs.rs/actix-web/2/actix_web/web/struct.Payload.html
[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" >}}
[responsebuilder]: https://docs.rs/actix-web/1.0.2/actix_web/dev/struct.HttpResponseBuilder.html
[compressmidddleware]: https://docs.rs/actix-web/1.0.2/actix_web/middleware/struct.Compress.html
[responsebuilder]: https://docs.rs/actix-web/2/actix_web/dev/struct.HttpResponseBuilder.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.
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
start methods.
@ -117,13 +117,13 @@ are available on unix systems.
> It is possible to disable signal handling with
[`HttpServer::disable_signals()`][disablesignals] method.
[httpserverstruct]: https://docs.rs/actix-web/1.0.2/actix_web/struct.HttpServer.html
[bindmethod]: https://docs.rs/actix-web/1.0.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
[bindrusttls]: https://docs.rs/actix-web/1.0.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
[workers]: https://docs.rs/actix-web/1.0.2/actix_web/struct.HttpServer.html#method.workers
[httpserverstruct]: https://docs.rs/actix-web/2/actix_web/struct.HttpServer.html
[bindmethod]: https://docs.rs/actix-web/2/actix_web/struct.HttpServer.html#method.bind
[bindopensslmethod]: https://docs.rs/actix-web/2/actix_web/struct.HttpServer.html#method.bind_openssl
[bindrusttls]: https://docs.rs/actix-web/2/actix_web/struct.HttpServer.html#method.bind_rustls
[startmethod]: https://docs.rs/actix-web/2/actix_web/struct.HttpServer.html#method.start
[workers]: https://docs.rs/actix-web/2/actix_web/struct.HttpServer.html#method.workers
[tlsalpn]: https://tools.ietf.org/html/rfc7301
[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
[disablesignals]: https://docs.rs/actix-web/1.0.2/actix_web/struct.HttpServer.html#method.disable_signals
[shutdowntimeout]: https://docs.rs/actix-web/2/actix_web/struct.HttpServer.html#method.shutdown_timeout
[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" >}}
[showfileslisting]: https://docs.rs/actix-files/0.1.2/actix_files/struct.Files.html
[indexfile]: https://docs.rs/actix-files/0.1.2/actix_files/struct.Files.html#method.index_file
[showfileslisting]: https://docs.rs/actix-files/0.2/actix_files/struct.Files.html
[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" >}}
[handlersection]: ../handlers/
[approute]: https://docs.rs/actix-web/1.0.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
[webresource]: https://docs.rs/actix-web/1.0.2/actix_web/struct.Resource.html
[resourcehandler]: https://docs.rs/actix-web/1.0.2/actix_web/struct.Resource.html#method.route
[route]: https://docs.rs/actix-web/1.0.2/actix_web/struct.Route.html
[routeguard]: https://docs.rs/actix-web/1.0.2/actix_web/struct.Route.html#method.guard
[routemethod]: https://docs.rs/actix-web/1.0.2/actix_web/struct.Route.html#method.method
[routeto]: https://docs.rs/actix-web/1.0.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
[matchinfo]: https://docs.rs/actix-web/1.0.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
[pathstruct]: https://docs.rs/actix-web/1.0.2/actix_web/dev/struct.Path.html
[query]: https://docs.rs/actix-web/1.0.2/actix_web/web/struct.Query.html
[urlfor]: https://docs.rs/actix-web/1.0.2/actix_web/struct.HttpRequest.html#method.url_for
[approute]: https://docs.rs/actix-web/2/actix_web/struct.App.html#method.route
[appservice]: https://docs.rs/actix-web/2/actix_web/struct.App.html?search=#method.service
[webresource]: https://docs.rs/actix-web/2/actix_web/struct.Resource.html
[resourcehandler]: https://docs.rs/actix-web/2/actix_web/struct.Resource.html#method.route
[route]: https://docs.rs/actix-web/2/actix_web/struct.Route.html
[routeguard]: https://docs.rs/actix-web/2/actix_web/struct.Route.html#method.guard
[routemethod]: https://docs.rs/actix-web/2/actix_web/struct.Route.html#method.method
[routeto]: https://docs.rs/actix-web/2/actix_web/struct.Route.html#method.to
[routetoasync]: https://docs.rs/actix-web/2/actix_web/struct.Route.html#method.to_async
[matchinfo]: https://docs.rs/actix-web/2/actix_web/struct.HttpRequest.html#method.match_info
[pathget]: https://docs.rs/actix-web/2/actix_web/dev/struct.Path.html#method.get
[pathstruct]: https://docs.rs/actix-web/2/actix_web/dev/struct.Path.html
[query]: https://docs.rs/actix-web/2/actix_web/web/struct.Query.html
[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
[guardtrait]: https://docs.rs/actix-web/1.0.2/actix_web/guard/trait.Guard.html
[guardfuncs]: https://docs.rs/actix-web/1.0.2/actix_web/guard/index.html#functions
[requestextensions]: https://docs.rs/actix-web/1.0.2/actix_web/struct.HttpRequest.html#method.extensions
[implfromrequest]: https://docs.rs/actix-web/1.0.2/actix_web/trait.FromRequest.html
[implresponder]: https://docs.rs/actix-web/1.0.2/actix_web/trait.Responder.html
[guardtrait]: https://docs.rs/actix-web/2/actix_web/guard/trait.Guard.html
[guardfuncs]: https://docs.rs/actix-web/2/actix_web/guard/index.html#functions
[requestextensions]: https://docs.rs/actix-web/2/actix_web/struct.HttpRequest.html#method.extensions
[implfromrequest]: https://docs.rs/actix-web/2/actix_web/trait.FromRequest.html
[implresponder]: https://docs.rs/actix-web/2/actix_web/trait.Responder.html
[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
> is available in [websocket-chat directory][chat]
[message]: https://docs.rs/actix-web-actors/1.0.0/actix_web_actors/ws/enum.Message.html
[payload]: https://docs.rs/actix-web/1.0.2/actix_web/web/struct.Payload.html
[message]: https://docs.rs/actix-web-actors/2/actix_web_actors/ws/enum.Message.html
[payload]: https://docs.rs/actix-web/2/actix_web/web/struct.Payload.html
[examples]: https://github.com/actix/examples/tree/master/websocket/
[chat]: https://github.com/actix/examples/tree/master/websocket-chat/

View File

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

View File

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

View File

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

View File

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

View File

@ -7,7 +7,7 @@ struct AppState {
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
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
}
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
*counter += 1; // <- access counter inside MutexGuard
@ -28,25 +28,26 @@ fn _index(data: web::Data<AppStateWithCounter>) -> String {
// </setup_mutable>
// <make_app_mutable>
fn _main() {
#[actix_rt::main]
async fn _main() -> std::io::Result<()> {
let counter = web::Data::new(AppStateWithCounter {
counter: Mutex::new(0),
});
HttpServer::new(move || { // move counter into the closure
App::new()
.register_data(counter.clone()) // <- register the created data
.app_data(counter.clone()) // <- register the created data
.route("/", web::get().to(_index))
})
.bind("127.0.0.1:8088")
.unwrap()
.bind("127.0.0.1:8088")?
.run()
.unwrap();
.await
}
// </make_app_mutable>
// <start_app>
pub fn main() {
#[actix_rt::main]
async fn main() -> std::io::Result<()> {
HttpServer::new(|| {
App::new()
.data(AppState {
@ -54,9 +55,8 @@ pub fn main() {
})
.route("/", web::get().to(index))
})
.bind("127.0.0.1:8088")
.unwrap()
.bind("127.0.0.1:8088")?
.run()
.unwrap();
.await
}
// </start_app>

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -4,5 +4,6 @@ version = "1.0.0"
edition = "2018"
[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"] }

View File

@ -2,11 +2,12 @@
use actix_web::{web, App, HttpRequest, HttpServer, Responder};
use openssl::ssl::{SslAcceptor, SslFiletype, SslMethod};
fn index(_req: HttpRequest) -> impl Responder {
async fn index(_req: HttpRequest) -> impl Responder {
"Hello."
}
fn main() {
#[actix_rt::main]
async fn main() -> std::io::Result<()> {
// load ssl keys
// 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'`
@ -17,9 +18,8 @@ fn main() {
builder.set_certificate_chain_file("cert.pem").unwrap();
HttpServer::new(|| App::new().route("/", web::get().to(index)))
.bind_ssl("127.0.0.1:8088", builder)
.unwrap()
.bind_openssl("127.0.0.1:8088", builder)?
.run()
.unwrap();
.await
}
// </main>

View File

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

View File

@ -1,20 +1,20 @@
// <main-example>
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");
format!("Hello {}!", &name)
}
fn main() {
#[actix_rt::main]
async fn main() -> std::io::Result<()> {
HttpServer::new(|| {
App::new()
.route("/", web::get().to(greet))
.route("/{name}", web::get().to(greet))
})
.bind("127.0.0.1:8088")
.unwrap()
.bind("127.0.0.1:8088")?
.run()
.unwrap();
.await
}
// </main-example>

View File

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

View File

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

View File

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

View File

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

View File

@ -5,10 +5,13 @@ pub mod user_sessions;
pub mod wrap_fn;
// <simple>
use std::pin::Pin;
use std::task::{Context, Poll};
use actix_service::{Service, Transform};
use actix_web::{dev::ServiceRequest, dev::ServiceResponse, Error};
use futures::future::{ok, FutureResult};
use futures::{Future, Poll};
use futures::future::{ok, Ready};
use futures::Future;
// There are two steps in middleware processing.
// 1. Middleware initialization, middleware factory gets called with
@ -30,7 +33,7 @@ where
type Error = Error;
type InitError = ();
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 {
ok(SayHiMiddleware { service })
@ -50,34 +53,40 @@ where
type Request = ServiceRequest;
type Response = ServiceResponse<B>;
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> {
self.service.poll_ready()
fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
self.service.poll_ready(cx)
}
fn call(&mut self, req: ServiceRequest) -> Self::Future {
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");
Ok(res)
}))
})
}
}
// </simple>
fn main() {
#[actix_rt::main]
async fn main() -> std::io::Result<()> {
use actix_web::{web, App, HttpServer};
HttpServer::new(|| {
App::new().wrap(SayHi).service(
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")
.unwrap()
.bind("127.0.0.1:8088")?
.run()
.unwrap();
.await
}

View File

@ -2,7 +2,7 @@
use actix_session::{CookieSession, Session};
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
if let Some(count) = session.get::<i32>("counter")? {
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(|| {
App::new()
.wrap(
@ -25,9 +26,8 @@ pub fn main() {
)
.service(web::resource("/").to(index))
})
.bind("127.0.0.1:8088")
.unwrap()
.bind("127.0.0.1:8088")?
.run()
.unwrap();
.await
}
// </user-session>

View File

@ -1,9 +1,10 @@
// <wrap-fn>
use actix_service::Service;
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()
.wrap_fn(|req, srv| {
println!("Hi from start. You requested: {}", req.path());
@ -14,7 +15,9 @@ fn main() {
})
.route(
"/index.html",
web::get().to(|| "Hello, middleware!"),
web::get().to(|| async {
"Hello, middleware!"
}),
);
}
// </wrap-fn>

View File

@ -4,5 +4,6 @@ version = "1.0.0"
edition = "2018"
[dependencies]
actix-web = "1.0"
actix-web = "2.0"
actix-rt = "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);
format!("got event {}", new_event.id.unwrap())
}
fn index() -> HttpResponse {
async fn index() -> HttpResponse {
HttpResponse::Ok()
.content_type("text/html; charset=utf-8")
.body(include_str!("../static/form.html"))
}
fn main() {
#[actix_rt::main]
async fn main() -> std::io::Result<()> {
HttpServer::new(|| {
App::new()
.route("/", web::get().to(index))
.route("/event", web::post().to(capture_event))
})
.bind("127.0.0.1:8088")
.unwrap()
.bind("127.0.0.1:8088")?
.run()
.unwrap();
.await
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -14,15 +14,15 @@ struct Info {
}
/// 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))
}
fn main() {
#[actix_rt::main]
async fn main() -> std::io::Result<()> {
HttpServer::new(|| App::new().route("/", web::post().to(index)))
.bind("127.0.0.1:8088")
.unwrap()
.bind("127.0.0.1:8088")?
.run()
.unwrap();
.await
}
// </json-request>

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -1,7 +1,8 @@
// <keep-alive>
use actix_web::{web, App, HttpResponse, HttpServer};
pub fn main() {
#[actix_rt::main]
async fn main() -> std::io::Result<()> {
let one = HttpServer::new(|| {
App::new().route("/", web::get().to(|| HttpResponse::Ok()))
})
@ -17,6 +18,6 @@ pub fn main() {
})
.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>

View File

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

View File

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

View File

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

View File

@ -2,11 +2,12 @@
use actix_web::{web, App, HttpRequest, HttpServer, Responder};
use openssl::ssl::{SslAcceptor, SslFiletype, SslMethod};
fn index(_req: HttpRequest) -> impl Responder {
async fn index(_req: HttpRequest) -> impl Responder {
"Welcome!"
}
pub fn main() {
#[actix_rt::main]
async fn main() -> std::io::Result<()> {
// load ssl keys
// 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'`
@ -18,10 +19,9 @@ pub fn main() {
builder.set_certificate_chain_file("cert.pem").unwrap();
HttpServer::new(|| App::new().route("/", web::get().to(index)))
.bind_ssl("127.0.0.1:8088", builder)
.unwrap()
.bind_openssl("127.0.0.1:8088", builder)?
.run()
.unwrap();
.await
}
// </ssl>
//

View File

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

View File

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

View File

@ -3,7 +3,7 @@ use actix_files as fs;
use actix_web::http::header::{ContentDisposition, DispositionType};
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 file = fs::NamedFile::open(path)?;
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)))
.bind("127.0.0.1:8088")
.unwrap()
.bind("127.0.0.1:8088")?
.run()
.unwrap();
.await
}
// </config-one>

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -1,14 +1,15 @@
// <minfo>
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 v2: u8 = req.match_info().query("v2").parse().unwrap();
let (v3, v4): (u8, u8) = req.match_info().load().unwrap();
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};
HttpServer::new(|| {
@ -16,9 +17,8 @@ pub fn main() {
.route("/a/{v1}/{v2}/", web::get().to(index))
.route("", web::get().to(|| HttpResponse::Ok()))
})
.bind("127.0.0.1:8088")
.unwrap()
.bind("127.0.0.1:8088")?
.run()
.unwrap();
.await
}
// </minfo>

View File

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

View File

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

View File

@ -1,11 +1,12 @@
// <path>
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))
}
pub fn main() {
#[actix_rt::main]
async fn main() -> std::io::Result<()> {
use actix_web::{App, HttpServer};
HttpServer::new(|| {
@ -14,9 +15,8 @@ pub fn main() {
web::get().to(index),
)
})
.bind("127.0.0.1:8088")
.unwrap()
.bind("127.0.0.1:8088")?
.run()
.unwrap();
.await
}
// </path>

View File

@ -8,11 +8,12 @@ struct Info {
}
// 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))
}
pub fn main() {
#[actix_rt::main]
async fn main() -> std::io::Result<()> {
use actix_web::{App, HttpServer};
HttpServer::new(|| {
@ -21,9 +22,8 @@ pub fn main() {
web::get().to(index),
)
})
.bind("127.0.0.1:8088")
.unwrap()
.bind("127.0.0.1:8088")?
.run()
.unwrap();
.await
}
// </path>

View File

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

View File

@ -1,15 +1,16 @@
use actix_web::{web, App, HttpResponse, HttpServer};
// <scope>
fn show_users() -> HttpResponse {
async fn show_users() -> HttpResponse {
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))
}
pub fn main() {
#[actix_rt::main]
async fn main() -> std::io::Result<()> {
HttpServer::new(|| {
App::new().service(
web::scope("/users")
@ -17,9 +18,8 @@ pub fn main() {
.route("/show/{id}", web::get().to(user_detail)),
)
})
.bind("127.0.0.1:8088")
.unwrap()
.bind("127.0.0.1:8088")?
.run()
.unwrap();
.await
}
// </scope>

View File

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

View File

@ -1,7 +1,7 @@
// <url>
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
Ok(HttpResponse::Found()
@ -9,7 +9,8 @@ fn index(req: HttpRequest) -> Result<HttpResponse> {
.finish())
}
pub fn main() {
#[actix_rt::main]
async fn main() -> std::io::Result<()> {
use actix_web::{web, App, HttpServer};
HttpServer::new(|| {
@ -22,9 +23,8 @@ pub fn main() {
)
.route("/test/", web::get().to(index))
})
.bind("127.0.0.1:8088")
.unwrap()
.bind("127.0.0.1:8088")?
.run()
.unwrap();
.await
}
// </url>

View File

@ -4,6 +4,7 @@ version = "1.0.0"
edition = "2018"
[dependencies]
actix = "0.8"
actix-web = "1.0"
actix-web-actors = "1.0"
actix = "0.9"
actix-rt = "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
impl StreamHandler<ws::Message, ws::ProtocolError> for MyWs {
fn handle(&mut self, msg: ws::Message, ctx: &mut Self::Context) {
impl StreamHandler<Result<ws::Message, ws::ProtocolError>> for MyWs {
fn handle(
&mut self,
msg: Result<ws::Message, ws::ProtocolError>,
ctx: &mut Self::Context,
) {
match msg {
ws::Message::Ping(msg) => ctx.pong(&msg),
ws::Message::Text(text) => ctx.text(text),
ws::Message::Binary(bin) => ctx.binary(bin),
Ok(ws::Message::Ping(msg)) => ctx.pong(&msg),
Ok(ws::Message::Text(text)) => ctx.text(text),
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);
println!("{:?}", resp);
resp
}
fn main() {
#[actix_rt::main]
async fn main() -> std::io::Result<()> {
HttpServer::new(|| App::new().route("/ws/", web::get().to(index)))
.bind("127.0.0.1:8088")
.unwrap()
.bind("127.0.0.1:8088")?
.run()
.unwrap();
.await
}
// </websockets>