mirror of
https://github.com/actix/actix-website
synced 2024-11-27 10:02:57 +01:00
All links in markdown are now footnotes for easier updating.
This commit is contained in:
parent
6b08c4664b
commit
b9c78c1a58
@ -12,13 +12,16 @@ weight: 10
|
||||
Actix is your door to developing web services with Rust and this documentation
|
||||
is going to guide you.
|
||||
|
||||
This documentation currently covers mostly the `actix-web` part which is the
|
||||
high level web framework previously built on top of the `actix` actor framework and the
|
||||
[Tokio](https://tokio.rs/) async IO system. This is the part that is from an
|
||||
API stability point of view the most stable.
|
||||
This documentation currently covers mostly the `actix-web` part which is the high level
|
||||
web framework previously built on top of the `actix` actor framework and the [Tokio][tokio]
|
||||
async IO system. This is the part that is from an API stability point of view the most stable.
|
||||
|
||||
If you haven't used `actix-web` yet it's best to start with the [getting started
|
||||
guide](getting-started/). If you already know your ways around and you need
|
||||
specific information you might want to read the [actix-web API
|
||||
docs](https://docs.rs/actix-web) (or the lower level [actix API
|
||||
docs](https://docs.rs/actix)).
|
||||
guide][gettingstarted]. If you already know your ways around and you need
|
||||
specific information you might want to read the [actix-web API docs][actixwebdocs]
|
||||
(or the lower level [actix API docs][actixdocs]).
|
||||
|
||||
[gettingstarted]: ./getting-started
|
||||
[actixwebdocs]: https://docs.rs/actix-web
|
||||
[actixdocs]: https://docs.rs/actix
|
||||
[tokio]: (https://tokio.rs/)
|
||||
|
@ -28,8 +28,7 @@ it is automatically inserted. The prefix should consist of value path segments.
|
||||
In this example, an application with the `/app` prefix and a `index.html` resource
|
||||
are created. This resource is available through the `/app/index.html` url.
|
||||
|
||||
> For more information, check the
|
||||
> [URL Dispatch](/docs/url-dispatch/index.html#using-an-application-prefix-to-compose-applications) section.
|
||||
> For more information, check the [URL Dispatch][usingappprefix] section.
|
||||
|
||||
Multiple application scopes can be served with one server:
|
||||
|
||||
@ -61,9 +60,8 @@ When the app is initialized it needs to be passed the initial state:
|
||||
> instance. `HttpServer` constructs an application instance for each thread, thus
|
||||
> application state must be constructed multiple times. If you want to share state between
|
||||
> different threads, a shared object should be used, e.g. `Arc`. There is also an
|
||||
> [Example](https://github.com/actix/examples/blob/master/state/src/main.rs) using `Arc`
|
||||
> for this. Application state does not need to be `Send` and `Sync`,
|
||||
> but the application factory must be `Send` + `Sync`.
|
||||
> [Example][stateexample] using `Arc` for this. Application state does not need to be
|
||||
> `Send` and `Sync`, but the application factory must be `Send` + `Sync`.
|
||||
|
||||
To start the previous app, create it into a closure:
|
||||
|
||||
@ -77,11 +75,10 @@ Combining multiple applications with different state is possible as well.
|
||||
|
||||
## Using an Application Scope to Compose Applications
|
||||
|
||||
The `web::scope()` method allows to set a specific application 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 included callable's author intended while still maintaining the same
|
||||
resource names.
|
||||
The `web::scope()` method allows to set a specific application 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 included callable's author intended while still maintaining the same resource names.
|
||||
|
||||
For example:
|
||||
|
||||
@ -97,13 +94,11 @@ it will generate a URL with that same path.
|
||||
|
||||
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`](https://docs.rs/actix-web/1.0.2/actix_web/guard/trait.Guard.html) trait. Actix-web
|
||||
provides several guards, you can check
|
||||
[functions section](https://docs.rs/actix-web/1.0.2/actix_web/guard/index.html#functions)
|
||||
of api docs.
|
||||
[`Guard`][guardtrait] trait. Actix-web provides several guards, you can check
|
||||
[functions section][guardfuncs] of api docs.
|
||||
|
||||
One of the provided guards is [`Header`](https://docs.rs/actix-web/1.0.2/actix_web/guard/fn.Header.html),
|
||||
it can be used as application's filter based on request's header information.
|
||||
One of the provided guards is [`Header`][guardheader], it can be used as application's
|
||||
filter based on request's header information.
|
||||
|
||||
{{< include-example example="application" file="vh.rs" section="vh" >}}
|
||||
|
||||
@ -125,3 +120,9 @@ The result of the above example would be:
|
||||
```
|
||||
|
||||
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
|
||||
|
@ -6,13 +6,11 @@ weight: 1000
|
||||
|
||||
# Auto-Reloading Development Server
|
||||
|
||||
During development it can be very handy to have cargo automatically recompile
|
||||
the code on change. This can be accomplished by using
|
||||
[cargo-watch](https://github.com/passcod/cargo-watch). Because an actix app
|
||||
will typically bind to a port for listening for incoming HTTP requests it makes
|
||||
sense to combine this with the [listenfd](https://crates.io/crates/listenfd)
|
||||
crate and the [systemfd](https://github.com/mitsuhiko/systemfd) utility to
|
||||
ensure the socket is kept open while the app is compiling and reloading.
|
||||
During development it can be very handy to have cargo automatically recompile the code
|
||||
on change. This can be accomplished by using [cargo-watch][cargowatch]. Because an
|
||||
actix app will typically bind to a port for listening for incoming HTTP requests it makes
|
||||
sense to combine this with the [listenfd][listenfd] crate and the [systemfd][systemfd]
|
||||
utility to ensure the socket is kept open while the app is compiling and reloading.
|
||||
|
||||
`systemfd` will open a socket and pass it to `cargo-watch` which will watch for
|
||||
changes and then invoke the compiler and run your actix app. The actix app
|
||||
@ -30,8 +28,7 @@ cargo install systemfd cargo-watch
|
||||
## Code Changes
|
||||
|
||||
Additionally you need to slightly modify your actix app so that it can pick up
|
||||
an external socket opened by `systemfd`. Add the listenfd dependency to your
|
||||
app:
|
||||
an external socket opened by `systemfd`. Add the listenfd dependency to your app:
|
||||
|
||||
```ini
|
||||
[dependencies]
|
||||
@ -49,3 +46,7 @@ To now run the development server invoke this command:
|
||||
```
|
||||
systemfd --no-pid -s http::3000 -- cargo watch -x run
|
||||
```
|
||||
|
||||
[cargowatch]: https://github.com/passcod/cargo-watch
|
||||
[listenfd]: https://crates.io/crates/listenfd
|
||||
[systemfd]: https://github.com/mitsuhiko/systemfd
|
||||
|
@ -39,8 +39,10 @@ thus, we receive the message response asynchronously.
|
||||
|
||||
{{< include-example example="og_databases" file="main.rs" section="index" >}}
|
||||
|
||||
> A full example is available in the
|
||||
> [examples directory](https://github.com/actix/examples/tree/master/diesel/).
|
||||
> A full example is available in the [examples directory][examples].
|
||||
|
||||
> More information on sync actors can be found in the
|
||||
> [actix documentation](https://docs.rs/actix/0.7.0/actix/sync/index.html).
|
||||
> [actix documentation][actixdocs].
|
||||
|
||||
[examples]: https://github.com/actix/examples/tree/master/diesel/
|
||||
[actixdocs]: https://docs.rs/actix/0.7.0/actix/sync/index.html
|
||||
|
@ -23,19 +23,18 @@ Option 2 - accessed by calling `extract()` on the Extractor
|
||||
|
||||
# Path
|
||||
|
||||
[*Path*](https://docs.rs/actix-web/1.0.2/actix_web/dev/struct.Path.html) provides
|
||||
information that can be extracted from the Request's path. You can deserialize any
|
||||
variable segment from the path.
|
||||
[*Path*][pathstruct] provides information that can be extracted from the Request's
|
||||
path. You can deserialize any variable segment from the path.
|
||||
|
||||
For instance, for resource that registered for the `/users/{userid}/{friend}` path
|
||||
two segments could be deserialized, `userid` and `friend`. These segments
|
||||
could be extracted into a `tuple`, i.e. `Path<(u32, String)>` or any structure
|
||||
that implements the `Deserialize` trait from the *serde* crate.
|
||||
two segments could be deserialized, `userid` and `friend`. These segments could be
|
||||
extracted into a `tuple`, i.e. `Path<(u32, String)>` or any structure that implements
|
||||
the `Deserialize` trait from the *serde* crate.
|
||||
|
||||
{{< include-example example="extractors" file="path_one.rs" section="path-one" >}}
|
||||
|
||||
It is also possible to extract path information to a specific type that
|
||||
implements the `Deserialize` trait from *serde*. Here is an equivalent example that uses *serde*
|
||||
It is also possible to extract path information to a specific type that implements the
|
||||
`Deserialize` trait from *serde*. Here is an equivalent example that uses *serde*
|
||||
instead of a *tuple* type.
|
||||
|
||||
{{< include-example example="extractors" file="path_two.rs" section="path-two" >}}
|
||||
@ -46,25 +45,24 @@ It is also possible to `get` or `query` the request for path parameters by name:
|
||||
|
||||
# Query
|
||||
|
||||
The [*Query*](https://docs.rs/actix-web/1.0.2/actix_web/web/struct.Query.html)
|
||||
type provides extraction functionality for the request's query parameters. Underneath it
|
||||
uses *serde_urlencoded* crate.
|
||||
The [*Query*][querystruct] type provides extraction functionality for the request's
|
||||
query parameters. Underneath it uses *serde_urlencoded* crate.
|
||||
|
||||
{{< include-example example="extractors" file="query.rs" section="query" >}}
|
||||
|
||||
# Json
|
||||
|
||||
[*Json*](https://docs.rs/actix-web/1.0.2/actix_web/web/struct.Json.html) allows to deserialize
|
||||
a request body into a struct. To extract typed information from a request's body,
|
||||
the type `T` must implement the `Deserialize` trait from *serde*.
|
||||
[*Json*][jsonstruct] allows to deserialize a request body into a struct. To extract
|
||||
typed information from a request's body, the type `T` must implement the `Deserialize`
|
||||
trait from *serde*.
|
||||
|
||||
{{< include-example example="extractors" file="json_one.rs" section="json-one" >}}
|
||||
|
||||
Some extractors provide a way to configure the extraction process. Json extractor
|
||||
[*JsonConfig*](https://docs.rs/actix-web/1.0.2/actix_web/web/struct.JsonConfig.html) type
|
||||
for configuration. To configure an extractor, pass it's configuration object to the resource's
|
||||
`.data()` method. In case of a *Json* extractor it returns a *JsonConfig*. You can
|
||||
configure the maximum size of the json payload as well as a custom error handler function.
|
||||
[*JsonConfig*][jsonconfig] type for configuration. To configure an extractor, pass it's
|
||||
configuration object to the resource's `.data()` method. In case of a *Json* extractor
|
||||
it returns a *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.
|
||||
|
||||
@ -72,19 +70,18 @@ The following example limits the size of the payload to 4kb and uses a custom er
|
||||
|
||||
# Form
|
||||
|
||||
At the moment only url-encoded forms are supported. The url-encoded body
|
||||
could be extracted to a specific type. This type must implement
|
||||
the `Deserialize` trait from the *serde* crate.
|
||||
At the moment only url-encoded forms are supported. The url-encoded body could be
|
||||
extracted to a specific type. This type must implement the `Deserialize` trait from
|
||||
the *serde* crate.
|
||||
|
||||
[*FormConfig*](https://docs.rs/actix-web/1.0.2/actix_web/web/struct.FormConfig.html) allows
|
||||
configuring the extraction process.
|
||||
[*FormConfig*][formconfig] allows configuring the extraction process.
|
||||
|
||||
{{< include-example example="extractors" file="form.rs" section="form" >}}
|
||||
|
||||
# Multiple extractors
|
||||
|
||||
Actix-web provides extractor implementations for tuples (up to 10 elements)
|
||||
whose elements implement `FromRequest`.
|
||||
Actix-web provides extractor implementations for tuples (up to 10 elements) whose
|
||||
elements implement `FromRequest`.
|
||||
|
||||
For example we can use a path extractor and a query extractor at the same time.
|
||||
|
||||
@ -94,18 +91,16 @@ For example we can use a path extractor and a query extractor at the same time.
|
||||
|
||||
Actix-web also provides several other extractors:
|
||||
|
||||
* [*Data*](https://docs.rs/actix-web/1.0.2/actix_web/web/struct.Data.html) - 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*](https://docs.rs/actix-web/1.0.2/actix_web/trait.FromRequest.html#example-2)
|
||||
* [*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.
|
||||
* *bytes::Bytes* - You can convert a request's payload into *Bytes*.
|
||||
[*Example*](https://docs.rs/actix-web/1.0.2/actix_web/trait.FromRequest.html#example-4)
|
||||
[*Example*][bytesexample]
|
||||
is available in doc strings.
|
||||
* *Payload* - You can access a request's payload.
|
||||
[*Example*](https://docs.rs/actix-web/1.0.2/actix_web/web/struct.Payload.html)
|
||||
[*Example*][payloadexample]
|
||||
|
||||
# Async Data Access
|
||||
|
||||
@ -130,4 +125,15 @@ number of requests processed per thread. A proper implementation would use `Arc`
|
||||
> Be careful with synchronization primitives like `Mutex` or `RwLock`. The `actix-web` framework
|
||||
> handles requests asynchronously. By blocking thread execution, all concurrent
|
||||
> request handling processes would block. If you need to share or update some state
|
||||
> from multiple threads, consider using the [actix](https://actix.github.io/actix/actix/) actor system.
|
||||
> from multiple threads, consider using the [actix][actix] actor system.
|
||||
|
||||
[pathstruct]: (https://docs.rs/actix-web/1.0.2/actix_web/dev/struct.Path.html
|
||||
[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
|
||||
[actix]: https://actix.github.io/actix/actix/
|
||||
|
@ -45,4 +45,6 @@ Head over to ``http://localhost:8088/`` to see the results.
|
||||
|
||||
If you want, you can have an automatic reloading server during development
|
||||
that recompiles on demand. To see how this can be accomplished have a look
|
||||
at the [autoreload pattern](../autoreload/).
|
||||
at the [autoreload pattern][autoload].
|
||||
|
||||
[autoload]: ../autoreload/
|
||||
|
@ -7,22 +7,17 @@ weight: 160
|
||||
# Request Handlers
|
||||
|
||||
A request handler is a function that accepts zero or more parameters that can be extracted
|
||||
from a request (ie,
|
||||
[*impl FromRequest*](https://docs.rs/actix-web/1.0.2/actix_web/trait.FromRequest.html))
|
||||
and returns a type that can be converted into an HttpResponse (ie,
|
||||
[*impl Responder*](https://docs.rs/actix-web/1.0.2/actix_web/trait.Responder.html)).
|
||||
from a request (ie, [*impl FromRequest*][implfromrequest]) and returns a type that can
|
||||
be converted into an HttpResponse (ie, [*impl Responder*][implresponder]).
|
||||
|
||||
Request handling happens in two stages. First the handler object is called,
|
||||
returning any object that implements the
|
||||
[*Responder*](https://docs.rs/actix-web/1.0.2/actix_web/trait.Responder.html) trait.
|
||||
Then, `respond_to()` is called on the returned object, converting itself to a `HttpResponse`
|
||||
or `Error`.
|
||||
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 provides `Responder` implementations for some standard types,
|
||||
By default actix-web provides `Responder` implementations for some standard types,
|
||||
such as `&'static str`, `String`, etc.
|
||||
|
||||
> For a complete list of implementations, check
|
||||
> [*Responder documentation*](../../actix-web/actix_web/trait.Responder.html#foreign-impls).
|
||||
> For a complete list of implementations, check [*Responder documentation*][responderimpls].
|
||||
|
||||
Examples of valid handlers:
|
||||
|
||||
@ -64,31 +59,37 @@ Let's create a response for a custom type that serializes to an `application/jso
|
||||
## Async handlers
|
||||
|
||||
There are two different types of async handlers. Response objects can be generated asynchronously
|
||||
or more precisely, any type that implements the [*Responder*](../../actix-web/actix_web/trait.Responder.html) trait.
|
||||
or more precisely, any type that implements the [*Responder*][respondertrait] trait.
|
||||
|
||||
In this case, the handler must return a `Future` object that resolves to the *Responder* type, i.e:
|
||||
|
||||
{{< include-example example="async-handlers" file="main.rs" section="async-responder" >}}
|
||||
|
||||
Or the response body can be generated asynchronously. In this case, body
|
||||
must implement the stream trait `Stream<Item=Bytes, Error=Error>`, i.e:
|
||||
Or the response body can be generated asynchronously. In this case, body must implement
|
||||
the stream trait `Stream<Item=Bytes, Error=Error>`, i.e:
|
||||
|
||||
{{< include-example example="async-handlers" file="stream.rs" section="stream" >}}
|
||||
|
||||
Both methods can be combined. (i.e Async response with streaming body)
|
||||
|
||||
It is possible to return a `Result` where the `Result::Item` type can be `Future`.
|
||||
In this example, the `index` handler can return an error immediately or return a
|
||||
future that resolves to a `HttpResponse`.
|
||||
It is possible to return a `Result` where the `Result::Item` type can be `Future`. In
|
||||
this example, the `index` handler can return an error immediately or return a future
|
||||
that resolves to a `HttpResponse`.
|
||||
|
||||
{{< include-example example="async-handlers" file="async_stream.rs" section="async-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.
|
||||
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*](../../actix-web/actix_web/enum.Either.html) type can be used.
|
||||
`Either` allows combining two different responder types into a single type.
|
||||
For this case, the [*Either*][either] type can be used. `Either` allows combining two
|
||||
different responder types into a single type.
|
||||
|
||||
{{< include-example example="either" file="main.rs" section="either" >}}
|
||||
|
||||
[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
|
||||
[respondertrait]: https://docs.rs/actix-web/1.0.2/actix_web/trait.Responder.html
|
||||
[responderimpls]: ../../actix-web/actix_web/trait.Responder.html#foreign-impls
|
||||
[either]: ../../actix-web/actix_web/enum.Either.html
|
||||
|
@ -8,13 +8,12 @@ weight: 250
|
||||
|
||||
# Negotiation
|
||||
|
||||
*HTTP/2.0* protocol over tls without prior knowledge requires
|
||||
[tls alpn](https://tools.ietf.org/html/rfc7301).
|
||||
*HTTP/2.0* protocol over tls without prior knowledge requires [tls alpn][tlsalpn].
|
||||
|
||||
> Currently, only `rust-openssl` has support.
|
||||
|
||||
`alpn` negotiation requires enabling the feature. When enabled, `HttpServer` provides the
|
||||
[bind_ssl](../../actix-web/actix_web/server/struct.HttpServer.html#method.serve_tls) method.
|
||||
[bind_ssl][bindssl] method.
|
||||
|
||||
```toml
|
||||
[dependencies]
|
||||
@ -23,10 +22,14 @@ openssl = { version = "0.10", features = ["v110"] }
|
||||
```
|
||||
{{< include-example example="http2" file="main.rs" section="main" >}}
|
||||
|
||||
Upgrades to *HTTP/2.0* schema described in
|
||||
[rfc section 3.2](https://http2.github.io/http2-spec/#rfc.section.3.2) is not supported.
|
||||
Starting *HTTP/2* with prior knowledge is supported for both clear text connection
|
||||
and tls connection. [rfc section 3.4](https://http2.github.io/http2-spec/#rfc.section.3.4)
|
||||
Upgrades to *HTTP/2.0* schema described in [rfc section 3.2][rfcsection32] is not
|
||||
supported. Starting *HTTP/2* with prior knowledge is supported for both clear text
|
||||
connection and tls connection. [rfc section 3.4][rfcsection34].
|
||||
|
||||
> Check out [examples/tls](https://github.com/actix/examples/tree/master/tls)
|
||||
> for a concrete example.
|
||||
> Check out [examples/tls][examples] for a concrete example.
|
||||
|
||||
[rfcsection32]: https://http2.github.io/http2-spec/#rfc.section.3.2
|
||||
[rfcsection34]: https://http2.github.io/http2-spec/#rfc.section.3.4
|
||||
[bindssl]: ../../actix-web/actix_web/server/struct.HttpServer.html#method.serve_tls
|
||||
[tlsalpn]: https://tools.ietf.org/html/rfc7301
|
||||
[examples]: https://github.com/actix/examples/tree/master/tls
|
||||
|
@ -6,16 +6,13 @@ weight: 110
|
||||
|
||||
# Installing Rust
|
||||
|
||||
Since `actix-web` is a Rust framework you will need Rust to get started with it.
|
||||
If you don't have it yet we recommend you use `rustup` to manage your Rust
|
||||
installation. The [official rust
|
||||
guide](https://doc.rust-lang.org/book/ch01-01-installation.html)
|
||||
has a wonderful section on getting started.
|
||||
Since `actix-web` is a Rust framework you will need Rust to get started with it. If you
|
||||
don't have it yet we recommend you use `rustup` to manage your Rust installation. The
|
||||
[official rust guide][rustguide] has a wonderful section on getting started.
|
||||
|
||||
We currently require at least Rust {{< rust-version "actix-web" >}} so make sure you
|
||||
run `rustup update` to have the latest and greatest Rust version available. In
|
||||
particular this guide will assume that you actually run Rust
|
||||
{{< rust-version "actix-web" >}} or later.
|
||||
We currently require at least Rust {{< rust-version "actix-web" >}} so make sure you run
|
||||
`rustup update` to have the latest and greatest Rust version available. In particular
|
||||
this guide will assume that you actually run Rust {{< rust-version "actix-web" >}} or later.
|
||||
|
||||
# Installing `actix-web`
|
||||
|
||||
@ -40,10 +37,9 @@ actix-web = { git = "https://github.com/actix/actix-web" }
|
||||
|
||||
# Diving In
|
||||
|
||||
There are two paths you can take here. You can follow the guide along or if
|
||||
you are very impatient you might want to have a look at our
|
||||
[extensive example repository](https://github.com/actix/examples) and run the
|
||||
included examples. Here for instance is how you run the included `basics`
|
||||
There are two paths you can take here. You can follow the guide along or if you are very
|
||||
impatient you might want to have a look at our [extensive example repository][exmaples]
|
||||
and run the included examples. Here for instance is how you run the included `basics`
|
||||
example:
|
||||
|
||||
```
|
||||
@ -51,3 +47,6 @@ git clone https://github.com/actix/examples
|
||||
cd examples/basics
|
||||
cargo run
|
||||
```
|
||||
|
||||
[rustguide]: https://doc.rust-lang.org/book/ch01-01-installation.html
|
||||
[examples]: https://github.com/actix/examples
|
||||
|
@ -19,12 +19,10 @@ Typically, middleware is involved in the following actions:
|
||||
* Modify application state
|
||||
* Access external services (redis, logging, sessions)
|
||||
|
||||
Middleware is registered for each application and executed in same order as
|
||||
registration. In general, a *middleware* is a type that implements the
|
||||
[*Service trait*](../../actix-web/actix_web/dev/trait.Service.html) and
|
||||
[*Transform trait*](../../actix-web/actix_web/dev/trait.Transform.html).
|
||||
Each method in the traits has a default implementation. Each method can return
|
||||
a result immediately or a *future* object.
|
||||
Middleware is registered for each application and executed in same 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:
|
||||
|
||||
@ -39,7 +37,7 @@ It is common to register a logging middleware as the first middleware for the ap
|
||||
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](https://docs.rs/env_logger/*/env_logger/)
|
||||
for *actix_web* package to see access log ([env_logger][envlogger]
|
||||
or similar).
|
||||
|
||||
## Usage
|
||||
@ -96,31 +94,30 @@ a specified header.
|
||||
|
||||
## User sessions
|
||||
|
||||
Actix provides a general solution for session management. The
|
||||
[**actix-session**](https://docs.rs/actix-session/0.1.1/actix_session/) middleware can be
|
||||
used with different backend types to store session data in different backends.
|
||||
Actix provides a general solution for session management. The [**actix-session**][actixsession]
|
||||
middleware can be used with different backend types to store session data in different backends.
|
||||
|
||||
> By default, only cookie session backend is implemented. Other backend implementations
|
||||
> can be added.
|
||||
|
||||
[**CookieSession**](../../actix-web/actix_web/middleware/session/struct.CookieSessionBackend.html)
|
||||
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.
|
||||
[**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 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.
|
||||
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.
|
||||
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,
|
||||
[*HttpRequest::session()*](../../actix-web/actix_web/middleware/session/trait.RequestSession.html#tymethod.session)
|
||||
must be used. This method returns a
|
||||
[*Session*](../../actix-web/actix_web/middleware/session/struct.Session.html) object, which allows us to get or set
|
||||
session data.
|
||||
In general, you create a `SessionStorage` middleware and initialize it with specific
|
||||
backend implementation, such as a `CookieSession`. To access session data,
|
||||
[*HttpRequest::session()*][requestsession] must be used. This method returns a
|
||||
[*Session*][sessionobj] object, which allows us to get or set session data.
|
||||
|
||||
{{< include-example example="middleware" file="user_sessions.rs" section="user-session" >}}
|
||||
|
||||
@ -134,3 +131,11 @@ one. The error handler can return a response immediately or return a future that
|
||||
into a response.
|
||||
|
||||
{{< include-example example="middleware" file="errorhandler.rs" section="error-handler" >}}
|
||||
|
||||
[sessionobj]: ../../actix-web/actix_web/middleware/session/struct.Session.html
|
||||
[requestsession]: ../../actix-web/actix_web/middleware/session/trait.RequestSession.html#tymethod.session
|
||||
[cookiesession]: ../../actix-web/actix_web/middleware/session/struct.CookieSessionBackend.html
|
||||
[actixsession]: https://docs.rs/actix-session/0.1.1/actix_session/
|
||||
[envlogger]: https://docs.rs/env_logger/*/env_logger/
|
||||
[servicetrait]: ../../actix-web/actix_web/dev/trait.Service.html
|
||||
[transformtrait]: ../../actix-web/actix_web/dev/trait.Transform.html
|
||||
|
@ -18,8 +18,7 @@ Actix automatically *decompresses* payloads. The following codecs are supported:
|
||||
* EncodingExt
|
||||
|
||||
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`.
|
||||
according to the header value. Multiple codecs are not supported, i.e: `Content-Encoding: br, gzip`.
|
||||
|
||||
# JSON Request
|
||||
|
||||
@ -39,8 +38,7 @@ body first and then deserialize the json into an object.
|
||||
|
||||
{{< include-example example="requests" file="manual.rs" section="json-manual" >}}
|
||||
|
||||
> A complete example for both options is available in
|
||||
> [examples directory](https://github.com/actix/examples/tree/master/json/).
|
||||
> A complete example for both options is available in [examples directory][examples].
|
||||
|
||||
# Chunked transfer encoding
|
||||
|
||||
@ -51,26 +49,22 @@ compression codecs (br, gzip, deflate), then the byte stream is decompressed.
|
||||
# Multipart body
|
||||
|
||||
Actix provides multipart stream support.
|
||||
[*Multipart*](../../actix-web/actix_web/multipart/struct.Multipart.html) is implemented as
|
||||
a stream of multipart items. Each item can be a
|
||||
[*Field*](../../actix-web/actix_web/multipart/struct.Field.html) or a nested
|
||||
*Multipart* stream.`HttpResponse::multipart()` returns the *Multipart* stream
|
||||
for the current request.
|
||||
[*Multipart*][multipartstruct] is implemented as a stream of multipart items. Each item
|
||||
can be a [*Field*][fieldstruct] or a nested *Multipart* stream.`HttpResponse::multipart()`
|
||||
returns the *Multipart* stream for the current request.
|
||||
|
||||
The following demonstrates multipart stream handling for a simple form:
|
||||
|
||||
{{< include-example example="requests" file="multipart.rs" section="multipart" >}}
|
||||
|
||||
> A full example is available in the
|
||||
> [examples directory](https://github.com/actix/examples/tree/master/multipart/).
|
||||
> A full example is available in the [examples directory][multipartexample].
|
||||
|
||||
# Urlencoded body
|
||||
|
||||
Actix provides support for *application/x-www-form-urlencoded* encoded bodies.
|
||||
`HttpResponse::urlencoded()` returns a
|
||||
[*UrlEncoded*](../../actix-web/actix_web/dev/struct.UrlEncoded.html) future, which resolves
|
||||
to the deserialized instance. The type of the instance must implement the
|
||||
`Deserialize` trait from *serde*.
|
||||
`HttpResponse::urlencoded()` returns a [*UrlEncoded*][urlencoder] future, 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:
|
||||
|
||||
@ -89,3 +83,9 @@ body payload.
|
||||
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]: ../../actix-web/actix_web/multipart/struct.Multipart.html
|
||||
[fieldstruct]: ../../actix-web/actix_web/multipart/struct.Field.html
|
||||
[multipartexample]: https://github.com/actix/examples/tree/master/multipart/
|
||||
[urlencoder]: ../../actix-web/actix_web/dev/struct.UrlEncoded.html
|
||||
|
@ -10,8 +10,7 @@ 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](../../actix-web/actix_web/dev/struct.HttpResponseBuilder.html)
|
||||
> for type descriptions.
|
||||
> 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
|
||||
@ -21,7 +20,7 @@ builder instance multiple times, the builder will panic.
|
||||
|
||||
# Content encoding
|
||||
|
||||
Actix automatically *compresses* payloads. The following codecs are supported:
|
||||
Actix-web automatically *compresses* payloads. The following codecs are supported:
|
||||
|
||||
* Brotli
|
||||
* Gzip
|
||||
@ -75,3 +74,5 @@ is enabled automatically.
|
||||
> Enabling chunked encoding for *HTTP/2.0* responses is forbidden.
|
||||
|
||||
{{< include-example example="responses" file="chunked.rs" section="chunked" >}}
|
||||
|
||||
[responsebuilder]: ../../actix-web/actix_web/dev/struct.HttpResponseBuilder.html
|
||||
|
@ -6,19 +6,18 @@ weight: 1020
|
||||
|
||||
# Sentry Crash Reporting
|
||||
|
||||
[Sentry](https://sentry.io/) is a crash reporting system that supports the
|
||||
failure crate which is the base of the actix error reporting. With a
|
||||
middleware it's possible to automatically report server errors to Sentry.
|
||||
[Sentry][sentrysite] is a crash reporting system that supports the failure crate which
|
||||
is the base of the actix error reporting. With a middleware it's possible to
|
||||
automatically report server errors to Sentry.
|
||||
|
||||
# Middleware
|
||||
|
||||
This middleware captures any error in the server error range (500 - 599)
|
||||
and sends the attached error to sentry with its stacktrace.
|
||||
|
||||
To use the middleware the [sentry crate](https://crates.io/crates/sentry) needs to be
|
||||
initialized and configured and the [sentry-actix middleware](https://crates.io/crates/sentry-actix)
|
||||
needs to be added. Additionally it makes sense to also register the panic handler
|
||||
to be informed about hard panics.
|
||||
To use the middleware the [sentry crate][sentrycrate] needs to be initialized and configured
|
||||
and the [sentry-actix middleware][sentrymiddleware] needs to be added. Additionally it
|
||||
makes sense to also register the panic handler to be informed about hard panics.
|
||||
|
||||
{{< include-example example="sentry" file="main.rs" section="middleware" >}}
|
||||
|
||||
@ -33,3 +32,7 @@ The hub can also be made current for the duration of a call. Then `Hub::current
|
||||
until the end of the `run` block.
|
||||
|
||||
{{< include-example example="sentry" file="main.rs" section="hub2" >}}
|
||||
|
||||
[sentrysite]: https://sentry.io/
|
||||
[sentrycrate]: https://crates.io/crates/sentry
|
||||
[sentrymiddleware]: https://crates.io/crates/sentry-actix
|
||||
|
@ -6,22 +6,17 @@ weight: 150
|
||||
|
||||
# The HTTP Server
|
||||
|
||||
The [**HttpServer**](https://docs.rs/actix-web/1.0.2/actix_web/struct.HttpServer.html) type is responsible for
|
||||
serving http requests.
|
||||
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.
|
||||
`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 bind to a specific socket address,
|
||||
[`bind()`](../../actix-web/actix_web/server/struct.HttpServer.html#method.bind)
|
||||
must be used, and it may be called multiple times. To bind ssl socket,
|
||||
[`bind_ssl()`](../../actix-web/actix_web/server/struct.HttpServer.html#method.bind_ssl)
|
||||
or [`bind_rustls()`](../../actix-web/1.0.0/actix_web/struct.HttpServer.html#method.bind_rustls)
|
||||
should be used. To start the http server, use one of the start methods.
|
||||
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
|
||||
[`bind_rustls()`][bindrusttls] should be used. To start the http server, use one of the
|
||||
start methods.
|
||||
|
||||
- use [`start()`](../../actix-web/actix_web/server/struct.HttpServer.html#method.start)
|
||||
for a server
|
||||
- use [`start()`] for a server
|
||||
|
||||
{{< include-example example="server" section="main" >}}
|
||||
|
||||
@ -30,8 +25,8 @@ for a server
|
||||
> this server, send a `StopServer` message.
|
||||
|
||||
`HttpServer` is implemented as an actix actor. It is possible to communicate with the server
|
||||
via a messaging system. Start method, e.g. `start()`, returns the
|
||||
address of the started http server. It accepts several messages:
|
||||
via a messaging system. Start method, e.g. `start()`, returns the address of the started
|
||||
http server. It accepts several messages:
|
||||
|
||||
- `PauseServer` - Pause accepting incoming connections
|
||||
- `ResumeServer` - Resume accepting incoming connections
|
||||
@ -41,18 +36,16 @@ address of the started http server. It accepts several messages:
|
||||
|
||||
## Multi-threading
|
||||
|
||||
`HttpServer` automatically starts a number of http workers, by default
|
||||
this number is equal to number of logical CPUs in the system. This number
|
||||
can be overridden with the
|
||||
[`HttpServer::workers()`](../../actix-web/actix_web/server/struct.HttpServer.html#method.workers) method.
|
||||
`HttpServer` automatically starts a number of http workers, by default this number is
|
||||
equal to number of logical CPUs in the system. This number can be overridden with the
|
||||
[`HttpServer::workers()`][workers] method.
|
||||
|
||||
{{< include-example example="server" file="workers.rs" section="workers" >}}
|
||||
|
||||
The server creates a separate application instance for each created worker. Application state
|
||||
is not shared between threads. To share state, `Arc` could be used.
|
||||
|
||||
> Application state does not need to be `Send` and `Sync`,
|
||||
> but factories must be `Send` + `Sync`.
|
||||
> Application state does not need to be `Send` and `Sync`, but factories must be `Send` + `Sync`.
|
||||
|
||||
## SSL
|
||||
|
||||
@ -66,18 +59,16 @@ actix-web = { version = "{{< actix-version "actix-web" >}}", features = ["ssl"]
|
||||
|
||||
{{< include-example example="server" file="ssl.rs" section="ssl" >}}
|
||||
|
||||
> **Note**: the *HTTP/2.0* protocol requires
|
||||
> [tls alpn](https://tools.ietf.org/html/rfc7301).
|
||||
> **Note**: the *HTTP/2.0* protocol requires [tls alpn][tlsalpn].
|
||||
> At the moment, only `openssl` has `alpn` support.
|
||||
> For a full example, check out
|
||||
> [examples/tls](https://github.com/actix/examples/tree/master/tls).
|
||||
> For a full example, check out [examples/tls][exampletls].
|
||||
|
||||
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
|
||||
To remove the password, then copy nopass.pem to key.pem
|
||||
```bash
|
||||
$ openssl rsa -in key.pem -out nopass.pem
|
||||
```
|
||||
@ -94,10 +85,9 @@ Actix can wait for requests on a keep-alive connection.
|
||||
|
||||
{{< include-example example="server" file="keep_alive.rs" section="keep-alive" >}}
|
||||
|
||||
If the first option is selected, then *keep alive* state is
|
||||
calculated based on the response's *connection-type*. By default
|
||||
`HttpResponse::connection_type` is not defined. In that case *keep alive* is
|
||||
defined by the request's http version.
|
||||
If the first option is selected, then *keep alive* state is calculated based on the
|
||||
response's *connection-type*. By default `HttpResponse::connection_type` is not
|
||||
defined. In that case *keep alive* is defined by the request's http version.
|
||||
|
||||
> *keep alive* is **off** for *HTTP/1.0* and is **on** for *HTTP/1.1* and *HTTP/2.0*.
|
||||
|
||||
@ -109,22 +99,30 @@ defined by the request's http version.
|
||||
|
||||
`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()`](../../actix-web/actix_web/server/struct.HttpServer.html#method.shutdown_timeout) method.
|
||||
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.
|
||||
|
||||
You can send a stop message to the server with the server address and specify if you want
|
||||
graceful shutdown or not. The
|
||||
[`start()`](../../actix-web/actix_web/server/struct.HttpServer.html#method.start)
|
||||
method returns address of the server.
|
||||
graceful shutdown or not. The [`start()`][startmethod] method returns address of the server.
|
||||
|
||||
`HttpServer` handles several OS signals. *CTRL-C* is available on all OSs,
|
||||
other signals are available on unix systems.
|
||||
`HttpServer` handles several OS signals. *CTRL-C* is available on all OSs, 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()`](../../actix-web/actix_web/server/struct.HttpServer.html#method.disable_signals)
|
||||
> method.
|
||||
[`HttpServer::disable_signals()`][disablesignals] method.
|
||||
|
||||
[httpserverstruct]: https://docs.rs/actix-web/1.0.2/actix_web/struct.HttpServer.html
|
||||
[bindmethod]: ../../actix-web/actix_web/server/struct.HttpServer.html#method.bind
|
||||
[bindsslmethod]: ../../actix-web/actix_web/server/struct.HttpServer.html#method.bind_ssl
|
||||
[bindrusttls]: ../../actix-web/1.0.0/actix_web/struct.HttpServer.html#method.bind_rustls
|
||||
[startmethod]: ../../actix-web/actix_web/server/struct.HttpServer.html#method.start
|
||||
[workers]: ../../actix-web/actix_web/server/struct.HttpServer.html#method.workers
|
||||
[tlsalpn]: https://tools.ietf.org/html/rfc7301
|
||||
[exampletls]: https://github.com/actix/examples/tree/master/tls
|
||||
[shutdowntimeout]: ../../actix-web/actix_web/server/struct.HttpServer.html#method.shutdown_timeout
|
||||
[disablesignals]: (../../actix-web/actix_web/server/struct.HttpServer.html#method.disable_signals)
|
||||
|
@ -21,13 +21,11 @@ it will be unable to serve sub-paths.
|
||||
|
||||
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()*](https://docs.rs/actix-files/0.1.2/actix_files/struct.Files.html)
|
||||
[*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()*](https://docs.rs/actix-files/0.1.2/actix_files/struct.Files.html#method.index_file)
|
||||
method to configure this redirect.
|
||||
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
|
||||
|
||||
@ -47,3 +45,6 @@ But it is possible to customize any of them by implementing the trait onto own s
|
||||
The Configuration cal 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
|
||||
|
@ -12,9 +12,8 @@ integration tests.
|
||||
# Unit Tests
|
||||
|
||||
For unit testing, actix-web provides a request builder type and a simple handler runner.
|
||||
[*TestRequest*](https://docs.rs/actix-web/1.0.2/actix_web/test/struct.TestRequest.html)
|
||||
implements a builder-like pattern.
|
||||
You can generate a `HttpRequest` instance with `to_http_request()`, or you can
|
||||
[*TestRequest*][testrequest] implements a builder-like pattern. You can generate a
|
||||
`HttpRequest` instance with `to_http_request()`, or you can
|
||||
run your handler with `block_on()`.
|
||||
|
||||
{{< include-example example="testing" file="main.rs" section="unit-tests" >}}
|
||||
@ -30,8 +29,7 @@ methods can be used to send requests to the test server.
|
||||
To create a `Service` for testing, use the `test::init_serivce` method which accepts a
|
||||
regular `App` builder.
|
||||
|
||||
> Check the [api documentation](https://docs.rs/actix-web/1.0.2/actix_web/test/index.html)
|
||||
> for more information.
|
||||
> Check the [api documentation][actixdocs] for more information.
|
||||
|
||||
{{< include-example example="testing" file="integration_one.rs" section="integration-one" >}}
|
||||
|
||||
@ -43,10 +41,13 @@ the normal application. For example, you may need to initialize application stat
|
||||
|
||||
# Stream response tests
|
||||
|
||||
If you need to test stream it would be enough to convert a
|
||||
[*ClientResponse*](../../actix-web/actix_web/client/struct.ClientResponse.html) to future
|
||||
and execute it.
|
||||
For example of testing
|
||||
[*Server Sent Events*](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events).
|
||||
If you need to test stream it would be enough to convert a [*ClientResponse*][clientresponse]
|
||||
to future and execute it.
|
||||
For example of testing [*Server Sent Events*][serversentevents].
|
||||
|
||||
{{< include-example 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
|
||||
[clientresponse]: ../../actix-web/actix_web/client/struct.ClientResponse.html
|
||||
[actixdocs]: (https://docs.rs/actix-web/1.0.2/actix_web/test/index.html)
|
||||
[testrequest]: https://docs.rs/actix-web/1.0.2/actix_web/error/trait.ResponseError.html#foreign-impls
|
||||
|
@ -10,31 +10,29 @@ URL dispatch provides a simple way for mapping URLs to handler code using a simp
|
||||
matching language. If one of the patterns matches the path information associated with a request,
|
||||
a particular handler object is invoked.
|
||||
|
||||
> A handler is a specific object that implements the
|
||||
> `Handler` trait, defined in your application, that receives the request and returns
|
||||
> a response object. More information is available in the
|
||||
> [handler section](sec-4-handler.html).
|
||||
> A handler is a specific object that implements the `Handler` trait, defined in your
|
||||
> application, that receives the request and returns a response object. More information
|
||||
> is available in the [handler section][sec4handler].
|
||||
|
||||
# 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*).
|
||||
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()*](../../actix-web/actix_web/struct.App.html#method.route) method provides
|
||||
simple way of registering routes. This method adds a single route to application
|
||||
routing table. This method accepts a *path pattern*,
|
||||
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.
|
||||
|
||||
{{< include-example 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::resource()*](../../actix-web/actix_web/struct.App.html#method.resource) method
|
||||
While *App::route()* provides simple way of registering routes, to access complete resource
|
||||
configuration, a different method has to be used. The [*App::resource()*][appresource] method
|
||||
adds a single resource to application routing table. This method accepts a *path pattern*
|
||||
and a resource configuration function.
|
||||
|
||||
@ -71,24 +69,19 @@ and path equals to `/path`, Resource calls handle of the first matching route.
|
||||
|
||||
If a resource can not match any route, a "NOT FOUND" response is returned.
|
||||
|
||||
[*ResourceHandler::route()*](../../actix-web/actix_web/dev/struct.ResourceHandler.html#method.route) returns a
|
||||
[*Route*](../../actix-web/actix_web/dev/struct.Route.html) object. Route can be configured with a
|
||||
builder-like pattern. Following configuration methods are available:
|
||||
[*ResourceHandler::route()*][resourcehandler] returns a [*Route*][route] object. Route
|
||||
can be configured with a builder-like pattern. Following configuration methods are available:
|
||||
|
||||
* [*Route::guard()*](../../actix-web/actix_web/dev/struct.Route.html#method.guard)
|
||||
registers a new guard. Any number of guards can be registered for each route.
|
||||
* [*Route::method()*](../../actix-web/actix_web/dev/struct.Route.html#method.method)
|
||||
registers a method guard. Any number of guards can be registered for each route.
|
||||
* [*Route::to()*](../../actix-web/actix_web/dev/struct.Route.html#method.to) registers
|
||||
handler function for this route. Only one handler can be registered.
|
||||
Usually handler registration
|
||||
is the last config operation. Handler function can be a function or closure
|
||||
and has the type
|
||||
`Fn(HttpRequest<S>) -> R + 'static`
|
||||
* [*Route::to_async()*](../../actix-web/actix_web/dev/struct.Route.html#method.to_async) registers
|
||||
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
|
||||
* [*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 handler function for this route. Only one handler
|
||||
can be registered. Usually handler registration is the last config operation. Handler
|
||||
function can be a function or closure and has the type `Fn(HttpRequest<S>) -> R + 'static`
|
||||
* [*Route::to_async()*][routetoasync] registers 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<S>) -> Future<Item = HttpResponse, Error = Error> + 'static`
|
||||
|
||||
# Route matching
|
||||
@ -272,10 +265,8 @@ You can get variable path segments from `HttpRequest::match_info()`.
|
||||
|
||||
# Match information
|
||||
|
||||
All values representing matched path segments are available in
|
||||
[`HttpRequest::match_info`](../actix_web/struct.HttpRequest.html#method.match_info).
|
||||
Specific values can be retrieved with
|
||||
[`Params::get()`](../actix_web/dev/struct.Params.html#method.get).
|
||||
All values representing matched path segments are available in [`HttpRequest::match_info`][matchinfo].
|
||||
Specific values can be retrieved with [`Params::get()`][paramsget].
|
||||
|
||||
{{< include-example example="url-dispatch" file="minfo.rs" section="minfo" >}}
|
||||
|
||||
@ -301,13 +292,11 @@ safe to interpolate within, or use as a suffix of, a path without additional che
|
||||
|
||||
## Path information extractor
|
||||
|
||||
Actix provides functionality for type safe path information extraction.
|
||||
[*Path*](../../actix-web/actix_web/struct.Path.html) extracts information, destination type
|
||||
could be defined in several different forms. Simplest approach is to use
|
||||
`tuple` type. Each element in tuple must correpond to one element from
|
||||
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 correpond 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.
|
||||
`Path<(u32, String)>` type, but `Path<(String, String, String)>` type will always fail.
|
||||
|
||||
{{< include-example example="url-dispatch" file="path.rs" section="path" >}}
|
||||
|
||||
@ -316,21 +305,19 @@ this struct must implement *serde's *`Deserialize` trait.
|
||||
|
||||
{{< include-example example="url-dispatch" file="path2.rs" section="path" >}}
|
||||
|
||||
[*Query*](../../actix-web/actix_web/struct.Query.html) provides similar
|
||||
functionality for request query parameters.
|
||||
[*Query*][query] provides similar functionality for request query parameters.
|
||||
|
||||
# Generating resource URLs
|
||||
|
||||
Use the [*HttpRequest.url_for()*](../../actix-web/actix_web/struct.HttpRequest.html#method.url_for)
|
||||
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:
|
||||
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:
|
||||
|
||||
{{< include-example 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*](https://docs.rs/url/1.7.0/url/struct.Url.html) so you
|
||||
can modify this url (add query parameters, anchor, etc).
|
||||
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
|
||||
@ -347,14 +334,13 @@ 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.
|
||||
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.
|
||||
|
||||
If *append* is *true*, append slash when needed. If a resource is
|
||||
defined with trailing slash and the request doesn't have one, it will
|
||||
be appended automatically.
|
||||
If *append* is *true*, append slash when needed. If a resource is defined with trailing
|
||||
slash and the request doesn't have one, it will be appended automatically.
|
||||
|
||||
If *merge* is *true*, merge multiple consecutive slashes in the path into one.
|
||||
|
||||
@ -375,11 +361,10 @@ It is possible to register path normalization only for *GET* requests only:
|
||||
|
||||
## 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.
|
||||
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:
|
||||
|
||||
@ -395,9 +380,8 @@ it will generate a URL with that same path.
|
||||
|
||||
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`](../actix_web/guard/trait.Guard.html) trait. Actix provides
|
||||
several predicates, you can check
|
||||
[functions section](../../actix-web/actix_web/guard/index.html#functions) of api docs.
|
||||
[`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*:
|
||||
|
||||
@ -405,9 +389,8 @@ Here is a simple guard that check that a request contains a specific *header*:
|
||||
|
||||
In this example, *index* handler will be called only if request contains *CONTENT-TYPE* header.
|
||||
|
||||
Guards have access to the application's state via `HttpRequest::data()`.
|
||||
Also predicates can store extra information in
|
||||
[request extensions](../../actix-web/actix_web/struct.HttpRequest.html#method.extensions).
|
||||
Guards have access to the application's state via `HttpRequest::data()`. Also predicates
|
||||
can store extra information in [request extensions][httprequest].
|
||||
|
||||
## Modifying guard values
|
||||
|
||||
@ -440,3 +423,22 @@ This method accepts a *configuration function* same as normal resource configura
|
||||
with `App::service()` method.
|
||||
|
||||
{{< include-example example="url-dispatch" file="dhandler.rs" section="default" >}}
|
||||
|
||||
[sec4handler]: sec-4-handler.html
|
||||
[approute]: ../../actix-web/actix_web/struct.App.html#method.route
|
||||
[appresource]: ../../actix-web/actix_web/struct.App.html#method.resource
|
||||
[resourcehandler]: ../../actix-web/actix_web/dev/struct.ResourceHandler.html#method.route
|
||||
[route]: ../../actix-web/actix_web/dev/struct.Route.html
|
||||
[routeguard]: ../../actix-web/actix_web/dev/struct.Route.html#method.guard
|
||||
[routemethod]: ../../actix-web/actix_web/dev/struct.Route.html#method.method
|
||||
[routeto]: ../../actix-web/actix_web/dev/struct.Route.html#method.to
|
||||
[routetoasync]: ../../actix-web/actix_web/dev/struct.Route.html#method.to_async
|
||||
[matchinfo]: ../actix_web/struct.HttpRequest.html#method.match_info
|
||||
[paramsget]: ../actix_web/dev/struct.Params.html#method.get
|
||||
[pathstruct]: ../../actix-web/actix_web/struct.Path.html
|
||||
[query]: ../../actix-web/actix_web/struct.Query.html
|
||||
[urlfor]: ../../actix-web/actix_web/struct.HttpRequest.html#method.url_for
|
||||
[urlobj]: https://docs.rs/url/1.7.0/url/struct.Url.html
|
||||
[guardtrait]: ../actix_web/guard/trait.Guard.html
|
||||
[guardfuncs]: ../../actix-web/actix_web/guard/index.html#functions
|
||||
[httprequest]: ../../actix-web/actix_web/struct.HttpRequest.html#method.extensions
|
||||
|
@ -5,8 +5,7 @@ weight: 240
|
||||
---
|
||||
|
||||
Actix supports WebSockets out-of-the-box. It is possible to convert a request's `Payload`
|
||||
to a stream of [*ws::Message*](../../actix-web/actix_web/ws/enum.Message.html) with
|
||||
a [*ws::WsStream*](../../actix-web/actix_web/ws/struct.WsStream.html) and then use stream
|
||||
to a stream of [*ws::Message*][message] with a [*ws::WsStream*][wsstream] and then use stream
|
||||
combinators to handle actual messages, but it is simpler to handle websocket communications
|
||||
with an http actor.
|
||||
|
||||
@ -14,8 +13,12 @@ The following is an example of a simple websocket echo server:
|
||||
|
||||
{{< include-example example="websockets" file="main.rs" section="websockets" >}}
|
||||
|
||||
> A simple websocket echo server example is available in the
|
||||
> [examples directory](https://github.com/actix/examples/tree/master/websocket/).
|
||||
> 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](https://github.com/actix/examples/tree/master/websocket-chat/)
|
||||
> is available in [websocket-chat directory][chat]
|
||||
|
||||
[message]: ../../actix-web/actix_web/ws/enum.Message.html
|
||||
[wsstream]: ../../actix-web/actix_web/ws/struct.WsStream.html
|
||||
[examples]: https://github.com/actix/examples/tree/master/websocket/
|
||||
[chat]: https://github.com/actix/examples/tree/master/websocket-chat/
|
||||
|
Loading…
Reference in New Issue
Block a user