From 4a41b92cc7afe5ea843f2a849e3df239768bd2e6 Mon Sep 17 00:00:00 2001 From: Nikolay Kim Date: Sat, 21 Jul 2018 05:40:42 -0700 Subject: [PATCH] update user guide --- config.toml | 4 ++-- content/docs/autoreload.md | 2 +- content/docs/databases.md | 6 +++--- content/docs/errors.md | 10 ++++----- content/docs/extractors.md | 25 ++++++++++----------- content/docs/handlers.md | 42 +++++++++++++++--------------------- content/docs/middleware.md | 10 ++++----- content/docs/request.md | 14 ++++++------ content/docs/response.md | 4 ++-- content/docs/static-files.md | 2 +- content/docs/testing.md | 4 ++-- content/docs/url-dispatch.md | 4 ++-- content/docs/whatis.md | 2 +- layouts/index.html | 2 +- 14 files changed, 62 insertions(+), 69 deletions(-) diff --git a/config.toml b/config.toml index 47c2931..5f25122 100644 --- a/config.toml +++ b/config.toml @@ -15,5 +15,5 @@ baseURL = "https://actix.rs" weight = 1 [params] -actixVersion = "0.5" -actixWebVersion = "0.6" +actixVersion = "0.7" +actixWebVersion = "0.7" diff --git a/content/docs/autoreload.md b/content/docs/autoreload.md index eb7e0e9..8ee9db4 100644 --- a/content/docs/autoreload.md +++ b/content/docs/autoreload.md @@ -46,7 +46,7 @@ extern crate listenfd; use listenfd::ListenFd; use actix_web::{server, App, HttpRequest, Responder}; -fn index(_req: HttpRequest) -> impl Responder { +fn index(_req: &HttpRequest) -> impl Responder { "Hello World!" } diff --git a/content/docs/databases.md b/content/docs/databases.md index 6674f86..63218fe 100644 --- a/content/docs/databases.md +++ b/content/docs/databases.md @@ -79,7 +79,7 @@ can access it. ```rust /// This is state where we will store *DbExecutor* address. struct State { - db: Addr, + db: Addr, } fn main() { @@ -109,7 +109,7 @@ thus, we receive the message response asynchronously. ```rust /// Async handler -fn index(req: HttpRequest) -> Box> { +fn index(req: &HttpRequest) -> Box> { let name = &req.match_info()["name"]; // Send message to `DbExecutor` actor @@ -129,4 +129,4 @@ fn index(req: HttpRequest) -> Box> > [examples directory](https://github.com/actix/examples/tree/master/diesel/). > More information on sync actors can be found in the -> [actix documentation](https://docs.rs/actix/0.5.0/actix/sync/index.html). +> [actix documentation](https://docs.rs/actix/0.7.0/actix/sync/index.html). diff --git a/content/docs/errors.md b/content/docs/errors.md index 4cb1404..70deb6b 100644 --- a/content/docs/errors.md +++ b/content/docs/errors.md @@ -40,7 +40,7 @@ converted into an `HttpInternalServerError`: ```rust use std::io; -fn index(req: HttpRequest) -> io::Result { +fn index(req: &HttpRequest) -> io::Result { Ok(fs::NamedFile::open("static/index.html")?) } ``` @@ -64,7 +64,7 @@ struct MyError { // Use default implementation for `error_response()` method impl error::ResponseError for MyError {} -fn index(req: HttpRequest) -> Result<&'static str, MyError> { +fn index(req: &HttpRequest) -> Result<&'static str, MyError> { Err(MyError{name: "test"}) } ``` @@ -102,7 +102,7 @@ impl error::ResponseError for MyError { } } -fn index(req: HttpRequest) -> Result<&'static str, MyError> { +fn index(req: &HttpRequest) -> Result<&'static str, MyError> { Err(MyError::BadClientData) } ``` @@ -123,7 +123,7 @@ struct MyError { name: &'static str } -fn index(req: HttpRequest) -> Result<&'static str> { +fn index(req: &HttpRequest) -> Result<&'static str> { let result: Result<&'static str, MyError> = Err(MyError{name: "test"}); Ok(result.map_err(|e| error::ErrorBadRequest(e.name))?) @@ -220,7 +220,7 @@ impl error::ResponseError for UserError { } } -fn index(_req: HttpRequest) -> Result<&'static str, UserError> { +fn index(_: &HttpRequest) -> Result<&'static str, UserError> { fs::NamedFile::open("static/index.html").map_err(|_e| UserError::InternalError)?; Ok("success!") } diff --git a/content/docs/extractors.md b/content/docs/extractors.md index e9c4394..684d84d 100644 --- a/content/docs/extractors.md +++ b/content/docs/extractors.md @@ -31,9 +31,9 @@ fn index((params, info): (Path<(String, String,)>, Json)) -> HttpRespons use actix_web::FromRequest; -fn index(req: HttpRequest) -> HttpResponse { - let params = Path::<(String, String)>::extract(&req); - let info = Json::::extract(&req); +fn index(req: &HttpRequest) -> HttpResponse { + let params = Path::<(String, String)>::extract(req); + let info = Json::::extract(req); ... } @@ -55,9 +55,9 @@ impl Handler for MyHandler { type Result = HttpResponse; /// Handle request - fn handle(&mut self, req: HttpRequest) -> Self::Result { - let params = Path::<(String, String)>::extract(&req); - let info = Json::::extract(&req); + fn handle(&self, req: &HttpRequest) -> Self::Result { + let params = Path::<(String, String)>::extract(req); + let info = Json::::extract(req); ... @@ -204,12 +204,13 @@ fn main() { let app = App::new().resource( "/index.html", |r| { r.method(http::Method::POST) - .with(index) - .limit(4096) // <- change json extractor configuration - .error_handler(|err, req| { // <- create custom error response - error::InternalError::from_response( - err, HttpResponse::Conflict().finish()).into() - }); + .with_config(index, |cfg| { + cfg.limit(4096) // <- change json extractor configuration + cfg.error_handler(|err, req| { // <- create custom error response + error::InternalError::from_response( + err, HttpResponse::Conflict().finish()).into() + }) + }); }); } ``` diff --git a/content/docs/handlers.md b/content/docs/handlers.md index 9b7148a..386f8c1 100644 --- a/content/docs/handlers.md +++ b/content/docs/handlers.md @@ -23,13 +23,13 @@ such as `&'static str`, `String`, etc. Examples of valid handlers: ```rust -fn index(req: HttpRequest) -> &'static str { +fn index(req: &HttpRequest) -> &'static str { "Hello world!" } ``` ```rust -fn index(req: HttpRequest) -> String { +fn index(req: &HttpRequest) -> String { "Hello world!".to_owned() } ``` @@ -38,13 +38,13 @@ You can also change the signature to return `impl Responder` which works well if complex types are involved. ```rust -fn index(req: HttpRequest) -> impl Responder { +fn index(req: &HttpRequest) -> impl Responder { Bytes::from_static("Hello world!") } ``` ```rust,ignore -fn index(req: HttpRequest) -> Box> { +fn index(req: &HttpRequest) -> Box> { ... } ``` @@ -54,8 +54,8 @@ Application state is accessible from the handler with the `HttpRequest::state()` however, state is accessible as a read-only reference. If you need mutable access to state, it must be implemented. -> **Note**: Alternatively, the handler can mutably access its own state because the `handle` method takes -> mutable reference to *self*. **Beware**, actix creates multiple copies +> **Note**: Alternatively, the handler can use interior mutably to access its own +> state. **Beware**, actix creates multiple copies > of the application state and the handlers, unique for each thread. If you run your > application in several threads, actix will create the same amount as number of threads > of application state objects and handler objects. @@ -65,14 +65,15 @@ Here is an example of a handler that stores the number of processed requests: ```rust use actix_web::{App, HttpRequest, HttpResponse, dev::Handler}; -struct MyHandler(usize); +struct MyHandler(Cell); impl Handler for MyHandler { type Result = HttpResponse; /// Handle request - fn handle(&mut self, req: HttpRequest) -> Self::Result { - self.0 += 1; + fn handle(&self, req: &HttpRequest) -> Self::Result { + let i = self.0.get(); + self.0.set(i + 1); HttpResponse::Ok().into() } } @@ -92,7 +93,7 @@ impl Handler for MyHandler { type Result = HttpResponse; /// Handle request - fn handle(&mut self, req: HttpRequest) -> Self::Result { + fn handle(&self, req: &HttpRequest) -> Self::Result { self.0.fetch_add(1, Ordering::Relaxed); HttpResponse::Ok().into() } @@ -156,7 +157,7 @@ impl Responder for MyObj { } } -fn index(req: HttpRequest) -> impl Responder { +fn index(req: &HttpRequest) -> impl Responder { MyObj { name: "user" } } @@ -187,7 +188,7 @@ use bytes::Bytes; use futures::stream::once; use futures::future::{Future, result}; -fn index(req: HttpRequest) -> Box> { +fn index(req: &HttpRequest) -> Box> { result(Ok(HttpResponse::Ok() .content_type("text/html") @@ -195,7 +196,7 @@ fn index(req: HttpRequest) -> Box> { .responder() } -fn index2(req: HttpRequest) -> Box> { +fn index2(req: &HttpRequest) -> Box> { result(Ok("Welcome!")) .responder() } @@ -216,7 +217,7 @@ use actix_web::*; use bytes::Bytes; use futures::stream::once; -fn index(req: HttpRequest) -> HttpResponse { +fn index(req: &HttpRequest) -> HttpResponse { let body = once(Ok(Bytes::from_static(b"test"))); HttpResponse::Ok() @@ -243,7 +244,7 @@ use bytes::Bytes; use futures::stream::once; use futures::future::{Future, result}; -fn index(req: HttpRequest) -> Result>, Error> { +fn index(req: &HttpRequest) -> Result>, Error> { if is_error() { Err(error::ErrorBadRequest("bad request")) } else { @@ -269,7 +270,7 @@ use actix_web::{Either, Error, HttpResponse}; type RegisterResult = Either>>; -fn index(req: HttpRequest) -> impl Responder { +fn index(req: &HttpRequest) -> impl Responder { if is_a_variant() { // <- choose variant A Either::A( HttpResponse::BadRequest().body("Bad data")) @@ -281,12 +282,3 @@ fn index(req: HttpRequest) -> impl Responder { } } ``` - -## Tokio core handle - -Any `actix-web` handler runs within a properly configured -[actix system](https://actix.github.io/actix/actix/struct.System.html) -and [arbiter](https://actix.github.io/actix/actix/struct.Arbiter.html). -You can always get access to the tokio handle via the -[Arbiter::handle()](https://actix.github.io/actix/actix/struct.Arbiter.html#method.handle) -method. diff --git a/content/docs/middleware.md b/content/docs/middleware.md index e93a16a..c024289 100644 --- a/content/docs/middleware.md +++ b/content/docs/middleware.md @@ -40,15 +40,13 @@ impl Middleware for Headers { /// Method is called when request is ready. It may return /// future, which should resolve before next middleware get called. - fn start(&self, req: &mut HttpRequest) -> Result { - req.headers_mut().insert( - header::CONTENT_TYPE, header::HeaderValue::from_static("text/plain")); + fn start(&self, req: &HttpRequest) -> Result { Ok(Started::Done) } /// Method is called when handler returns response, /// but before sending http message to peer. - fn response(&self, req: &mut HttpRequest, mut resp: HttpResponse) + fn response(&self, req: &HttpRequest, mut resp: HttpResponse) -> Result { resp.headers_mut().insert( @@ -190,7 +188,7 @@ session data. use actix_web::{server, App, HttpRequest, Result}; use actix_web::middleware::session::{RequestSession, SessionStorage, CookieSessionBackend}; -fn index(mut req: HttpRequest) -> Result<&'static str> { +fn index(req: &HttpRequest) -> Result<&'static str> { // access session data if let Some(count) = req.session().get::("counter")? { println!("SESSION value: {}", count); @@ -230,7 +228,7 @@ use actix_web::{ App, HttpRequest, HttpResponse, Result, http, middleware::Response, middleware::ErrorHandlers}; -fn render_500(_: &mut HttpRequest, resp: HttpResponse) -> Result { +fn render_500(_: &HttpRequest, resp: HttpResponse) -> Result { let mut builder = resp.into_builder(); builder.header(http::header::CONTENT_TYPE, "application/json"); Ok(Response::Done(builder.into())) diff --git a/content/docs/request.md b/content/docs/request.md index ba7b29c..1f2e9f8 100644 --- a/content/docs/request.md +++ b/content/docs/request.md @@ -58,7 +58,7 @@ struct MyObj { number: i32, } -fn index(mut req: HttpRequest) -> Box> { +fn index(req: &HttpRequest) -> Box> { req.json().from_err() .and_then(|val: MyObj| { println!("model: {:?}", val); @@ -80,7 +80,7 @@ use futures::{Future, Stream}; #[derive(Serialize, Deserialize)] struct MyObj {name: String, number: i32} -fn index(req: HttpRequest) -> Box> { +fn index(req: &HttpRequest) -> Box> { // `concat2` will asynchronously read each chunk of the request body and // return a single, concatenated, chunk req.concat2() @@ -120,7 +120,7 @@ The following demonstrates multipart stream handling for a simple form: ```rust use actix_web::*; -fn index(req: HttpRequest) -> Box> { +fn index(req: &HttpRequest) -> Box> { // get multipart and iterate over multipart items req.multipart() .and_then(|item| { @@ -171,7 +171,7 @@ struct FormData { username: String, } -fn index(mut req: HttpRequest) -> Box> { +fn index(req: &HttpRequest) -> Box> { req.urlencoded::() // <- get UrlEncoded future .from_err() .and_then(|data| { // <- deserialized instance @@ -195,8 +195,10 @@ use actix_web::*; use futures::{Future, Stream}; -fn index(mut req: HttpRequest) -> Box> { - req.from_err() +fn index(req: &HttpRequest) -> Box> { + req + .payload() + .from_err() .fold((), |_, chunk| { println!("Chunk: {:?}", chunk); result::<_, error::PayloadError>(Ok(())) diff --git a/content/docs/response.md b/content/docs/response.md index 6bceded..1d2a33f 100644 --- a/content/docs/response.md +++ b/content/docs/response.md @@ -20,7 +20,7 @@ builder instance multiple times, the builder will panic. ```rust use actix_web::{HttpRequest, HttpResponse, http::ContentEncoding}; -fn index(req: HttpRequest) -> HttpResponse { +fn index(req: &HttpRequest) -> HttpResponse { HttpResponse::Ok() .content_encoding(ContentEncoding::Br) .content_type("plain/text") @@ -107,7 +107,7 @@ struct MyObj { name: String, } -fn index(req: HttpRequest) -> Result> { +fn index(req: &HttpRequest) -> Result> { Ok(Json(MyObj{name: req.match_info().query("name")?})) } diff --git a/content/docs/static-files.md b/content/docs/static-files.md index 2ccac19..1df8043 100644 --- a/content/docs/static-files.md +++ b/content/docs/static-files.md @@ -13,7 +13,7 @@ match a path tail, we can use a `[.*]` regex. use std::path::PathBuf; use actix_web::{App, HttpRequest, Result, http::Method, fs::NamedFile}; -fn index(req: HttpRequest) -> Result { +fn index(req: &HttpRequest) -> Result { let path: PathBuf = req.match_info().query("tail")?; Ok(NamedFile::open(path)?) } diff --git a/content/docs/testing.md b/content/docs/testing.md index 3fb0f83..46e5249 100644 --- a/content/docs/testing.md +++ b/content/docs/testing.md @@ -20,7 +20,7 @@ run your handler with `run()` or `run_async()`. ```rust use actix_web::{http, test, HttpRequest, HttpResponse, HttpMessage}; -fn index(req: HttpRequest) -> HttpResponse { +fn index(req: &HttpRequest) -> HttpResponse { if let Some(hdr) = req.headers().get(http::header::CONTENT_TYPE) { if let Ok(s) = hdr.to_str() { return HttpResponse::Ok().into() @@ -87,7 +87,7 @@ function the same way as you would for real http server configuration. ```rust use actix_web::{http, test, App, HttpRequest, HttpResponse}; -fn index(req: HttpRequest) -> HttpResponse { +fn index(req: &HttpRequest) -> HttpResponse { HttpResponse::Ok().into() } diff --git a/content/docs/url-dispatch.md b/content/docs/url-dispatch.md index b69a7a7..a24f376 100644 --- a/content/docs/url-dispatch.md +++ b/content/docs/url-dispatch.md @@ -82,7 +82,7 @@ builder-like pattern. Following configuration methods are available: Usually handler registration is the last config operation. Handler function can be a function or closure and has the type - `Fn(HttpRequest) -> R + 'static` + `Fn(&HttpRequest) -> R + 'static` * [*Route::h()*](../../actix-web/actix_web/dev/struct.Route.html#method.h) registers a handler object that implements the `Handler` trait. This is similar to `f()` method - only one handler can @@ -91,7 +91,7 @@ builder-like pattern. Following configuration methods are available: an async handler function for this route. Only one handler can be registered. Handler registration is the last config operation. Handler function can be a function or closure and has the type - `Fn(HttpRequest) -> Future + 'static` + `Fn(&HttpRequest) -> Future + 'static` # Route matching diff --git a/content/docs/whatis.md b/content/docs/whatis.md index d65e041..1eec567 100644 --- a/content/docs/whatis.md +++ b/content/docs/whatis.md @@ -23,5 +23,5 @@ server `actix-web` is powerful enough to provide HTTP 1 and HTTP 2 support as well as SSL/TLS. This makes it useful for building small services ready for distribution. -Most importantly: `actix-web` runs on Rust 1.24 or later and it works with +Most importantly: `actix-web` runs on Rust 1.26 or later and it works with stable releases. diff --git a/layouts/index.html b/layouts/index.html index 4a746c5..b9e9d9d 100644 --- a/layouts/index.html +++ b/layouts/index.html @@ -42,7 +42,7 @@ {{ highlight `extern crate actix_web; use actix_web::{server, App, HttpRequest, Responder}; -fn greet(req: HttpRequest) -> impl Responder { +fn greet(req: &HttpRequest) -> impl Responder { let to = req.match_info().get("name").unwrap_or("World"); format!("Hello {}!", to) }