1
0
mirror of https://github.com/actix/actix-website synced 2025-06-27 07:29:02 +02:00

migrate to docusaurus (v2) (#266)

Co-authored-by: ibraheemdev <ibrah1440@gmail.com>
This commit is contained in:
Santiago
2022-07-16 11:59:20 +02:00
committed by GitHub
parent a85b4ff5a3
commit 8393aea71a
85 changed files with 23020 additions and 4357 deletions

104
docs/application.md Normal file
View File

@ -0,0 +1,104 @@
---
title: Application
---
import CodeBlock from "@site/src/components/code_block.js";
# Writing an Application
`actix-web` provides various primitives to build web servers and applications with Rust. It provides routing, middleware, pre-processing of requests, post-processing of responses, etc.
All `actix-web` servers are built around the [`App`][app] instance. It is used for registering routes for resources and middleware. It also stores application state shared across all handlers within the same scope.
An application's [`scope`][scope] acts as a namespace for all routes, i.e. all routes for a specific application scope have the same url path prefix. The application prefix always contains a leading "/" slash. If a supplied prefix does not contain leading slash, it is automatically inserted. The prefix should consist of value path segments.
> For an application with scope `/app`, any request with the paths `/app`, `/app/`, or `/app/test` would match; however, the path `/application` would not match.
<CodeBlock example="application" file="app.rs" section="setup" />
In this example, an application with the `/app` prefix and an `index.html` resource is created. This resource is available through the `/app/index.html` url.
> For more information, check the [URL Dispatch][usingappprefix] section.
## State
Application state is shared with all routes and resources within the same scope. State can be accessed with the [`web::Data<T>`][data] extractor where `T` is the type of the state. State is also accessible for middleware.
Let's write a simple application and store the application name in the state:
<CodeBlock example="application" file="state.rs" section="setup" />
Next, pass in the state when initializing the App and start the application:
<CodeBlock example="application" file="state.rs" section="start_app" />
Any number of state types could be registered within the application.
## Shared Mutable State
`HttpServer` accepts an application factory rather than an application instance. An `HttpServer` constructs an application instance for each thread. Therefore, application data must be constructed multiple times. If you want to share data between different threads, a shareable object should be used, e.g. `Send` + `Sync`.
Internally, [`web::Data`][data] uses `Arc`. So in order to avoid creating two `Arc`s, we should create our Data before registering it using [`App::app_data()`][appdata].
In the following example, we will write an application with mutable, shared state. First, we define our state and create our handler:
<CodeBlock example="application" file="mutable_state.rs" section="setup_mutable" />
and register the data in an `App`:
<CodeBlock example="application" file="mutable_state.rs" section="make_app_mutable" />
Key takeaways:
- State initialized _inside_ the closure passed to `HttpServer::new` is local to the worker thread and may become de-synced if modified.
- To achieve _globally shared state_, it must be created **outside** of the closure passed to `HttpServer::new` and moved/cloned in.
## Using an Application Scope to Compose Applications
The [`web::scope()`][webscope] method allows setting a resource group prefix. This scope represents a resource prefix that will be prepended to all resource patterns added by the resource configuration. This can be used to help mount a set of routes at a different location than the original author intended while still maintaining the same resource names.
For example:
<CodeBlock example="application" file="scope.rs" section="scope" />
In the above example, the `show_users` route will have an effective route pattern of `/users/show` instead of `/show` because the application's scope argument will be prepended to the pattern. The route will then only match if the URL path is `/users/show`, and when the [`HttpRequest.url_for()`][urlfor] function is called with the route name `show_users`, it will generate a URL with that same path.
## Application guards and virtual hosting
You can think of a guard as a simple function that accepts a _request_ object reference and returns _true_ or _false_. Formally, a guard is any object that implements the [`Guard`][guardtrait] trait. Actix Web provides several guards. You can check the [functions section][guardfuncs] of the API docs.
One of the provided guards is [`Header`][guardheader]. It can be used as a filter based on request header information.
<CodeBlock example="application" file="vh.rs" section="vh" />
## Configure
For simplicity and reusability both [`App`][appconfig] and [`web::Scope`][webscopeconfig] provide the `configure` method. This function is useful for moving parts of the configuration to a different module or even library. For example, some of the resource's configuration could be moved to a different module.
<CodeBlock example="application" file="config.rs" section="config" />
The result of the above example would be:
```
/ -> "/"
/app -> "app"
/api/test -> "test"
```
Each [`ServiceConfig`][serviceconfig] can have its own `data`, `routes`, and `services`.
<!-- LINKS -->
[usingappprefix]: /docs/url-dispatch/index.html#using-an-application-prefix-to-compose-applications
[stateexample]: https://github.com/actix/examples/blob/master/basics/state/src/main.rs
[guardtrait]: https://docs.rs/actix-web/4/actix_web/guard/trait.Guard.html
[guardfuncs]: https://docs.rs/actix-web/4/actix_web/guard/index.html#functions
[guardheader]: https://docs.rs/actix-web/4/actix_web/guard/fn.Header.html
[data]: https://docs.rs/actix-web/4/actix_web/web/struct.Data.html
[app]: https://docs.rs/actix-web/4/actix_web/struct.App.html
[appconfig]: https://docs.rs/actix-web/4/actix_web/struct.App.html#method.configure
[appdata]: https://docs.rs/actix-web/4/actix_web/struct.App.html#method.app_data
[scope]: https://docs.rs/actix-web/4/actix_web/struct.Scope.html
[webscopeconfig]: https://docs.rs/actix-web/4/actix_web/struct.Scope.html#method.configure
[webscope]: https://docs.rs/actix-web/4/actix_web/web/fn.scope.html
[urlfor]: https://docs.rs/actix-web/4/actix_web/struct.HttpRequest.html#method.url_for
[serviceconfig]: https://docs.rs/actix-web/4/actix_web/web/struct.ServiceConfig.html

17
docs/autoreload.md Normal file
View File

@ -0,0 +1,17 @@
---
title: Auto-Reloading
---
# Auto-Reloading Development Server
During development it can be very handy to have cargo automatically recompile the code on changes. This can be accomplished very easily by using [`cargo-watch`].
```sh
cargo watch -x 'run --bin app'
```
## Historical Note
An old version of this page recommended using a combination of systemfd and listenfd, but this has many gotchas and was difficult to integrate properly, especially when part of a broader development workflow. We consider [`cargo-watch`] to be sufficient for auto-reloading purposes.
[`cargo-watch`]: https://github.com/passcod/cargo-watch

38
docs/conn_lifecycle.md Normal file
View File

@ -0,0 +1,38 @@
---
title: Connection Lifecycle
---
# Architecture overview
After Server has started listening to all sockets, [`Accept`][accept] and [`Worker`][worker] are two main loops responsible for processing incoming client connections.
Once connection accepted Application level protocol processing happens in a protocol specific [`Dispatcher`][dispatcher] loop spawned from [`Worker`][worker].
Please note, below diagrams are outlining happy-path scenarios only.
![](/img/diagrams/connection_overview.svg)
## Accept loop in more detail
![](/img/diagrams/connection_accept.svg)
Most of code implementation resides in [`actix-server`][server] crate for struct [`Accept`][accept].
## Worker loop in more detail
![](/img/diagrams/connection_worker.svg)
Most of code implementation resides in [`actix-server`][server] crate for struct [`Worker`][worker].
## Request loop roughly
![](/img/diagrams/connection_request.svg)
Most of code implementation for request loop resides in [`actix-web`][web] and [`actix-http`][http] crates.
[server]: https://crates.io/crates/actix-server
[web]: https://crates.io/crates/actix-web
[http]: https://crates.io/crates/actix-http
[accept]: https://github.com/actix/actix-net/blob/master/actix-server/src/accept.rs
[worker]: https://github.com/actix/actix-net/blob/master/actix-server/src/worker.rs
[dispatcher]: https://github.com/actix/actix-web/blob/master/actix-http/src/h1/dispatcher.rs

36
docs/databases.md Normal file
View File

@ -0,0 +1,36 @@
---
title: Databases
---
import CodeBlock from "@site/src/components/code_block.js";
# Async Options
We have several example projects showing use of async database adapters:
- Postgres: https://github.com/actix/examples/tree/master/databases/postgres
- SQLite: https://github.com/actix/examples/tree/master/databases/sqlite
- MongoDB: https://github.com/actix/examples/tree/master/databases/mongodb
# Diesel
The current version of Diesel (v1) does not support asynchronous operations, so it is important to use the [`web::block`][web-block] function to offload your database operations to the Actix runtime thread-pool.
You can create action functions that correspond to all the operations your app will perform on the database.
<CodeBlock example="databases" file="main.rs" section="handler" />
Now you should set up the database pool using a crate such as `r2d2`, which makes many DB connections available to your app. This means that multiple handlers can manipulate the DB at the same time, and still accept new connections. Simply, the pool in your app state. (In this case, it's beneficial not to use a state wrapper struct because the pool handles shared access for you.)
<CodeBlock example="databases" file="main.rs" section="main" />
Now, in a request handler, use the `Data<T>` extractor to get the pool from app state and get a connection from it. This provides an owned database connection that can be passed into a [`web::block`][web-block] closure. Then just call the action function with the necessary arguments and `.await` the result.
This example also maps the error to an `HttpResponse` before using the `?` operator but this is not necessary if your return error type implements [`ResponseError`][response-error].
<CodeBlock example="databases" file="main.rs" section="index" />
That's it! See the full example here: https://github.com/actix/examples/tree/master/databases/diesel
[web-block]: https://docs.rs/actix-web/4/actix_web/web/fn.block.html
[response-error]: https://docs.rs/actix-web/4/actix_web/trait.ResponseError.html

107
docs/errors.md Normal file
View File

@ -0,0 +1,107 @@
---
title: Errors
---
import CodeBlock from "@site/src/components/code_block.js";
# Errors
Actix Web uses its own [`actix_web::error::Error`][actixerror] type and [`actix_web::error::ResponseError`][responseerror] trait for error handling from web handlers.
If a handler returns an `Error` (referring to the [general Rust trait `std::error::Error`][stderror]) in a `Result` that also implements the `ResponseError` trait, actix-web will render that error as an HTTP response with its corresponding [`actix_web::http::StatusCode`][status_code]. An internal server error is generated by default:
```rust
pub trait ResponseError {
fn error_response(&self) -> Response<Body>;
fn status_code(&self) -> StatusCode;
}
```
A `Responder` coerces compatible `Result`s into HTTP responses:
```rust
impl<T: Responder, E: Into<Error>> Responder for Result<T, E>
```
`Error` in the code above is actix-web's error definition, and any errors that implement `ResponseError` can be converted to one automatically.
Actix Web provides `ResponseError` implementations for some common non-actix errors. For example, if a handler responds with an `io::Error`, that error is converted into an `HttpInternalServerError`:
```rust
use std::io;
use actix_files::NamedFile;
fn index(_req: HttpRequest) -> io::Result<NamedFile> {
Ok(NamedFile::open("static/index.html")?)
}
```
See [the actix-web API documentation][responseerrorimpls] for a full list of foreign implementations for `ResponseError`.
## An example of a custom error response
Here's an example implementation for `ResponseError`, using the [derive_more] crate for declarative error enums.
<CodeBlock example="errors" file="main.rs" section="response-error" />
`ResponseError` has a default implementation for `error_response()` that will render a _500_ (internal server error), and that's what will happen when the `index` handler executes above.
Override `error_response()` to produce more useful results:
<CodeBlock example="errors" file="override_error.rs" section="override" />
## Error helpers
Actix Web provides a set of error helper functions that are useful for generating specific HTTP error codes from other errors. Here we convert `MyError`, which doesn't implement the `ResponseError` trait, to a _400_ (bad request) using `map_err`:
<CodeBlock example="errors" file="helpers.rs" section="helpers" />
See the [API documentation for actix-web's `error` module][actixerror] for a full list of available error helpers.
## Error logging
Actix logs all errors at the `WARN` log level. If an application's log level is set to `DEBUG` and `RUST_BACKTRACE` is enabled, the backtrace is also logged. These are configurable with environmental variables:
```
>> RUST_BACKTRACE=1 RUST_LOG=actix_web=debug cargo run
```
The `Error` type uses the cause's error backtrace if available. If the underlying failure does not provide a backtrace, a new backtrace is constructed pointing to the point where the conversion occurred (rather than the origin of the error).
## Recommended practices in error handling
It might be useful to think about dividing the errors an application produces into two broad groups: those which are intended to be user-facing, and those which are not.
An example of the former is that I might use failure to specify a `UserError` enum which encapsulates a `ValidationError` to return whenever a user sends bad input:
<CodeBlock example="errors" file="recommend_one.rs" section="recommend-one" />
This will behave exactly as intended because the error message defined with `display` is written with the explicit intent to be read by a user.
However, sending back an error's message isn't desirable for all errors -- there are many failures that occur in a server environment where we'd probably want the specifics to be hidden from the user. For example, if a database goes down and client libraries start producing connect timeout errors, or if an HTML template was improperly formatted and errors when rendered. In these cases, it might be preferable to map the errors to a generic error suitable for user consumption.
Here's an example that maps an internal error to a user-facing `InternalError` with a custom message:
<CodeBlock example="errors" file="recommend_two.rs" section="recommend-two" />
By dividing errors into those which are user facing and those which are not, we can ensure that we don't accidentally expose users to errors thrown by application internals which they weren't meant to see.
## Error Logging
This is a basic example using `middleware::Logger` which depends on `env_logger` and `log`:
```toml
[dependencies]
env_logger = "0.8"
log = "0.4"
```
<CodeBlock example="errors" file="logging.rs" section="logging" />
[actixerror]: https://docs.rs/actix-web/4/actix_web/error/struct.Error.html
[errorhelpers]: https://docs.rs/actix-web/4/actix_web/trait.ResponseError.html
[derive_more]: https://crates.io/crates/derive_more
[responseerror]: https://docs.rs/actix-web/4/actix_web/error/trait.ResponseError.html
[responseerrorimpls]: https://docs.rs/actix-web/4/actix_web/error/trait.ResponseError.html#foreign-impls
[stderror]: https://doc.rust-lang.org/std/error/trait.Error.html
[status_code]: https://docs.rs/actix-web/4/actix_web/http/struct.StatusCode.html

97
docs/extractors.md Normal file
View File

@ -0,0 +1,97 @@
---
title: Extractors
---
import CodeBlock from "@site/src/components/code_block.js";
# Type-safe information extraction
Actix Web provides a facility for type-safe request information access called _extractors_ (i.e., `impl FromRequest`). There are lots of built-in extractor implementations (see [implementors](https://actix.rs/actix-web/actix_web/trait.FromRequest.html#implementors)).
An extractor can be accessed as an argument to a handler function. Actix Web supports up to 12 extractors per handler function. Argument position does not matter.
<CodeBlock example="extractors" file="main.rs" section="option-one" />
## Path
[_Path_][pathstruct] provides information that is extracted from the request's path. Parts of the path that are extractable are called "dynamic segments" and are marked with curly braces. You can deserialize any variable segment from the path.
For instance, for resource that registered for the `/users/{user_id}/{friend}` path, two segments could be deserialized, `user_id` and `friend`. These segments could be extracted as a tuple in the order they are declared (e.g., `Path<(u32, String)>`).
<CodeBlock example="extractors" file="path_one.rs" section="path-one" />
It is also possible to extract path information to a type that implements the `Deserialize` trait from `serde` by matching dynamic segment names with field names. Here is an equivalent example that uses `serde` instead of a tuple type.
<CodeBlock example="extractors" file="path_two.rs" section="path-two" />
As a non-type-safe alternative, it's also possible to query (see [`match_info` docs][docsrs_match_info]) the request for path parameters by name within a handler:
<CodeBlock example="extractors" file="path_three.rs" section="path-three" />
## Query
The [`Query<T>`][querystruct] type provides extraction functionality for the request's query parameters. Underneath it uses `serde_urlencoded` crate.
<CodeBlock example="extractors" file="query.rs" section="query" />
## Json
[`Json<T>`][jsonstruct] allows deserialization of a request body into a struct. To extract typed information from a request's body, the type `T` must implement `serde::Deserialize`.
<CodeBlock example="extractors" file="json_one.rs" section="json-one" />
Some extractors provide a way to configure the extraction process. To configure an extractor, pass its configuration object to the resource's `.app_data()` method. In the case of _Json_ extractor it returns a [_JsonConfig_][jsonconfig]. You can configure the maximum size of the JSON payload as well as a custom error handler function.
The following example limits the size of the payload to 4kb and uses a custom error handler.
<CodeBlock example="extractors" file="json_two.rs" section="json-two" />
# URL-Encoded Forms
A URL-encoded form body can be extracted to a struct, much like `Json<T>`. This type must implement `serde::Deserialize`.
[_FormConfig_][formconfig] allows configuring the extraction process.
<CodeBlock example="extractors" file="form.rs" section="form" />
## Other
Actix Web also provides several other extractors:
- [_Data_][datastruct] - If you need access to an application state.
- _HttpRequest_ - _HttpRequest_ itself is an extractor which returns self, in case you need access to the request.
- _String_ - You can convert a request's payload to a _String_. [_Example_][stringexample] is available in doc strings.
- _actix_web::web::Bytes_ - You can convert a request's payload into _Bytes_. [_Example_][bytesexample] is available in doc strings.
- _Payload_ - Low-level payload extractor primarily for building other extractors. [_Example_][payloadexample]
# Application State Extractor
Application state is accessible from the handler with the `web::Data` extractor; however, state is accessible as a read-only reference. If you need mutable access to state, it must be implemented.
Here is an example of a handler that stores the number of processed requests:
<CodeBlock example="request-handlers" file="main.rs" section="data" />
Although this handler will work, `data.count` will only count the number of requests handled _by each worker thread_. To count the number of total requests across all threads, one should use shared `Arc` and [atomics][atomics].
<CodeBlock example="request-handlers" file="handlers_arc.rs" section="arc" />
**Note**: If you want the _entire_ state to be shared across all threads, use `web::Data` and `app_data` as described in [Shared Mutable State][shared_mutable_state].
Be careful when using blocking synchronization primitives like `Mutex` or `RwLock` within your app state. Actix Web handles requests asynchronously. It is a problem if the [_critical section_][critical_section] in your handler is too big or contains an `.await` point. If this is a concern, we would advise you to also read [Tokio's advice on using blocking `Mutex` in async code][tokio_std_mutex].
[pathstruct]: https://docs.rs/actix-web/4/actix_web/dev/struct.Path.html
[querystruct]: https://docs.rs/actix-web/4/actix_web/web/struct.Query.html
[jsonstruct]: https://docs.rs/actix-web/4/actix_web/web/struct.Json.html
[jsonconfig]: https://docs.rs/actix-web/4/actix_web/web/struct.JsonConfig.html
[formconfig]: https://docs.rs/actix-web/4/actix_web/web/struct.FormConfig.html
[datastruct]: https://docs.rs/actix-web/4/actix_web/web/struct.Data.html
[stringexample]: https://docs.rs/actix-web/4/actix_web/trait.FromRequest.html#impl-FromRequest-for-String
[bytesexample]: https://docs.rs/actix-web/4/actix_web/trait.FromRequest.html#impl-FromRequest-5
[payloadexample]: https://docs.rs/actix-web/4/actix_web/web/struct.Payload.html
[docsrs_match_info]: https://docs.rs/actix-web/latest/actix_web/struct.HttpRequest.html#method.match_info
[actix]: https://actix.github.io/actix/actix/
[atomics]: https://doc.rust-lang.org/std/sync/atomic/
[shared_mutable_state]: /docs/application#shared-mutable-state
[critical_section]: https://en.wikipedia.org/wiki/Critical_section
[tokio_std_mutex]: https://tokio.rs/tokio/tutorial/shared-state#on-using-stdsyncmutex

51
docs/getting-started.md Normal file
View File

@ -0,0 +1,51 @@
---
title: Getting Started
---
import RenderCodeBlock from '@theme/CodeBlock';
import CodeBlock from "@site/src/components/code_block.js";
import { rustVersion, actixWebMajorVersion } from "@site/vars";
## Installing Rust
If you don't have Rust yet, we recommend you use `rustup` to manage your Rust installation. The [official rust guide][rustguide] has a wonderful section on getting started.
<p>
Actix Web currently has a minimum supported Rust version (MSRV) of { rustVersion }. Running <code>rustup update</code> will ensure you have the latest and greatest Rust version available. As such, this guide assumes you are running Rust { rustVersion } or later.
</p>
## Hello, world!
Start by creating a new binary-based Cargo project and changing into the new directory:
```bash
cargo new hello-world
cd hello-world
```
Add `actix-web` as a dependency of your project by adding the following to your `Cargo.toml` file.
<!-- DEPENDENCY -->
<RenderCodeBlock className="language-toml">
{`[dependencies]
actix-web = "${actixWebMajorVersion}"`}
</RenderCodeBlock>
Request handlers use async functions that accept zero or more parameters. These parameters can be extracted from a request (see `FromRequest` trait) and returns a type that can be converted into an `HttpResponse` (see `Responder` trait):
<CodeBlock example="getting-started" section="handlers" />
Notice that some of these handlers have routing information attached directly using the built-in macros. These allow you to specify the method and path that the handler should respond to. You will see below how to register `manual_hello` (i.e. routes that do not use a routing macro).
Next, create an `App` instance and register the request handlers. Use `App::service` for the handlers using routing macros and `App::route` for manually routed handlers, declaring the path and method. Finally, the app is started inside an `HttpServer` which will serve incoming requests using your `App` as an "application factory".
<CodeBlock example="getting-started" section="main" />
That's it! Compile and run the program with `cargo run`. The `#[actix_web::main]` macro executes the async main function within the actix runtime. Now you can go to `http://127.0.0.1:8080/` or any of the other routes you defined to see the results.
<!-- LINKS -->
[rustguide]: https://doc.rust-lang.org/book/ch01-01-installation.html
[actix-web-codegen]: https://docs.rs/actix-web-codegen/

70
docs/handlers.md Normal file
View File

@ -0,0 +1,70 @@
---
title: Handlers
---
import CodeBlock from "@site/src/components/code_block.js";
# Request Handlers
A request handler is an async function that accepts zero or more parameters that can be extracted from a request (i.e., [_impl FromRequest_][implfromrequest]) and returns a type that can be converted into an HttpResponse (i.e., [_impl Responder_][respondertrait]).
Request handling happens in two stages. First the handler object is called, returning any object that implements the [_Responder_][respondertrait] trait. Then, `respond_to()` is called on the returned object, converting itself to a `HttpResponse` or `Error`.
By default actix-web provides `Responder` implementations for some standard types, such as `&'static str`, `String`, etc.
> For a complete list of implementations, check the [_Responder documentation_][responderimpls].
Examples of valid handlers:
```rust
async fn index(_req: HttpRequest) -> &'static str {
"Hello world!"
}
```
```rust
async fn index(_req: HttpRequest) -> String {
"Hello world!".to_owned()
}
```
You can also change the signature to return `impl Responder` which works well if more complex types are involved.
```rust
async fn index(_req: HttpRequest) -> impl Responder {
web::Bytes::from_static(b"Hello world!")
}
```
```rust
async fn index(req: HttpRequest) -> Box<Future<Item=HttpResponse, Error=Error>> {
...
}
```
## Response with custom type
To return a custom type directly from a handler function, the type needs to implement the `Responder` trait.
Let's create a response for a custom type that serializes to an `application/json` response:
<CodeBlock example="responder-trait" file="main.rs" section="responder-trait" />
## Streaming response body
Response body can be generated asynchronously. In this case, body must implement the stream trait `Stream<Item=Bytes, Error=Error>`, i.e.:
<CodeBlock example="async-handlers" file="stream.rs" section="stream" />
## Different return types (Either)
Sometimes, you need to return different types of responses. For example, you can error check and return errors, return async responses, or any result that requires two different types.
For this case, the [Either][either] type can be used. `Either` allows combining two different responder types into a single type.
<CodeBlock example="either" file="main.rs" section="either" />
[implfromrequest]: https://docs.rs/actix-web/4/actix_web/trait.FromRequest.html
[respondertrait]: https://docs.rs/actix-web/4/actix_web/trait.Responder.html
[responderimpls]: https://docs.rs/actix-web/4/actix_web/trait.Responder.html#foreign-impls
[either]: https://docs.rs/actix-web/4/actix_web/enum.Either.html

38
docs/http2.md Normal file
View File

@ -0,0 +1,38 @@
---
title: HTTP/2
---
import RenderCodeBlock from '@theme/CodeBlock';
import CodeBlock from '@site/src/components/code_block.js';
import { actixWebMajorVersion } from "@site/vars";
`actix-web` automatically upgrades connections to *HTTP/2* if possible.
# Negotiation
<!-- TODO: use rustls example -->
When either of the `rustls` or `openssl` features are enabled, `HttpServer` provides the [bind_rustls][bindrustls] method and [bind_openssl][bindopenssl] methods, respectively.
<!-- DEPENDENCY -->
<RenderCodeBlock className="language-toml">
{`[dependencies]
actix-web = { version = "${actixWebMajorVersion}", features = ["openssl"] }
openssl = { version = "0.10", features = ["v110"] }
`}
</RenderCodeBlock>
<CodeBlock example="http2" file="main.rs" section="main" />
Upgrades to HTTP/2 described in [RFC 7540 §3.2][rfcsection32] are not supported. Starting HTTP/2 with prior knowledge is supported for both cleartext and TLS connections ([RFC 7540 §3.4][rfcsection34]) (when using the lower level `actix-http` service builders).
> Check out [the TLS examples][examples] for concrete example.
[rfcsection32]: https://httpwg.org/specs/rfc7540.html#rfc.section.3.2
[rfcsection34]: https://httpwg.org/specs/rfc7540.html#rfc.section.3.4
[bindrustls]: https://docs.rs/actix-web/4/actix_web/struct.HttpServer.html#method.bind_rustls
[bindopenssl]: https://docs.rs/actix-web/4/actix_web/struct.HttpServer.html#method.bind_openssl
[tlsalpn]: https://tools.ietf.org/html/rfc7301
[examples]: https://github.com/actix/examples/tree/master/https-tls

22
docs/http_server_init.md Normal file
View File

@ -0,0 +1,22 @@
---
title: HTTP Server Initialization
---
# Architecture overview
Below is a diagram of HttpServer initialization, which happens on the following code
```rust
#[actix_web::main]
async fn main() -> std::io::Result<()> {
HttpServer::new(|| {
App::new()
.route("/", web::to(|| HttpResponse::Ok()))
})
.bind(("127.0.0.1", 8080))?
.run()
.await
}
```
![](/img/diagrams/http_server.svg)

111
docs/middleware.md Normal file
View File

@ -0,0 +1,111 @@
---
title: Middleware
---
import CodeBlock from "@site/src/components/code_block.js";
# Middleware
Actix Web's middleware system allows us to add additional behavior to request/response processing. Middleware can hook into an incoming request process, enabling us to modify requests as well as halt request processing to return a response early.
Middleware can also hook into response processing.
Typically, middleware is involved in the following actions:
- Pre-process the Request
- Post-process a Response
- Modify application state
- Access external services (redis, logging, sessions)
Middleware is registered for each `App`, `scope`, or `Resource` and executed in opposite order as registration. In general, a _middleware_ is a type that implements the [_Service trait_][servicetrait] and [_Transform trait_][transformtrait]. Each method in the traits has a default implementation. Each method can return a result immediately or a _future_ object.
The following demonstrates creating a simple middleware:
<CodeBlock example="middleware" file="main.rs" section="simple" />
Alternatively, for simple use cases, you can use [_wrap_fn_][wrap_fn] to create small, ad-hoc middleware:
<CodeBlock example="middleware" file="wrap_fn.rs" section="wrap-fn" />
> Actix Web provides several useful middleware, such as _logging_, _user sessions_, _compress_, etc.
**Warning: if you use `wrap()` or `wrap_fn()` multiple times, the last occurrence will be executed first.**
## Logging
Logging is implemented as a middleware. It is common to register a logging middleware as the first middleware for the application. Logging middleware must be registered for each application.
The `Logger` middleware uses the standard log crate to log information. You should enable logger for _actix_web_ package to see access log ([env_logger][envlogger] or similar).
### Usage
Create `Logger` middleware with the specified `format`. Default `Logger` can be created with `default` method, it uses the default format:
```ignore
%a %t "%r" %s %b "%{Referer}i" "%{User-Agent}i" %T
```
<CodeBlock example="middleware" file="logger.rs" section="logger" />
The following is an example of the default logging format:
```
INFO:actix_web::middleware::logger: 127.0.0.1:59934 [02/Dec/2017:00:21:43 -0800] "GET / HTTP/1.1" 302 0 "-" "curl/7.54.0" 0.000397
INFO:actix_web::middleware::logger: 127.0.0.1:59947 [02/Dec/2017:00:22:40 -0800] "GET /index.html HTTP/1.1" 200 0 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.13; rv:57.0) Gecko/20100101 Firefox/57.0" 0.000646
```
### Format
- `%%` The percent sign
- `%a` Remote IP-address (IP-address of proxy if using reverse proxy)
- `%t` Time when the request was started to process
- `%P` The process ID of the child that serviced the request
- `%r` First line of request
- `%s` Response status code
- `%b` Size of response in bytes, including HTTP headers
- `%T` Time taken to serve the request, in seconds with floating fraction in .06f format
- `%D` Time taken to serve the request, in milliseconds
- `%{FOO}i` request.headers['FOO']
- `%{FOO}o` response.headers['FOO']
- `%{FOO}e` os.environ['FOO']
### Default headers
To set default response headers, the `DefaultHeaders` middleware can be used. The _DefaultHeaders_ middleware does not set the header if response headers already contain a specified header.
<CodeBlock example="middleware" file="default_headers.rs" section="default-headers" />
## User sessions
Actix Web provides a general solution for session management. The [**actix-session**][actixsession] middleware can use multiple backend types to store session data.
> By default, only cookie session backend is implemented. Other backend implementations can be added.
[**CookieSession**][cookiesession] uses cookies as session storage. `CookieSessionBackend` creates sessions which are limited to storing fewer than 4000 bytes of data, as the payload must fit into a single cookie. An internal server error is generated if a session contains more than 4000 bytes.
A cookie may have a security policy of _signed_ or _private_. Each has a respective `CookieSession` constructor.
A _signed_ cookie may be viewed but not modified by the client. A _private_ cookie may neither be viewed nor modified by the client.
The constructors take a key as an argument. This is the private key for cookie session - when this value is changed, all session data is lost.
In general, you create a `SessionStorage` middleware and initialize it with specific backend implementation, such as a `CookieSession`. To access session data the [`Session`][requestsession] extractor must be used. This method returns a [_Session_][sessionobj] object, which allows us to get or set session data.
<CodeBlock example="middleware" file="user_sessions.rs" section="user-session" />
## Error handlers
`ErrorHandlers` middleware allows us to provide custom handlers for responses.
You can use the `ErrorHandlers::handler()` method to register a custom error handler for a specific status code. You can modify an existing response or create a completly new one. The error handler can return a response immediately or return a future that resolves into a response.
<CodeBlock example="middleware" file="errorhandler.rs" section="error-handler" />
[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/4/actix_web/dev/trait.Service.html
[transformtrait]: https://docs.rs/actix-web/4/actix_web/dev/trait.Transform.html
[wrap_fn]: https://docs.rs/actix-web/4/actix_web/struct.App.html#method.wrap_fn

88
docs/request.md Normal file
View File

@ -0,0 +1,88 @@
---
title: Requests
---
# JSON Request
There are several options for json body deserialization.
The first option is to use _Json_ extractor. First, you define a handler function that accepts `Json<T>` as a parameter, then, you use the `.to()` method for registering this handler. It is also possible to accept arbitrary valid json object by using `serde_json::Value` as a type `T`.
First example of json of `JSON Request` depends on `serde`:
```toml
[dependencies]
serde = { version = "1.0", features = ["derive"] }
```
Second example of `JSON Request` depends on `serde` and `serde_json` and `futures`:
```toml
[dependencies]
serde = { version = "1.0", features = ["derive"] }
serde_json = "1"
futures = "0.3"
```
If you want to add default value for a field, refer to `serde`'s [documentation](https://serde.rs/attr-default.html).
<CodeBlock example="requests" file="main.rs" section="json-request" />
You may also manually load the payload into memory and then deserialize it.
In the following example, we will deserialize a _MyObj_ struct. We need to load the request body first and then deserialize the json into an object.
<CodeBlock example="requests" file="manual.rs" section="json-manual" />
> A complete example for both options is available in [examples directory][examples].
## Content Encoding
Actix Web automatically _decompresses_ payloads. The following codecs are supported:
- Brotli
- Gzip
- Deflate
- Zstd
If request headers contain a `Content-Encoding` header, the request payload is decompressed according to the header value. Multiple codecs are not supported, i.e: `Content-Encoding: br, gzip`.
## Chunked transfer encoding
Actix automatically decodes _chunked_ encoding. The [`web::Payload`][payloadextractor] extractor already contains the decoded byte stream. If the request payload is compressed with one of the supported compression codecs (br, gzip, deflate), then the byte stream is decompressed.
## Multipart body
Actix Web provides multipart stream support with an external crate, [`actix-multipart`][multipartcrate].
> A full example is available in the [examples directory][multipartexample].
## Urlencoded body
Actix Web provides support for _application/x-www-form-urlencoded_ encoded bodies with the [`web::Form`][formencoded] extractor which resolves to the deserialized instance. The type of the instance must implement the `Deserialize` trait from _serde_.
The _UrlEncoded_ future can resolve into an error in several cases:
- content type is not `application/x-www-form-urlencoded`
- transfer encoding is `chunked`.
- content-length is greater than 256k
- payload terminates with error.
<CodeBlock example="requests" file="urlencoded.rs" section="urlencoded" />
## Streaming request
_HttpRequest_ is a stream of `Bytes` objects. It can be used to read the request body payload.
In the following example, we read and print the request payload chunk by chunk:
<CodeBlock example="requests" file="streaming.rs" section="streaming" />
[examples]: https://github.com/actix/examples/tree/master/json/json
[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/forms/multipart
[urlencoded]: https://docs.rs/actix-web/4/actix_web/dev/struct.UrlEncoded.html
[payloadextractor]: https://docs.rs/actix-web/4/actix_web/web/struct.Payload.html
[multipartcrate]: https://crates.io/crates/actix-multipart
[formencoded]: https://docs.rs/actix-web/4/actix_web/web/struct.Form.html

68
docs/response.md Normal file
View File

@ -0,0 +1,68 @@
---
title: Responses
---
import CodeBlock from "@site/src/components/code_block.js";
# Response
A builder-like pattern is used to construct an instance of `HttpResponse`. `HttpResponse` provides several methods that return a `HttpResponseBuilder` instance, which implements various convenience methods for building responses.
> Check the [documentation][responsebuilder] for type descriptions.
The methods `.body`, `.finish`, and `.json` finalize response creation and return a constructed _HttpResponse_ instance. If this methods is called on the same builder instance multiple times, the builder will panic.
<CodeBlock example="responses" file="main.rs" section="builder" />
## JSON Response
The `Json` type allows to respond with well-formed JSON data: simply return a value of type `Json<T>` where `T` is the type of a structure to serialize into _JSON_. The type `T` must implement the `Serialize` trait from _serde_.
For the following example to work, you need to add `serde` to your dependencies in `Cargo.toml`:
```toml
[dependencies]
serde = { version = "1.0", features = ["derive"] }
```
<CodeBlock example="responses" file="json_resp.rs" section="json-resp" />
Using the `Json` type this way instead of calling the `.json` method on a `HttpResponse` makes it immediately clear that the function returns JSON and not any other type of response.
## Content encoding
Actix Web can automatically _compress_ payloads with the [_Compress middleware_][compressmidddleware]. The following codecs are supported:
- Brotli
- Gzip
- Deflate
- Identity
<CodeBlock example="responses" file="compress.rs" section="compress" />
Response payload is compressed based on the _encoding_ parameter from the `middleware::BodyEncoding` trait. By default, `ContentEncoding::Auto` is used. If `ContentEncoding::Auto` is selected, then the compression depends on the request's `Accept-Encoding` header.
> `ContentEncoding::Identity` can be used to disable compression. If another content encoding is selected, the compression is enforced for that codec.
For example, to enable `brotli` for a single handler use `ContentEncoding::Br`:
<CodeBlock example="responses" file="brotli.rs" section="brotli" />
or for the entire application:
<CodeBlock example="responses" file="brotli_two.rs" section="brotli-two" />
In this case we explicitly disable content compression by setting content encoding to an `Identity` value:
<CodeBlock example="responses" file="identity.rs" section="identity" />
When dealing with an already compressed body (for example when serving assets), set the content encoding to `Identity` to avoid compressing the already compressed data and set the `content-encoding` header manually:
<CodeBlock example="responses" file="identity_two.rs" section="identity-two" />
Also it is possible to set default content encoding on application level, by default `ContentEncoding::Auto` is used, which implies automatic content compression negotiation.
<CodeBlock example="responses" file="auto.rs" section="auto" />
[responsebuilder]: https://docs.rs/actix-web/4/actix_web/struct.HttpResponseBuilder.html
[compressmidddleware]: https://docs.rs/actix-web/4/actix_web/middleware/struct.Compress.html

125
docs/server.md Normal file
View File

@ -0,0 +1,125 @@
---
title: Server
---
import RenderCodeBlock from '@theme/CodeBlock';
import CodeBlock from '@site/src/components/code_block.js';
import { actixWebMajorVersion } from "@site/vars";
# The HTTP Server
The [**HttpServer**][httpserverstruct] type is responsible for serving HTTP requests.
`HttpServer` accepts an application factory as a parameter, and the application factory must have `Send` + `Sync` boundaries. More about that in the _multi-threading_ section.
To start the web server it must first be bound to a network socket. Use [`HttpServer::bind()`][bindmethod] with a socket address tuple or string such as `("127.0.0.1", 8080)` or `"0.0.0.0:8080"`. This will fail if the socket is being used by another application.
After the `bind` is successful, use [`HttpServer::run()`][httpserver_run] to return a [`Server`][server] instance. The `Server` must be `await`ed or `spawn`ed to start processing requests and will run until it receives a shutdown signal (such as, by default, a `ctrl-c`; [read more here](#graceful-shutdown)).
<CodeBlock example="server" section="main" />
## Multi-Threading
`HttpServer` automatically starts a number of HTTP _workers_, by default this number is equal to the number of logical CPUs in the system. This number can be overridden with the [`HttpServer::workers()`][workers] method.
<CodeBlock example="server" file="workers.rs" section="workers" />
Once the workers are created, they each receive a separate _application_ instance to handle requests. Application state is not shared between the threads, and handlers are free to manipulate their copy of the state with no concurrency concerns.
Application state does not need to be `Send` or `Sync`, but application factories must be `Send` + `Sync`.
To share state between worker threads, use an `Arc`/`Data`. Special care should be taken once sharing and synchronization are introduced. In many cases, performance costs are inadvertently introduced as a result of locking the shared state for modifications.
In some cases these costs can be alleviated using more efficient locking strategies, for example using [read/write locks](https://doc.rust-lang.org/std/sync/struct.RwLock.html) instead of [mutexes](https://doc.rust-lang.org/std/sync/struct.Mutex.html) to achieve non-exclusive locking, but the most performant implementations often tend to be ones in which no locking occurs at all.
Since each worker thread processes its requests sequentially, handlers which block the current thread will cause the current worker to stop processing new requests:
```rust
fn my_handler() -> impl Responder {
std::thread::sleep(Duration::from_secs(5)); // <-- Bad practice! Will cause the current worker thread to hang!
"response"
}
```
For this reason, any long, non-cpu-bound operation (e.g. I/O, database operations, etc.) should be expressed as futures or asynchronous functions. Async handlers get executed concurrently by worker threads and thus don't block execution:
```rust
async fn my_handler() -> impl Responder {
tokio::time::sleep(Duration::from_secs(5)).await; // <-- Ok. Worker thread will handle other requests here
"response"
}
```
The same limitation applies to extractors as well. When a handler function receives an argument which implements `FromRequest`, and that implementation blocks the current thread, the worker thread will block when running the handler. Special attention must be given when implementing extractors for this very reason, and they should also be implemented asynchronously where needed.
## TLS / HTTPS
Actix Web supports two TLS implementations out-of-the-box: `rustls` and `openssl`.
The `rustls` crate feature is for `rustls` integration and `openssl` is for `openssl` integration.
<!-- DEPENDENCY -->
<RenderCodeBlock className="language-toml">
{`[dependencies]
actix-web = { version = "${actixWebMajorVersion}", features = ["openssl"] }
openssl = { version = "0.10" }
`}
</RenderCodeBlock>
<CodeBlock example="server" file="ssl.rs" section="ssl" />
To create the key.pem and cert.pem use the command. **Fill in your own subject**
```bash
$ openssl req -x509 -newkey rsa:4096 -keyout key.pem -out cert.pem \
-days 365 -sha256 -subj "/C=CN/ST=Fujian/L=Xiamen/O=TVlinux/OU=Org/CN=muro.lxd"
```
To remove the password, then copy nopass.pem to key.pem
```bash
$ openssl rsa -in key.pem -out nopass.pem
```
## Keep-Alive
Actix Web keeps connections open to wait for subsequent requests.
> _keep alive_ connection behavior is defined by server settings.
- `Duration::from_secs(75)` or `KeepAlive::Timeout(75)`: enables 75 second keep-alive timer.
- `KeepAlive::Os`: uses OS keep-alive.
- `None` or `KeepAlive::Disabled`: disables keep-alive.
<CodeBlock example="server" file="keep_alive.rs" section="keep-alive" />
If the first option above is selected, then keep-alive is enabled for HTTP/1.1 requests if the response does not explicitly disallow it by, for example, setting the [connection type][httpconnectiontype] to `Close` or `Upgrade`. Force closing a connection can be done with [the `force_close()` method on `HttpResponseBuilder`](https://docs.rs/actix-web/4/actix_web/dev/struct.HttpResponseBuilder.html#method.force_close)
> Keep-alive is **off** for HTTP/1.0 and is **on** for HTTP/1.1 and HTTP/2.0.
<CodeBlock example="server" file="keep_alive_tp.rs" section="example" />
## Graceful shutdown
`HttpServer` supports graceful shutdown. After receiving a stop signal, workers have a specific amount of time to finish serving requests. Any workers still alive after the timeout are force-dropped. By default the shutdown timeout is set to 30 seconds. You can change this parameter with the [`HttpServer::shutdown_timeout()`][shutdowntimeout] method.
`HttpServer` handles several OS signals. _CTRL-C_ is available on all OSes, other signals are available on unix systems.
- _SIGINT_ - Force shutdown workers
- _SIGTERM_ - Graceful shutdown workers
- _SIGQUIT_ - Force shutdown workers
> It is possible to disable signal handling with [`HttpServer::disable_signals()`][disablesignals] method.
[server]: https://docs.rs/actix-web/4/actix_web/dev/struct.Server.html
[httpserverstruct]: https://docs.rs/actix-web/4/actix_web/struct.HttpServer.html
[bindmethod]: https://docs.rs/actix-web/4/actix_web/struct.HttpServer.html#method.bind
[httpserver_run]: https://docs.rs/actix-web/4/actix_web/struct.HttpServer.html#method.run
[bindopensslmethod]: https://docs.rs/actix-web/4/actix_web/struct.HttpServer.html#method.bind_openssl
[bindrusttls]: https://docs.rs/actix-web/4/actix_web/struct.HttpServer.html#method.bind_rustls
[workers]: https://docs.rs/actix-web/4/actix_web/struct.HttpServer.html#method.workers
[tlsalpn]: https://tools.ietf.org/html/rfc7301
[exampleopenssl]: https://github.com/actix/examples/tree/master/security/openssl
[shutdowntimeout]: https://docs.rs/actix-web/4/actix_web/struct.HttpServer.html#method.shutdown_timeout
[disablesignals]: https://docs.rs/actix-web/4/actix_web/struct.HttpServer.html#method.disable_signals
[httpconnectiontype]: https://docs.rs/actix-web/4/actix_web/http/enum.ConnectionType.html

40
docs/static-files.md Normal file
View File

@ -0,0 +1,40 @@
---
title: Static Files
---
import CodeBlock from "@site/src/components/code_block.js";
# Individual file
It is possible to serve static files with a custom path pattern and `NamedFile`. To match a path tail, we can use a `[.*]` regex.
<CodeBlock example="static-files" file="main.rs" section="individual-file" />
## Directory
To serve files from specific directories and sub-directories, `Files` can be used. `Files` must be registered with an `App::service()` method, otherwise it will be unable to serve sub-paths.
<CodeBlock example="static-files" file="directory.rs" section="directory" />
By default files listing for sub-directories is disabled. Attempt to load directory listing will return _404 Not Found_ response. To enable files listing, use [_Files::show_files_listing()_][showfileslisting] method.
Instead of showing files listing for directory, it is possible to redirect to a specific index file. Use the [_Files::index_file()_][indexfile] method to configure this redirect.
## Configuration
`NamedFiles` can specify various options for serving files:
- `set_content_disposition` - function to be used for mapping file's mime to corresponding `Content-Disposition` type
- `use_etag` - specifies whether `ETag` shall be calculated and included in headers.
- `use_last_modified` - specifies whether file modified timestamp should be used and added to `Last-Modified` header.
All of the above methods are optional and provided with the best defaults, But it is possible to customize any of them.
<CodeBlock example="static-files" file="configuration.rs" section="config-one" />
The Configuration can also be applied to directory service:
<CodeBlock example="static-files" file="configuration_two.rs" section="config-two" />
[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

42
docs/testing.md Normal file
View File

@ -0,0 +1,42 @@
---
title: Testing
---
import CodeBlock from "@site/src/components/code_block.js";
# Testing
Every application should be well tested. Actix Web provides tools to perform unit and integration tests.
## Unit Tests
For unit testing, actix-web provides a request builder type. [_TestRequest_][testrequest] implements a builder-like pattern. You can generate a `HttpRequest` instance with `to_http_request()` and call your handler with it.
<CodeBlock example="testing" file="main.rs" section="unit-tests" />
## Integration tests
There are a few methods for testing your application. Actix Web can be used to run the application with specific handlers in a real HTTP server.
`TestRequest::get()`, `TestRequest::post()` and other methods can be used to send requests to the test server.
To create a `Service` for testing, use the `test::init_service` method which accepts a regular `App` builder.
> Check the [API documentation][actixdocs] for more information.
<CodeBlock example="testing" file="integration_one.rs" section="integration-one" />
If you need more complex application configuration, testing should be very similar to creating the normal application. For example, you may need to initialize application state. Create an `App` with a `data` method and attach state just like you would from a normal application.
<CodeBlock example="testing" file="integration_two.rs" section="integration-two" />
## Stream response tests
If you need to test stream generation, it would be enough to call `take_body()` and convert a resulting [_ResponseBody_][responsebody] into a future and execute it, for example when testing [_Server Sent Events_][serversentevents].
<CodeBlock example="testing" file="stream_response.rs" section="stream-response" />
[serversentevents]: https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events
[responsebody]: https://docs.rs/actix-web/4/actix_web/body/enum.ResponseBody.html
[actixdocs]: https://docs.rs/actix-web/4/actix_web/test/index.html
[testrequest]: https://docs.rs/actix-web/4/actix_web/test/struct.TestRequest.html

302
docs/url-dispatch.md Normal file
View File

@ -0,0 +1,302 @@
---
title: URL Dispatch
---
import CodeBlock from "@site/src/components/code_block.js";
# URL Dispatch
URL dispatch provides a simple way for mapping URLs to handler code using a simple pattern matching language. If one of the patterns matches the path information associated with a request, a particular handler object is invoked.
> A request handler is a function that accepts zero or more parameters that can be extracted from a request (i.e., [_impl FromRequest_][implfromrequest]) and returns a type that can be converted into an HttpResponse (i.e., [_impl Responder_][implresponder]). More information is available in the [handler section][handlersection].
## Resource configuration
Resource configuration is the act of adding a new resources to an application. A resource has a name, which acts as an identifier to be used for URL generation. The name also allows developers to add routes to existing resources. A resource also has a pattern, meant to match against the _PATH_ portion of a _URL_ (the portion following the scheme and port, e.g. _/foo/bar_ in the _URL_ _http://localhost:8080/foo/bar?q=value_). It does not match against the _QUERY_ portion (the portion that follows _?_, e.g. _q=value_ in _http://localhost:8080/foo/bar?q=value_).
The [_App::route()_][approute] method provides simple way of registering routes. This method adds a single route to application routing table. This method accepts a _path pattern_, _HTTP method_ and a handler function. `route()` method could be called multiple times for the same path, in that case, multiple routes register for the same resource path.
<CodeBlock example="url-dispatch" section="main" />
While _App::route()_ provides simple way of registering routes, to access complete resource configuration, a different method has to be used. The [_App::service()_][appservice] method adds a single [resource][webresource] to application routing table. This method accepts a _path pattern_, guards, and one or more routes.
<CodeBlock example="url-dispatch" file="resource.rs" section="resource" />
If a resource does not contain any route or does not have any matching routes, it returns _NOT FOUND_ HTTP response.
### Configuring a Route
Resource contains a set of routes. Each route in turn has a set of `guards` and a handler. New routes can be created with `Resource::route()` method which returns a reference to new _Route_ instance. By default the _route_ does not contain any guards, so matches all requests and the default handler is `HttpNotFound`.
The application routes incoming requests based on route criteria which are defined during resource registration and route registration. Resource matches all routes it contains in the order the routes were registered via `Resource::route()`.
> A _Route_ can contain any number of _guards_ but only one handler.
<CodeBlock example="url-dispatch" file="cfg.rs" section="cfg" />
In this example, `HttpResponse::Ok()` is returned for _GET_ requests if the request contains `Content-Type` header, the value of this header is _text/plain_, and path equals to `/path`.
If a resource can not match any route, a "NOT FOUND" response is returned.
[_ResourceHandler::route()_][resourcehandler] returns a [_Route_][route] object. Route can be configured with a builder-like pattern. Following configuration methods are available:
- [_Route::guard()_][routeguard] registers a new guard. Any number of guards can be registered for each route.
- [_Route::method()_][routemethod] registers a method guard. Any number of guards can be registered for each route.
- [_Route::to()_][routeto] registers an async handler function for this route. Only one handler can be registered. Usually handler registration is the last config operation.
## Route matching
The main purpose of route configuration is to match (or not match) the request's `path` against a URL path pattern. `path` represents the path portion of the URL that was requested.
The way that _actix-web_ does this is very simple. When a request enters the system, for each resource configuration declaration present in the system, actix checks the request's path against the pattern declared. This checking happens in the order that the routes were declared via `App::service()` method. If resource can not be found, the _default resource_ is used as the matched resource.
When a route configuration is declared, it may contain route guard arguments. All route guards associated with a route declaration must be `true` for the route configuration to be used for a given request during a check. If any guard in the set of route guard arguments provided to a route configuration returns `false` during a check, that route is skipped and route matching continues through the ordered set of routes.
If any route matches, the route matching process stops and the handler associated with the route is invoked. If no route matches after all route patterns are exhausted, a _NOT FOUND_ response get returned.
## Resource pattern syntax
The syntax of the pattern matching language used by actix in the pattern argument is straightforward.
The pattern used in route configuration may start with a slash character. If the pattern does not start with a slash character, an implicit slash will be prepended to it at matching time. For example, the following patterns are equivalent:
```
{foo}/bar/baz
```
and:
```
/{foo}/bar/baz
```
A _variable part_ (replacement marker) is specified in the form _{identifier}_, where this means "accept any characters up to the next slash character and use this as the name in the `HttpRequest.match_info()` object".
A replacement marker in a pattern matches the regular expression `[^{}/]+`.
A match_info is the `Params` object representing the dynamic parts extracted from a _URL_ based on the routing pattern. It is available as _request.match_info_. For example, the following pattern defines one literal segment (foo) and two replacement markers (baz, and bar):
```
foo/{baz}/{bar}
```
The above pattern will match these URLs, generating the following match information:
```
foo/1/2 -> Params {'baz': '1', 'bar': '2'}
foo/abc/def -> Params {'baz': 'abc', 'bar': 'def'}
```
It will not match the following patterns however:
```
foo/1/2/ -> No match (trailing slash)
bar/abc/def -> First segment literal mismatch
```
The match for a segment replacement marker in a segment will be done only up to the first non-alphanumeric character in the segment in the pattern. So, for instance, if this route pattern was used:
```
foo/{name}.html
```
The literal path `/foo/biz.html` will match the above route pattern, and the match result will be `Params {'name': 'biz'}`. However, the literal path `/foo/biz` will not match, because it does not contain a literal `.html` at the end of the segment represented by `{name}.html` (it only contains biz, not biz.html).
To capture both segments, two replacement markers can be used:
```
foo/{name}.{ext}
```
The literal path `/foo/biz.html` will match the above route pattern, and the match result will be `Params {'name': 'biz', 'ext': 'html'}`. This occurs because there is a literal part of `.` (period) between the two replacement markers `{name}` and `{ext}`.
Replacement markers can optionally specify a regular expression which will be used to decide whether a path segment should match the marker. To specify that a replacement marker should match only a specific set of characters as defined by a regular expression, you must use a slightly extended form of replacement marker syntax. Within braces, the replacement marker name must be followed by a colon, then directly thereafter, the regular expression. The default regular expression associated with a replacement marker `[^/]+` matches one or more characters which are not a slash. For example, under the hood, the replacement marker `{foo}` can more verbosely be spelled as `{foo:[^/]+}`. You can change this to be an arbitrary regular expression to match an arbitrary sequence of characters, such as `{foo:\d+}` to match only digits.
Segments must contain at least one character in order to match a segment replacement marker. For example, for the URL `/abc/`:
- `/abc/{foo}` will not match.
- `/{foo}/` will match.
> **Note**: path will be URL-unquoted and decoded into valid unicode string before matching pattern and values representing matched path segments will be URL-unquoted too.
So for instance, the following pattern:
```
foo/{bar}
```
When matching the following URL:
```
http://example.com/foo/La%20Pe%C3%B1a
```
The match dictionary will look like so (the value is URL-decoded):
```
Params {'bar': 'La Pe\xf1a'}
```
Literal strings in the path segment should represent the decoded value of the path provided to actix. You don't want to use a URL-encoded value in the pattern. For example, rather than this:
```
/Foo%20Bar/{baz}
```
You'll want to use something like this:
```
/Foo Bar/{baz}
```
It is possible to get "tail match". For this purpose custom regex has to be used.
```
foo/{bar}/{tail:.*}
```
The above pattern will match these URLs, generating the following match information:
```
foo/1/2/ -> Params {'bar': '1', 'tail': '2/'}
foo/abc/def/a/b/c -> Params {'bar': 'abc', 'tail': 'def/a/b/c'}
```
## Scoping Routes
Scoping helps you organize routes sharing common root paths. You can nest scopes within scopes.
Suppose that you want to organize paths to endpoints used to view "Users". Such paths may include:
- /users
- /users/show
- /users/show/{id}
A scoped layout of these paths would appear as follows
<CodeBlock example="url-dispatch" file="scope.rs" section="scope" />
A _scoped_ path can contain variable path segments as resources. Consistent with un-scoped paths.
You can get variable path segments from `HttpRequest::match_info()`. [`Path` extractor][pathextractor] also is able to extract scope level variable segments.
## Match information
All values representing matched path segments are available in [`HttpRequest::match_info`][matchinfo]. Specific values can be retrieved with [`Path::get()`][pathget].
<CodeBlock example="url-dispatch" file="minfo.rs" section="minfo" />
For this example for path '/a/1/2/', values v1 and v2 will resolve to "1" and "2".
### Path information extractor
Actix provides functionality for type safe path information extraction. [_Path_][pathstruct] extracts information, destination type could be defined in several different forms. Simplest approach is to use `tuple` type. Each element in tuple must correspond to one element from path pattern. i.e. you can match path pattern `/{id}/{username}/` against `Path<(u32, String)>` type, but `Path<(String, String, String)>` type will always fail.
<CodeBlock example="url-dispatch" file="path.rs" section="path" />
It also possible to extract path pattern information to a struct. In this case, this struct must implement _serde's_ `Deserialize` trait.
<CodeBlock example="url-dispatch" file="path2.rs" section="path" />
[_Query_][query] provides similar functionality for request query parameters.
## Generating resource URLs
Use the [_HttpRequest.url_for()_][urlfor] method to generate URLs based on resource patterns. For example, if you've configured a resource with the name "foo" and the pattern "{a}/{b}/{c}", you might do this:
<CodeBlock example="url-dispatch" file="urls.rs" section="url" />
This would return something like the string *http://example.com/test/1/2/3* (at least if the current protocol and hostname implied http://example.com). `url_for()` method returns [_Url object_][urlobj] so you can modify this url (add query parameters, anchor, etc). `url_for()` could be called only for _named_ resources otherwise error get returned.
## External resources
Resources that are valid URLs, can be registered as external resources. They are useful for URL generation purposes only and are never considered for matching at request time.
<CodeBlock example="url-dispatch" file="url_ext.rs" section="ext" />
## Path normalization and redirecting to slash-appended routes
By normalizing it means:
- To add a trailing slash to the path.
- To replace multiple slashes with one.
The handler returns as soon as it finds a path that resolves correctly. The order of normalization conditions, if all are enabled, is 1) merge, 2) both merge and append and 3) append. If the path resolves with at least one of those conditions, it will redirect to the new path.
<CodeBlock example="url-dispatch" file="norm.rs" section="norm" />
In this example `//resource///` will be redirected to `/resource/`.
In this example, the path normalization handler is registered for all methods, but you should not rely on this mechanism to redirect _POST_ requests. The redirect of the slash-appending _Not Found_ will turn a _POST_ request into a GET, losing any _POST_ data in the original request.
It is possible to register path normalization only for _GET_ requests only:
<CodeBlock example="url-dispatch" file="norm2.rs" section="norm" />
### Using an Application Prefix to Compose Applications
The `web::scope()` method allows to set a specific application scope. This scope represents a resource prefix that will be prepended to all resource patterns added by the resource configuration. This can be used to help mount a set of routes at a different location than the included callable's author intended while still maintaining the same resource names.
For example:
<CodeBlock example="url-dispatch" file="scope.rs" section="scope" />
In the above example, the _show_users_ route will have an effective route pattern of _/users/show_ instead of _/show_ because the application's scope will be prepended to the pattern. The route will then only match if the URL path is _/users/show_, and when the `HttpRequest.url_for()` function is called with the route name show_users, it will generate a URL with that same path.
## Custom route guard
You can think of a guard as a simple function that accepts a _request_ object reference and returns _true_ or _false_. Formally, a guard is any object that implements the [`Guard`][guardtrait] trait. Actix provides several predicates, you can check [functions section][guardfuncs] of API docs.
Here is a simple guard that check that a request contains a specific _header_:
<CodeBlock example="url-dispatch" file="guard.rs" section="guard" />
In this example, _index_ handler will be called only if request contains _CONTENT-TYPE_ header.
Guards can not access or modify the request object, but it is possible to store extra information in [request extensions][requestextensions].
### Modifying guard values
You can invert the meaning of any predicate value by wrapping it in a `Not` predicate. For example, if you want to return "METHOD NOT ALLOWED" response for all methods except "GET":
<CodeBlock example="url-dispatch" file="guard2.rs" section="guard2" />
The `Any` guard accepts a list of guards and matches if any of the supplied guards match. i.e:
```rust
guard::Any(guard::Get()).or(guard::Post())
```
The `All` guard accepts a list of guard and matches if all of the supplied guards match. i.e:
```rust
guard::All(guard::Get()).and(guard::Header("content-type", "plain/text"))
```
## Changing the default Not Found response
If the path pattern can not be found in the routing table or a resource can not find matching route, the default resource is used. The default response is _NOT FOUND_. It is possible to override the _NOT FOUND_ response with `App::default_service()`. This method accepts a _configuration function_ same as normal resource configuration with `App::service()` method.
<CodeBlock example="url-dispatch" file="dhandler.rs" section="default" />
[handlersection]: /docs/handlers/
[approute]: https://docs.rs/actix-web/4/actix_web/struct.App.html#method.route
[appservice]: https://docs.rs/actix-web/4/actix_web/struct.App.html?search=#method.service
[webresource]: https://docs.rs/actix-web/4/actix_web/struct.Resource.html
[resourcehandler]: https://docs.rs/actix-web/4/actix_web/struct.Resource.html#method.route
[route]: https://docs.rs/actix-web/4/actix_web/struct.Route.html
[routeguard]: https://docs.rs/actix-web/4/actix_web/struct.Route.html#method.guard
[routemethod]: https://docs.rs/actix-web/4/actix_web/struct.Route.html#method.method
[routeto]: https://docs.rs/actix-web/4/actix_web/struct.Route.html#method.to
[matchinfo]: https://docs.rs/actix-web/4/actix_web/struct.HttpRequest.html#method.match_info
[pathget]: https://docs.rs/actix-web/4/actix_web/dev/struct.Path.html#method.get
[pathstruct]: https://docs.rs/actix-web/4/actix_web/dev/struct.Path.html
[query]: https://docs.rs/actix-web/4/actix_web/web/struct.Query.html
[urlfor]: https://docs.rs/actix-web/4/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/4/actix_web/guard/trait.Guard.html
[guardfuncs]: https://docs.rs/actix-web/4/actix_web/guard/index.html#functions
[requestextensions]: https://docs.rs/actix-web/4/actix_web/struct.HttpRequest.html#method.extensions
[implfromrequest]: https://docs.rs/actix-web/4/actix_web/trait.FromRequest.html
[implresponder]: https://docs.rs/actix-web/4/actix_web/trait.Responder.html
[pathextractor]: /docs/extractors

23
docs/websockets.md Normal file
View File

@ -0,0 +1,23 @@
---
title: Websockets
---
import CodeBlock from "@site/src/components/code_block.js";
# Websockets
Actix Web supports WebSockets with the `actix-web-actors` crate. It is possible to convert a request's `Payload` to a stream of [_ws::Message_][message] with a [_web::Payload_][payload] and then use stream combinators to handle actual messages, but it is simpler to handle websocket communications with an http actor.
The following is an example of a simple websocket echo server:
<CodeBlock example="websockets" file="main.rs" section="websockets" />
> A simple websocket echo server example is available in the [examples directory][examples].
> 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/2/actix_web_actors/ws/enum.Message.html
[payload]: https://docs.rs/actix-web/4/actix_web/web/struct.Payload.html
[examples]: https://github.com/actix/examples/tree/master/websockets
[chat]: https://github.com/actix/examples/tree/master/websockets/chat

16
docs/welcome.md Normal file
View File

@ -0,0 +1,16 @@
---
title: Welcome
description: Guiding you through building web apps with Actix
slug: /
---
# Welcome to Actix
Actix Web lets you quickly and confidently develop web services in Rust and this guide will get you going in no time.
The documentation on this website focusses primarily on the Actix Web framework. For information about the actor framework called Actix, check out the [Actix book][actix-book] (or the lower level [actix API docs][actix-docs]). Otherwise, head on to the [getting started guide][getting-started]. If you already know your way around and you need specific information you might want to read the [actix-web API docs][actix-web-docs].
[getting-started]: ./getting-started
[actix-web-docs]: https://docs.rs/actix-web
[actix-docs]: https://docs.rs/actix
[actix-book]: https://actix.rs/book/actix

26
docs/whatis.md Normal file
View File

@ -0,0 +1,26 @@
---
title: What is Actix Web
---
import { rustVersion } from "@site/vars";
# Actix Web is part of an Ecosystem of Crates
Long ago, Actix Web was built on top of the `actix` actor framework. Now, Actix Web is largely unrelated to the actor framework and is built using a different system. Though `actix` is still maintained, its usefulness as a general tool is diminishing as the futures and async/await ecosystem matures. At this time, the use of `actix` is only required for WebSocket endpoints.
We call Actix Web a powerful and pragmatic framework. For all intents and purposes it's a micro-framework with a few twists. If you are already a Rust programmer you will probably find yourself at home quickly, but even if you are coming from another programming language you should find Actix Web easy to pick up.
<!-- TODO -->
<!-- actix-extras -->
An application developed with Actix Web will expose an HTTP server contained within a native executable. You can either put this behind another HTTP server like nginx or serve it up as-is. Even in the complete absence of another HTTP server Actix Web is powerful enough to provide HTTP/1 and HTTP/2 support as well as TLS (HTTPS). This makes it useful for building small services ready for production.
<p>
Most importantly: Actix Web runs on Rust { rustVersion } or later and it works with stable releases.
</p>
<!-- TODO -->
<!-- which is built upon the fantastic [Tokio][tokio] asynchronous I/O system -->
<!-- LINKS -->
[tokio]: https://tokio.rs