mirror of
https://github.com/actix/actix-website
synced 2025-02-20 03:14:22 +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
|
Actix is your door to developing web services with Rust and this documentation
|
||||||
is going to guide you.
|
is going to guide you.
|
||||||
|
|
||||||
This documentation currently covers mostly the `actix-web` part which is the
|
This documentation currently covers mostly the `actix-web` part which is the high level
|
||||||
high level web framework previously built on top of the `actix` actor framework and the
|
web framework previously built on top of the `actix` actor framework and the [Tokio][tokio]
|
||||||
[Tokio](https://tokio.rs/) async IO system. This is the part that is from an
|
async IO system. This is the part that is from an API stability point of view the most stable.
|
||||||
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
|
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
|
guide][gettingstarted]. If you already know your ways around and you need
|
||||||
specific information you might want to read the [actix-web API
|
specific information you might want to read the [actix-web API docs][actixwebdocs]
|
||||||
docs](https://docs.rs/actix-web) (or the lower level [actix API
|
(or the lower level [actix API docs][actixdocs]).
|
||||||
docs](https://docs.rs/actix)).
|
|
||||||
|
[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
|
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.
|
are created. This resource is available through the `/app/index.html` url.
|
||||||
|
|
||||||
> For more information, check the
|
> For more information, check the [URL Dispatch][usingappprefix] section.
|
||||||
> [URL Dispatch](/docs/url-dispatch/index.html#using-an-application-prefix-to-compose-applications) section.
|
|
||||||
|
|
||||||
Multiple application scopes can be served with one server:
|
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
|
> instance. `HttpServer` constructs an application instance for each thread, thus
|
||||||
> application state must be constructed multiple times. If you want to share state between
|
> 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
|
> 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`
|
> [Example][stateexample] using `Arc` for this. Application state does not need to be
|
||||||
> for this. Application state does not need to be `Send` and `Sync`,
|
> `Send` and `Sync`, but the application factory must be `Send` + `Sync`.
|
||||||
> but the application factory must be `Send` + `Sync`.
|
|
||||||
|
|
||||||
To start the previous app, create it into a closure:
|
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
|
## Using an Application Scope to Compose Applications
|
||||||
|
|
||||||
The `web::scope()` method allows to set a specific application prefix.
|
The `web::scope()` method allows to set a specific application prefix. This scope represents
|
||||||
This scope represents a resource prefix that will be prepended to all resource patterns added
|
a resource prefix that will be prepended to all resource patterns added by the resource
|
||||||
by the resource configuration. This can be used to help mount a set of routes at a different
|
configuration. This can be used to help mount a set of routes at a different location
|
||||||
location than the included callable's author intended while still maintaining the same
|
than the included callable's author intended while still maintaining the same resource names.
|
||||||
resource names.
|
|
||||||
|
|
||||||
For example:
|
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
|
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
|
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
|
[`Guard`][guardtrait] trait. Actix-web provides several guards, you can check
|
||||||
provides several guards, you can check
|
[functions section][guardfuncs] of api docs.
|
||||||
[functions section](https://docs.rs/actix-web/1.0.2/actix_web/guard/index.html#functions)
|
|
||||||
of api docs.
|
|
||||||
|
|
||||||
One of the provided guards is [`Header`](https://docs.rs/actix-web/1.0.2/actix_web/guard/fn.Header.html),
|
One of the provided guards is [`Header`][guardheader], it can be used as application's
|
||||||
it can be used as application's filter based on request's header information.
|
filter based on request's header information.
|
||||||
|
|
||||||
{{< include-example example="application" file="vh.rs" section="vh" >}}
|
{{< 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`
|
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
|
# Auto-Reloading Development Server
|
||||||
|
|
||||||
During development it can be very handy to have cargo automatically recompile
|
During development it can be very handy to have cargo automatically recompile the code
|
||||||
the code on change. This can be accomplished by using
|
on change. This can be accomplished by using [cargo-watch][cargowatch]. Because an
|
||||||
[cargo-watch](https://github.com/passcod/cargo-watch). Because an actix app
|
actix app will typically bind to a port for listening for incoming HTTP requests it makes
|
||||||
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]
|
||||||
sense to combine this with the [listenfd](https://crates.io/crates/listenfd)
|
utility to ensure the socket is kept open while the app is compiling and reloading.
|
||||||
crate and the [systemfd](https://github.com/mitsuhiko/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
|
`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
|
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
|
## Code Changes
|
||||||
|
|
||||||
Additionally you need to slightly modify your actix app so that it can pick up
|
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
|
an external socket opened by `systemfd`. Add the listenfd dependency to your app:
|
||||||
app:
|
|
||||||
|
|
||||||
```ini
|
```ini
|
||||||
[dependencies]
|
[dependencies]
|
||||||
@ -49,3 +46,7 @@ To now run the development server invoke this command:
|
|||||||
```
|
```
|
||||||
systemfd --no-pid -s http::3000 -- cargo watch -x run
|
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" >}}
|
{{< include-example example="og_databases" file="main.rs" section="index" >}}
|
||||||
|
|
||||||
> A full example is available in the
|
> A full example is available in the [examples directory][examples].
|
||||||
> [examples directory](https://github.com/actix/examples/tree/master/diesel/).
|
|
||||||
|
|
||||||
> More information on sync actors can be found in the
|
> 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
|
||||||
|
|
||||||
[*Path*](https://docs.rs/actix-web/1.0.2/actix_web/dev/struct.Path.html) provides
|
[*Path*][pathstruct] provides information that can be extracted from the Request's
|
||||||
information that can be extracted from the Request's path. You can deserialize any
|
path. You can deserialize any variable segment from the path.
|
||||||
variable segment from the path.
|
|
||||||
|
|
||||||
For instance, for resource that registered for the `/users/{userid}/{friend}` path
|
For instance, for resource that registered for the `/users/{userid}/{friend}` path
|
||||||
two segments could be deserialized, `userid` and `friend`. These segments
|
two segments could be deserialized, `userid` and `friend`. These segments could be
|
||||||
could be extracted into a `tuple`, i.e. `Path<(u32, String)>` or any structure
|
extracted into a `tuple`, i.e. `Path<(u32, String)>` or any structure that implements
|
||||||
that implements the `Deserialize` trait from the *serde* crate.
|
the `Deserialize` trait from the *serde* crate.
|
||||||
|
|
||||||
{{< include-example example="extractors" file="path_one.rs" section="path-one" >}}
|
{{< include-example example="extractors" file="path_one.rs" section="path-one" >}}
|
||||||
|
|
||||||
It is also possible to extract path information to a specific type that
|
It is also possible to extract path information to a specific type that implements the
|
||||||
implements the `Deserialize` trait from *serde*. Here is an equivalent example that uses *serde*
|
`Deserialize` trait from *serde*. Here is an equivalent example that uses *serde*
|
||||||
instead of a *tuple* type.
|
instead of a *tuple* type.
|
||||||
|
|
||||||
{{< include-example example="extractors" file="path_two.rs" section="path-two" >}}
|
{{< 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
|
# Query
|
||||||
|
|
||||||
The [*Query*](https://docs.rs/actix-web/1.0.2/actix_web/web/struct.Query.html)
|
The [*Query*][querystruct] type provides extraction functionality for the request's
|
||||||
type provides extraction functionality for the request's query parameters. Underneath it
|
query parameters. Underneath it uses *serde_urlencoded* crate.
|
||||||
uses *serde_urlencoded* crate.
|
|
||||||
|
|
||||||
{{< include-example example="extractors" file="query.rs" section="query" >}}
|
{{< include-example example="extractors" file="query.rs" section="query" >}}
|
||||||
|
|
||||||
# Json
|
# Json
|
||||||
|
|
||||||
[*Json*](https://docs.rs/actix-web/1.0.2/actix_web/web/struct.Json.html) allows to deserialize
|
[*Json*][jsonstruct] allows to deserialize a request body into a struct. To extract
|
||||||
a request body into a struct. To extract typed information from a request's body,
|
typed information from a request's body, the type `T` must implement the `Deserialize`
|
||||||
the type `T` must implement the `Deserialize` trait from *serde*.
|
trait from *serde*.
|
||||||
|
|
||||||
{{< include-example example="extractors" file="json_one.rs" section="json-one" >}}
|
{{< include-example example="extractors" file="json_one.rs" section="json-one" >}}
|
||||||
|
|
||||||
Some extractors provide a way to configure the extraction process. Json extractor
|
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
|
[*JsonConfig*][jsonconfig] type for configuration. To configure an extractor, pass it's
|
||||||
for configuration. To configure an extractor, pass it's configuration object to the resource's
|
configuration object to the resource's `.data()` method. In case of a *Json* extractor
|
||||||
`.data()` method. In case of a *Json* extractor it returns a *JsonConfig*. You can
|
it returns a *JsonConfig*. You can configure the maximum size of the json payload as
|
||||||
configure the maximum size of the json payload as well as a custom error handler function.
|
well as a custom error handler function.
|
||||||
|
|
||||||
The following example limits the size of the payload to 4kb and uses a custom error handler.
|
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
|
# Form
|
||||||
|
|
||||||
At the moment only url-encoded forms are supported. The url-encoded body
|
At the moment only url-encoded forms are supported. The url-encoded body could be
|
||||||
could be extracted to a specific type. This type must implement
|
extracted to a specific type. This type must implement the `Deserialize` trait from
|
||||||
the `Deserialize` trait from the *serde* crate.
|
the *serde* crate.
|
||||||
|
|
||||||
[*FormConfig*](https://docs.rs/actix-web/1.0.2/actix_web/web/struct.FormConfig.html) allows
|
[*FormConfig*][formconfig] allows configuring the extraction process.
|
||||||
configuring the extraction process.
|
|
||||||
|
|
||||||
{{< include-example example="extractors" file="form.rs" section="form" >}}
|
{{< include-example example="extractors" file="form.rs" section="form" >}}
|
||||||
|
|
||||||
# Multiple extractors
|
# Multiple extractors
|
||||||
|
|
||||||
Actix-web provides extractor implementations for tuples (up to 10 elements)
|
Actix-web provides extractor implementations for tuples (up to 10 elements) whose
|
||||||
whose elements implement `FromRequest`.
|
elements implement `FromRequest`.
|
||||||
|
|
||||||
For example we can use a path extractor and a query extractor at the same time.
|
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:
|
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
|
* [*Data*][datastruct] - If you need access to an application state.
|
||||||
access to an application state.
|
* *HttpRequest* - *HttpRequest* itself is an extractor which returns self, in case you
|
||||||
* *HttpRequest* - *HttpRequest* itself is an extractor which returns self,
|
need access to the request.
|
||||||
in case you need access to the request.
|
* *String* - You can convert a request's payload to a *String*. [*Example*][stringexample]
|
||||||
* *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)
|
|
||||||
is available in doc strings.
|
is available in doc strings.
|
||||||
* *bytes::Bytes* - You can convert a request's payload into *Bytes*.
|
* *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.
|
is available in doc strings.
|
||||||
* *Payload* - You can access a request's payload.
|
* *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
|
# 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
|
> Be careful with synchronization primitives like `Mutex` or `RwLock`. The `actix-web` framework
|
||||||
> handles requests asynchronously. By blocking thread execution, all concurrent
|
> handles requests asynchronously. By blocking thread execution, all concurrent
|
||||||
> request handling processes would block. If you need to share or update some state
|
> request handling processes would block. If you need to share or update some state
|
||||||
> from multiple threads, consider using the [actix](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
|
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
|
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
|
# Request Handlers
|
||||||
|
|
||||||
A request handler is a function that accepts zero or more parameters that can be extracted
|
A request handler is a function that accepts zero or more parameters that can be extracted
|
||||||
from a request (ie,
|
from a request (ie, [*impl FromRequest*][implfromrequest]) and returns a type that can
|
||||||
[*impl FromRequest*](https://docs.rs/actix-web/1.0.2/actix_web/trait.FromRequest.html))
|
be converted into an HttpResponse (ie, [*impl Responder*][implresponder]).
|
||||||
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)).
|
|
||||||
|
|
||||||
Request handling happens in two stages. First the handler object is called,
|
Request handling happens in two stages. First the handler object is called, returning any
|
||||||
returning any object that implements the
|
object that implements the [*Responder*][respondertrait] trait. Then, `respond_to()` is
|
||||||
[*Responder*](https://docs.rs/actix-web/1.0.2/actix_web/trait.Responder.html) trait.
|
called on the returned object, converting itself to a `HttpResponse` or `Error`.
|
||||||
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.
|
such as `&'static str`, `String`, etc.
|
||||||
|
|
||||||
> For a complete list of implementations, check
|
> For a complete list of implementations, check [*Responder documentation*][responderimpls].
|
||||||
> [*Responder documentation*](../../actix-web/actix_web/trait.Responder.html#foreign-impls).
|
|
||||||
|
|
||||||
Examples of valid handlers:
|
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
|
## Async handlers
|
||||||
|
|
||||||
There are two different types of async handlers. Response objects can be generated asynchronously
|
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:
|
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" >}}
|
{{< include-example example="async-handlers" file="main.rs" section="async-responder" >}}
|
||||||
|
|
||||||
Or the response body can be generated asynchronously. In this case, body
|
Or the response body can be generated asynchronously. In this case, body must implement
|
||||||
must implement the stream trait `Stream<Item=Bytes, Error=Error>`, i.e:
|
the stream trait `Stream<Item=Bytes, Error=Error>`, i.e:
|
||||||
|
|
||||||
{{< include-example example="async-handlers" file="stream.rs" section="stream" >}}
|
{{< include-example example="async-handlers" file="stream.rs" section="stream" >}}
|
||||||
|
|
||||||
Both methods can be combined. (i.e Async response with streaming body)
|
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`.
|
It is possible to return a `Result` where the `Result::Item` type can be `Future`. In
|
||||||
In this example, the `index` handler can return an error immediately or return a
|
this example, the `index` handler can return an error immediately or return a future
|
||||||
future that resolves to a `HttpResponse`.
|
that resolves to a `HttpResponse`.
|
||||||
|
|
||||||
{{< include-example example="async-handlers" file="async_stream.rs" section="async-stream" >}}
|
{{< include-example example="async-handlers" file="async_stream.rs" section="async-stream" >}}
|
||||||
|
|
||||||
## Different return types (Either)
|
## Different return types (Either)
|
||||||
|
|
||||||
Sometimes, you need to return different types of responses. For example,
|
Sometimes, you need to return different types of responses. For example, you can error
|
||||||
you can error check and return errors, return async responses, or any result that requires two different types.
|
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.
|
For this case, the [*Either*][either] type can be used. `Either` allows combining two
|
||||||
`Either` allows combining two different responder types into a single type.
|
different responder types into a single type.
|
||||||
|
|
||||||
{{< include-example example="either" file="main.rs" section="either" >}}
|
{{< 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
|
# Negotiation
|
||||||
|
|
||||||
*HTTP/2.0* protocol over tls without prior knowledge requires
|
*HTTP/2.0* protocol over tls without prior knowledge requires [tls alpn][tlsalpn].
|
||||||
[tls alpn](https://tools.ietf.org/html/rfc7301).
|
|
||||||
|
|
||||||
> Currently, only `rust-openssl` has support.
|
> Currently, only `rust-openssl` has support.
|
||||||
|
|
||||||
`alpn` negotiation requires enabling the feature. When enabled, `HttpServer` provides the
|
`alpn` negotiation requires enabling the feature. When enabled, `HttpServer` provides the
|
||||||
[bind_ssl](../../actix-web/actix_web/server/struct.HttpServer.html#method.serve_tls) method.
|
[bind_ssl][bindssl] method.
|
||||||
|
|
||||||
```toml
|
```toml
|
||||||
[dependencies]
|
[dependencies]
|
||||||
@ -23,10 +22,14 @@ openssl = { version = "0.10", features = ["v110"] }
|
|||||||
```
|
```
|
||||||
{{< include-example example="http2" file="main.rs" section="main" >}}
|
{{< include-example example="http2" file="main.rs" section="main" >}}
|
||||||
|
|
||||||
Upgrades to *HTTP/2.0* schema described in
|
Upgrades to *HTTP/2.0* schema described in [rfc section 3.2][rfcsection32] is not
|
||||||
[rfc section 3.2](https://http2.github.io/http2-spec/#rfc.section.3.2) is not supported.
|
supported. Starting *HTTP/2* with prior knowledge is supported for both clear text
|
||||||
Starting *HTTP/2* with prior knowledge is supported for both clear text connection
|
connection and tls connection. [rfc section 3.4][rfcsection34].
|
||||||
and tls connection. [rfc section 3.4](https://http2.github.io/http2-spec/#rfc.section.3.4)
|
|
||||||
|
|
||||||
> Check out [examples/tls](https://github.com/actix/examples/tree/master/tls)
|
> Check out [examples/tls][examples] for a concrete example.
|
||||||
> 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
|
# Installing Rust
|
||||||
|
|
||||||
Since `actix-web` is a Rust framework you will need Rust to get started with it.
|
Since `actix-web` is a Rust framework you will need Rust to get started with it. If you
|
||||||
If you don't have it yet we recommend you use `rustup` to manage your Rust
|
don't have it yet we recommend you use `rustup` to manage your Rust installation. The
|
||||||
installation. The [official rust
|
[official rust guide][rustguide] has a wonderful section on getting started.
|
||||||
guide](https://doc.rust-lang.org/book/ch01-01-installation.html)
|
|
||||||
has a wonderful section on getting started.
|
|
||||||
|
|
||||||
We currently require at least Rust {{< rust-version "actix-web" >}} so make sure you
|
We currently require at least Rust {{< rust-version "actix-web" >}} so make sure you run
|
||||||
run `rustup update` to have the latest and greatest Rust version available. In
|
`rustup update` to have the latest and greatest Rust version available. In particular
|
||||||
particular this guide will assume that you actually run Rust
|
this guide will assume that you actually run Rust {{< rust-version "actix-web" >}} or later.
|
||||||
{{< rust-version "actix-web" >}} or later.
|
|
||||||
|
|
||||||
# Installing `actix-web`
|
# Installing `actix-web`
|
||||||
|
|
||||||
@ -40,10 +37,9 @@ actix-web = { git = "https://github.com/actix/actix-web" }
|
|||||||
|
|
||||||
# Diving In
|
# Diving In
|
||||||
|
|
||||||
There are two paths you can take here. You can follow the guide along or if
|
There are two paths you can take here. You can follow the guide along or if you are very
|
||||||
you are very impatient you might want to have a look at our
|
impatient you might want to have a look at our [extensive example repository][exmaples]
|
||||||
[extensive example repository](https://github.com/actix/examples) and run the
|
and run the included examples. Here for instance is how you run the included `basics`
|
||||||
included examples. Here for instance is how you run the included `basics`
|
|
||||||
example:
|
example:
|
||||||
|
|
||||||
```
|
```
|
||||||
@ -51,3 +47,6 @@ git clone https://github.com/actix/examples
|
|||||||
cd examples/basics
|
cd examples/basics
|
||||||
cargo run
|
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
|
* Modify application state
|
||||||
* Access external services (redis, logging, sessions)
|
* Access external services (redis, logging, sessions)
|
||||||
|
|
||||||
Middleware is registered for each application and executed in same order as
|
Middleware is registered for each application and executed in same order as registration.
|
||||||
registration. In general, a *middleware* is a type that implements the
|
In general, a *middleware* is a type that implements the [*Service trait*][servicetrait] and
|
||||||
[*Service trait*](../../actix-web/actix_web/dev/trait.Service.html) and
|
[*Transform trait*][transformtrait]. Each method in the traits has a default
|
||||||
[*Transform trait*](../../actix-web/actix_web/dev/trait.Transform.html).
|
implementation. Each method can return a result immediately or a *future* object.
|
||||||
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:
|
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.
|
Logging middleware must be registered for each application.
|
||||||
|
|
||||||
The `Logger` middleware uses the standard log crate to log information. You should enable logger
|
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).
|
or similar).
|
||||||
|
|
||||||
## Usage
|
## Usage
|
||||||
@ -96,31 +94,30 @@ a specified header.
|
|||||||
|
|
||||||
## User sessions
|
## User sessions
|
||||||
|
|
||||||
Actix provides a general solution for session management. The
|
Actix provides a general solution for session management. The [**actix-session**][actixsession]
|
||||||
[**actix-session**](https://docs.rs/actix-session/0.1.1/actix_session/) middleware can be
|
middleware can be used with different backend types to store session data in different backends.
|
||||||
used with different backend types to store session data in different backends.
|
|
||||||
|
|
||||||
> By default, only cookie session backend is implemented. Other backend implementations
|
> By default, only cookie session backend is implemented. Other backend implementations
|
||||||
> can be added.
|
> can be added.
|
||||||
|
|
||||||
[**CookieSession**](../../actix-web/actix_web/middleware/session/struct.CookieSessionBackend.html)
|
[**CookieSession**][cookiesession] uses cookies as session storage. `CookieSessionBackend`
|
||||||
uses cookies as session storage. `CookieSessionBackend` creates sessions which
|
creates sessions which are limited to storing fewer than 4000 bytes of data, as the payload
|
||||||
are limited to storing fewer than 4000 bytes of data, as the payload must fit into a
|
must fit into a single cookie. An internal server error is generated if a session
|
||||||
single cookie. An internal server error is generated if a session contains more than 4000 bytes.
|
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
|
In general, you create a `SessionStorage` middleware and initialize it with specific
|
||||||
`SessionStorage` middleware and initialize it with specific backend implementation,
|
backend implementation, such as a `CookieSession`. To access session data,
|
||||||
such as a `CookieSession`. To access session data,
|
[*HttpRequest::session()*][requestsession] must be used. This method returns a
|
||||||
[*HttpRequest::session()*](../../actix-web/actix_web/middleware/session/trait.RequestSession.html#tymethod.session)
|
[*Session*][sessionobj] object, which allows us to get or set session data.
|
||||||
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.
|
|
||||||
|
|
||||||
{{< include-example example="middleware" file="user_sessions.rs" section="user-session" >}}
|
{{< 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.
|
into a response.
|
||||||
|
|
||||||
{{< include-example example="middleware" file="errorhandler.rs" section="error-handler" >}}
|
{{< 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
|
* EncodingExt
|
||||||
|
|
||||||
If request headers contain a `Content-Encoding` header, the request payload is decompressed
|
If request headers contain a `Content-Encoding` header, the request payload is decompressed
|
||||||
according to the header value. Multiple codecs are not supported,
|
according to the header value. Multiple codecs are not supported, i.e: `Content-Encoding: br, gzip`.
|
||||||
i.e: `Content-Encoding: br, gzip`.
|
|
||||||
|
|
||||||
# JSON Request
|
# 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" >}}
|
{{< include-example example="requests" file="manual.rs" section="json-manual" >}}
|
||||||
|
|
||||||
> A complete example for both options is available in
|
> A complete example for both options is available in [examples directory][examples].
|
||||||
> [examples directory](https://github.com/actix/examples/tree/master/json/).
|
|
||||||
|
|
||||||
# Chunked transfer encoding
|
# Chunked transfer encoding
|
||||||
|
|
||||||
@ -51,26 +49,22 @@ compression codecs (br, gzip, deflate), then the byte stream is decompressed.
|
|||||||
# Multipart body
|
# Multipart body
|
||||||
|
|
||||||
Actix provides multipart stream support.
|
Actix provides multipart stream support.
|
||||||
[*Multipart*](../../actix-web/actix_web/multipart/struct.Multipart.html) is implemented as
|
[*Multipart*][multipartstruct] is implemented as a stream of multipart items. Each item
|
||||||
a stream of multipart items. Each item can be a
|
can be a [*Field*][fieldstruct] or a nested *Multipart* stream.`HttpResponse::multipart()`
|
||||||
[*Field*](../../actix-web/actix_web/multipart/struct.Field.html) or a nested
|
returns the *Multipart* stream for the current request.
|
||||||
*Multipart* stream.`HttpResponse::multipart()` returns the *Multipart* stream
|
|
||||||
for the current request.
|
|
||||||
|
|
||||||
The following demonstrates multipart stream handling for a simple form:
|
The following demonstrates multipart stream handling for a simple form:
|
||||||
|
|
||||||
{{< include-example example="requests" file="multipart.rs" section="multipart" >}}
|
{{< include-example example="requests" file="multipart.rs" section="multipart" >}}
|
||||||
|
|
||||||
> A full example is available in the
|
> A full example is available in the [examples directory][multipartexample].
|
||||||
> [examples directory](https://github.com/actix/examples/tree/master/multipart/).
|
|
||||||
|
|
||||||
# Urlencoded body
|
# Urlencoded body
|
||||||
|
|
||||||
Actix provides support for *application/x-www-form-urlencoded* encoded bodies.
|
Actix provides support for *application/x-www-form-urlencoded* encoded bodies.
|
||||||
`HttpResponse::urlencoded()` returns a
|
`HttpResponse::urlencoded()` returns a [*UrlEncoded*][urlencoder] future, which resolves
|
||||||
[*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`
|
||||||
to the deserialized instance. The type of the instance must implement the
|
trait from *serde*.
|
||||||
`Deserialize` trait from *serde*.
|
|
||||||
|
|
||||||
The *UrlEncoded* future can resolve into an error in several cases:
|
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:
|
In the following example, we read and print the request payload chunk by chunk:
|
||||||
|
|
||||||
{{< include-example example="requests" file="streaming.rs" section="streaming" >}}
|
{{< include-example example="requests" file="streaming.rs" section="streaming" >}}
|
||||||
|
|
||||||
|
[examples]: https://github.com/actix/examples/tree/master/json/
|
||||||
|
[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,
|
`HttpResponse` provides several methods that return a `HttpResponseBuilder` instance,
|
||||||
which implements various convenience methods for building responses.
|
which implements various convenience methods for building responses.
|
||||||
|
|
||||||
> Check the [documentation](../../actix-web/actix_web/dev/struct.HttpResponseBuilder.html)
|
> Check the [documentation][responsebuilder] for type descriptions.
|
||||||
> for type descriptions.
|
|
||||||
|
|
||||||
The methods `.body`, `.finish`, and `.json` finalize response creation and
|
The methods `.body`, `.finish`, and `.json` finalize response creation and
|
||||||
return a constructed *HttpResponse* instance. If this methods is called on the same
|
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
|
# Content encoding
|
||||||
|
|
||||||
Actix automatically *compresses* payloads. The following codecs are supported:
|
Actix-web automatically *compresses* payloads. The following codecs are supported:
|
||||||
|
|
||||||
* Brotli
|
* Brotli
|
||||||
* Gzip
|
* Gzip
|
||||||
@ -75,3 +74,5 @@ is enabled automatically.
|
|||||||
> Enabling chunked encoding for *HTTP/2.0* responses is forbidden.
|
> Enabling chunked encoding for *HTTP/2.0* responses is forbidden.
|
||||||
|
|
||||||
{{< include-example example="responses" file="chunked.rs" section="chunked" >}}
|
{{< 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 Crash Reporting
|
||||||
|
|
||||||
[Sentry](https://sentry.io/) is a crash reporting system that supports the
|
[Sentry][sentrysite] is a crash reporting system that supports the failure crate which
|
||||||
failure crate which is the base of the actix error reporting. With a
|
is the base of the actix error reporting. With a middleware it's possible to
|
||||||
middleware it's possible to automatically report server errors to Sentry.
|
automatically report server errors to Sentry.
|
||||||
|
|
||||||
# Middleware
|
# Middleware
|
||||||
|
|
||||||
This middleware captures any error in the server error range (500 - 599)
|
This middleware captures any error in the server error range (500 - 599)
|
||||||
and sends the attached error to sentry with its stacktrace.
|
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
|
To use the middleware the [sentry crate][sentrycrate] needs to be initialized and configured
|
||||||
initialized and configured and the [sentry-actix middleware](https://crates.io/crates/sentry-actix)
|
and the [sentry-actix middleware][sentrymiddleware] needs to be added. Additionally it
|
||||||
needs to be added. Additionally it makes sense to also register the panic handler
|
makes sense to also register the panic handler to be informed about hard panics.
|
||||||
to be informed about hard panics.
|
|
||||||
|
|
||||||
{{< include-example example="sentry" file="main.rs" section="middleware" >}}
|
{{< 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.
|
until the end of the `run` block.
|
||||||
|
|
||||||
{{< include-example example="sentry" file="main.rs" section="hub2" >}}
|
{{< 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 HTTP Server
|
||||||
|
|
||||||
The [**HttpServer**](https://docs.rs/actix-web/1.0.2/actix_web/struct.HttpServer.html) type is responsible for
|
The [**HttpServer**][httpserverstruct] type is responsible for serving http requests.
|
||||||
serving http requests.
|
|
||||||
|
|
||||||
`HttpServer` accepts an application factory as a parameter, and the
|
`HttpServer` accepts an application factory as a parameter, and the application factory
|
||||||
application factory must have `Send` + `Sync` boundaries. More about that in the
|
must have `Send` + `Sync` boundaries. More about that in the *multi-threading* section.
|
||||||
*multi-threading* section.
|
|
||||||
|
|
||||||
To bind to a specific socket address,
|
To bind to a specific socket address, [`bind()`][bindmethod] must be used, and it may be
|
||||||
[`bind()`](../../actix-web/actix_web/server/struct.HttpServer.html#method.bind)
|
called multiple times. To bind ssl socket, [`bind_ssl()`][bindsslmethod] or
|
||||||
must be used, and it may be called multiple times. To bind ssl socket,
|
[`bind_rustls()`][bindrusttls] should be used. To start the http server, use one of the
|
||||||
[`bind_ssl()`](../../actix-web/actix_web/server/struct.HttpServer.html#method.bind_ssl)
|
start methods.
|
||||||
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.
|
|
||||||
|
|
||||||
- use [`start()`](../../actix-web/actix_web/server/struct.HttpServer.html#method.start)
|
- use [`start()`] for a server
|
||||||
for a server
|
|
||||||
|
|
||||||
{{< include-example example="server" section="main" >}}
|
{{< include-example example="server" section="main" >}}
|
||||||
|
|
||||||
@ -30,8 +25,8 @@ for a server
|
|||||||
> this server, send a `StopServer` message.
|
> this server, send a `StopServer` message.
|
||||||
|
|
||||||
`HttpServer` is implemented as an actix actor. It is possible to communicate with the server
|
`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
|
via a messaging system. Start method, e.g. `start()`, returns the address of the started
|
||||||
address of the started http server. It accepts several messages:
|
http server. It accepts several messages:
|
||||||
|
|
||||||
- `PauseServer` - Pause accepting incoming connections
|
- `PauseServer` - Pause accepting incoming connections
|
||||||
- `ResumeServer` - Resume accepting incoming connections
|
- `ResumeServer` - Resume accepting incoming connections
|
||||||
@ -41,18 +36,16 @@ address of the started http server. It accepts several messages:
|
|||||||
|
|
||||||
## Multi-threading
|
## Multi-threading
|
||||||
|
|
||||||
`HttpServer` automatically starts a number of http workers, by default
|
`HttpServer` automatically starts a number of http workers, by default this number is
|
||||||
this number is equal to number of logical CPUs in the system. This number
|
equal to number of logical CPUs in the system. This number can be overridden with the
|
||||||
can be overridden with the
|
[`HttpServer::workers()`][workers] method.
|
||||||
[`HttpServer::workers()`](../../actix-web/actix_web/server/struct.HttpServer.html#method.workers) method.
|
|
||||||
|
|
||||||
{{< include-example example="server" file="workers.rs" section="workers" >}}
|
{{< include-example example="server" file="workers.rs" section="workers" >}}
|
||||||
|
|
||||||
The server creates a separate application instance for each created worker. Application state
|
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.
|
is not shared between threads. To share state, `Arc` could be used.
|
||||||
|
|
||||||
> Application state does not need to be `Send` and `Sync`,
|
> Application state does not need to be `Send` and `Sync`, but factories must be `Send` + `Sync`.
|
||||||
> but factories must be `Send` + `Sync`.
|
|
||||||
|
|
||||||
## SSL
|
## SSL
|
||||||
|
|
||||||
@ -66,18 +59,16 @@ actix-web = { version = "{{< actix-version "actix-web" >}}", features = ["ssl"]
|
|||||||
|
|
||||||
{{< include-example example="server" file="ssl.rs" section="ssl" >}}
|
{{< include-example example="server" file="ssl.rs" section="ssl" >}}
|
||||||
|
|
||||||
> **Note**: the *HTTP/2.0* protocol requires
|
> **Note**: the *HTTP/2.0* protocol requires [tls alpn][tlsalpn].
|
||||||
> [tls alpn](https://tools.ietf.org/html/rfc7301).
|
|
||||||
> At the moment, only `openssl` has `alpn` support.
|
> At the moment, only `openssl` has `alpn` support.
|
||||||
> For a full example, check out
|
> For a full example, check out [examples/tls][exampletls].
|
||||||
> [examples/tls](https://github.com/actix/examples/tree/master/tls).
|
|
||||||
|
|
||||||
To create the key.pem and cert.pem use the command. **Fill in your own subject**
|
To create the key.pem and cert.pem use the command. **Fill in your own subject**
|
||||||
```bash
|
```bash
|
||||||
$ openssl req -x509 -newkey rsa:4096 -keyout key.pem -out cert.pem \
|
$ 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"
|
-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
|
```bash
|
||||||
$ openssl rsa -in key.pem -out nopass.pem
|
$ 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" >}}
|
{{< include-example example="server" file="keep_alive.rs" section="keep-alive" >}}
|
||||||
|
|
||||||
If the first option is selected, then *keep alive* state is
|
If the first option is selected, then *keep alive* state is calculated based on the
|
||||||
calculated based on the response's *connection-type*. By default
|
response's *connection-type*. By default `HttpResponse::connection_type` is not
|
||||||
`HttpResponse::connection_type` is not defined. In that case *keep alive* is
|
defined. In that case *keep alive* is defined by the request's http version.
|
||||||
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*.
|
> *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
|
`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
|
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.
|
timeout are force-dropped. By default the shutdown timeout is set to 30 seconds. You
|
||||||
You can change this parameter with the
|
can change this parameter with the [`HttpServer::shutdown_timeout()`][shutdowntimeout]
|
||||||
[`HttpServer::shutdown_timeout()`](../../actix-web/actix_web/server/struct.HttpServer.html#method.shutdown_timeout) method.
|
method.
|
||||||
|
|
||||||
You can send a stop message to the server with the server address and specify if you want
|
You can send a stop message to the server with the server address and specify if you want
|
||||||
graceful shutdown or not. The
|
graceful shutdown or not. The [`start()`][startmethod] method returns address of the server.
|
||||||
[`start()`](../../actix-web/actix_web/server/struct.HttpServer.html#method.start)
|
|
||||||
method returns address of the server.
|
|
||||||
|
|
||||||
`HttpServer` handles several OS signals. *CTRL-C* is available on all OSs,
|
`HttpServer` handles several OS signals. *CTRL-C* is available on all OSs, other signals
|
||||||
other signals are available on unix systems.
|
are available on unix systems.
|
||||||
|
|
||||||
- *SIGINT* - Force shutdown workers
|
- *SIGINT* - Force shutdown workers
|
||||||
- *SIGTERM* - Graceful shutdown workers
|
- *SIGTERM* - Graceful shutdown workers
|
||||||
- *SIGQUIT* - Force shutdown workers
|
- *SIGQUIT* - Force shutdown workers
|
||||||
|
|
||||||
> It is possible to disable signal handling with
|
> It is possible to disable signal handling with
|
||||||
> [`HttpServer::disable_signals()`](../../actix-web/actix_web/server/struct.HttpServer.html#method.disable_signals)
|
[`HttpServer::disable_signals()`][disablesignals] method.
|
||||||
> 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
|
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
|
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.
|
method.
|
||||||
|
|
||||||
Instead of showing files listing for directory, it is possible to redirect
|
Instead of showing files listing for directory, it is possible to redirect to a specific
|
||||||
to a specific index file. Use the
|
index file. Use the [*Files::index_file()*][indexfile] method to configure this redirect.
|
||||||
[*Files::index_file()*](https://docs.rs/actix-files/0.1.2/actix_files/struct.Files.html#method.index_file)
|
|
||||||
method to configure this redirect.
|
|
||||||
|
|
||||||
# Configuration
|
# 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:
|
The Configuration cal also be applied to directory service:
|
||||||
|
|
||||||
{{< include-example example="static-files" file="configuration_two.rs" section="config-two" >}}
|
{{< include-example example="static-files" file="configuration_two.rs" section="config-two" >}}
|
||||||
|
|
||||||
|
[showfileslisting]: https://docs.rs/actix-files/0.1.2/actix_files/struct.Files.html
|
||||||
|
[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
|
# Unit Tests
|
||||||
|
|
||||||
For unit testing, actix-web provides a request builder type and a simple handler runner.
|
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)
|
[*TestRequest*][testrequest] implements a builder-like pattern. You can generate a
|
||||||
implements a builder-like pattern.
|
`HttpRequest` instance with `to_http_request()`, or you can
|
||||||
You can generate a `HttpRequest` instance with `to_http_request()`, or you can
|
|
||||||
run your handler with `block_on()`.
|
run your handler with `block_on()`.
|
||||||
|
|
||||||
{{< include-example example="testing" file="main.rs" section="unit-tests" >}}
|
{{< 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
|
To create a `Service` for testing, use the `test::init_serivce` method which accepts a
|
||||||
regular `App` builder.
|
regular `App` builder.
|
||||||
|
|
||||||
> Check the [api documentation](https://docs.rs/actix-web/1.0.2/actix_web/test/index.html)
|
> Check the [api documentation][actixdocs] for more information.
|
||||||
> for more information.
|
|
||||||
|
|
||||||
{{< include-example example="testing" file="integration_one.rs" section="integration-one" >}}
|
{{< 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
|
# Stream response tests
|
||||||
|
|
||||||
If you need to test stream it would be enough to convert a
|
If you need to test stream it would be enough to convert a [*ClientResponse*][clientresponse]
|
||||||
[*ClientResponse*](../../actix-web/actix_web/client/struct.ClientResponse.html) to future
|
to future and execute it.
|
||||||
and execute it.
|
For example of testing [*Server Sent Events*][serversentevents].
|
||||||
For example of testing
|
|
||||||
[*Server Sent Events*](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events).
|
|
||||||
|
|
||||||
{{< include-example example="testing" file="stream_response.rs" section="stream-response" >}}
|
{{< 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,
|
matching language. If one of the patterns matches the path information associated with a request,
|
||||||
a particular handler object is invoked.
|
a particular handler object is invoked.
|
||||||
|
|
||||||
> A handler is a specific object that implements the
|
> A handler is a specific object that implements the `Handler` trait, defined in your
|
||||||
> `Handler` trait, defined in your application, that receives the request and returns
|
> application, that receives the request and returns a response object. More information
|
||||||
> a response object. More information is available in the
|
> is available in the [handler section][sec4handler].
|
||||||
> [handler section](sec-4-handler.html).
|
|
||||||
|
|
||||||
# Resource configuration
|
# Resource configuration
|
||||||
|
|
||||||
Resource configuration is the act of adding a new resources to an application.
|
Resource configuration is the act of adding a new resources to an application. A resource
|
||||||
A resource has a name, which acts as an identifier to be used for URL generation.
|
has a name, which acts as an identifier to be used for URL generation. The name also
|
||||||
The name also allows developers to add routes to existing resources.
|
allows developers to add routes to existing resources. A resource also has a pattern,
|
||||||
A resource also has a pattern, meant to match against the *PATH* portion of a *URL* (the portion following the scheme and
|
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*).
|
port, e.g. */foo/bar* in the *URL* *http://localhost:8080/foo/bar?q=value*). It does not
|
||||||
It does not match against the *QUERY* portion (the portion that follows *?*, e.g. *q=value* in *http://localhost:8080/foo/bar?q=value*).
|
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
|
The [*App::route()*][approute] method provides simple way of registering routes. This
|
||||||
simple way of registering routes. This method adds a single route to application
|
method adds a single route to application routing table. This method accepts a *path pattern*,
|
||||||
routing table. This method accepts a *path pattern*,
|
|
||||||
*http method* and a handler function. `route()` method could be called multiple times
|
*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.
|
for the same path, in that case, multiple routes register for the same resource path.
|
||||||
|
|
||||||
{{< include-example example="url-dispatch" section="main" >}}
|
{{< include-example example="url-dispatch" section="main" >}}
|
||||||
|
|
||||||
While *App::route()* provides simple way of registering routes, to access
|
While *App::route()* provides simple way of registering routes, to access complete resource
|
||||||
complete resource configuration, a different method has to be used.
|
configuration, a different method has to be used. The [*App::resource()*][appresource] method
|
||||||
The [*App::resource()*](../../actix-web/actix_web/struct.App.html#method.resource) method
|
|
||||||
adds a single resource to application routing table. This method accepts a *path pattern*
|
adds a single resource to application routing table. This method accepts a *path pattern*
|
||||||
and a resource configuration function.
|
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.
|
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
|
[*ResourceHandler::route()*][resourcehandler] returns a [*Route*][route] object. Route
|
||||||
[*Route*](../../actix-web/actix_web/dev/struct.Route.html) object. Route can be configured with a
|
can be configured with a builder-like pattern. Following configuration methods are available:
|
||||||
builder-like pattern. Following configuration methods are available:
|
|
||||||
|
|
||||||
* [*Route::guard()*](../../actix-web/actix_web/dev/struct.Route.html#method.guard)
|
* [*Route::guard()*][routeguard] registers a new guard. Any number of guards can be
|
||||||
registers a new guard. Any number of guards can be registered for each route.
|
registered for each route.
|
||||||
* [*Route::method()*](../../actix-web/actix_web/dev/struct.Route.html#method.method)
|
* [*Route::method()*][routemethod] registers a method guard. Any number of guards can be
|
||||||
registers a method guard. Any number of guards can be registered for each route.
|
registered for each route.
|
||||||
* [*Route::to()*](../../actix-web/actix_web/dev/struct.Route.html#method.to) registers
|
* [*Route::to()*][routeto] registers handler function for this route. Only one handler
|
||||||
handler function for this route. Only one handler can be registered.
|
can be registered. Usually handler registration is the last config operation. Handler
|
||||||
Usually handler registration
|
function can be a function or closure and has the type `Fn(HttpRequest<S>) -> R + 'static`
|
||||||
is the last config operation. Handler function can be a function or closure
|
* [*Route::to_async()*][routetoasync] registers an async handler function for this route.
|
||||||
and has the type
|
Only one handler can be registered. Handler registration is the last config operation.
|
||||||
`Fn(HttpRequest<S>) -> R + 'static`
|
Handler function can be a function or closure and has the type
|
||||||
* [*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
|
|
||||||
`Fn(HttpRequest<S>) -> Future<Item = HttpResponse, Error = Error> + 'static`
|
`Fn(HttpRequest<S>) -> Future<Item = HttpResponse, Error = Error> + 'static`
|
||||||
|
|
||||||
# Route matching
|
# Route matching
|
||||||
@ -272,10 +265,8 @@ You can get variable path segments from `HttpRequest::match_info()`.
|
|||||||
|
|
||||||
# Match information
|
# Match information
|
||||||
|
|
||||||
All values representing matched path segments are available in
|
All values representing matched path segments are available in [`HttpRequest::match_info`][matchinfo].
|
||||||
[`HttpRequest::match_info`](../actix_web/struct.HttpRequest.html#method.match_info).
|
Specific values can be retrieved with [`Params::get()`][paramsget].
|
||||||
Specific values can be retrieved with
|
|
||||||
[`Params::get()`](../actix_web/dev/struct.Params.html#method.get).
|
|
||||||
|
|
||||||
{{< include-example example="url-dispatch" file="minfo.rs" section="minfo" >}}
|
{{< 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
|
## Path information extractor
|
||||||
|
|
||||||
Actix provides functionality for type safe path information extraction.
|
Actix provides functionality for type safe path information extraction. [*Path*][pathstruct]
|
||||||
[*Path*](../../actix-web/actix_web/struct.Path.html) extracts information, destination type
|
extracts information, destination type could be defined in several different forms. Simplest
|
||||||
could be defined in several different forms. Simplest approach is to use
|
approach is to use `tuple` type. Each element in tuple must correpond to one element from
|
||||||
`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 pattern. i.e. you can match path pattern `/{id}/{username}/` against
|
||||||
`Path<(u32, String)>` type, but `Path<(String, String, String)>` type will
|
`Path<(u32, String)>` type, but `Path<(String, String, String)>` type will always fail.
|
||||||
always fail.
|
|
||||||
|
|
||||||
{{< include-example example="url-dispatch" file="path.rs" section="path" >}}
|
{{< 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" >}}
|
{{< include-example example="url-dispatch" file="path2.rs" section="path" >}}
|
||||||
|
|
||||||
[*Query*](../../actix-web/actix_web/struct.Query.html) provides similar
|
[*Query*][query] provides similar functionality for request query parameters.
|
||||||
functionality for request query parameters.
|
|
||||||
|
|
||||||
# Generating resource URLs
|
# Generating resource URLs
|
||||||
|
|
||||||
Use the [*HttpRequest.url_for()*](../../actix-web/actix_web/struct.HttpRequest.html#method.url_for)
|
Use the [*HttpRequest.url_for()*][urlfor] method to generate URLs based on resource
|
||||||
method to generate URLs based on resource patterns. For example, if you've configured a
|
patterns. For example, if you've configured a resource with the name "foo" and the
|
||||||
resource with the name "foo" and the pattern "{a}/{b}/{c}", you might do this:
|
pattern "{a}/{b}/{c}", you might do this:
|
||||||
|
|
||||||
{{< include-example example="url-dispatch" file="urls.rs" section="url" >}}
|
{{< 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
|
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).
|
the current protocol and hostname implied http://example.com). `url_for()` method
|
||||||
`url_for()` method returns [*Url object*](https://docs.rs/url/1.7.0/url/struct.Url.html) so you
|
returns [*Url object*][urlobj] so you can modify this url (add query parameters, anchor, etc).
|
||||||
can modify this url (add query parameters, anchor, etc).
|
|
||||||
`url_for()` could be called only for *named* resources otherwise error get returned.
|
`url_for()` could be called only for *named* resources otherwise error get returned.
|
||||||
|
|
||||||
# External resources
|
# External resources
|
||||||
@ -347,14 +334,13 @@ By normalizing it means:
|
|||||||
* To add a trailing slash to the path.
|
* To add a trailing slash to the path.
|
||||||
* To replace multiple slashes with one.
|
* To replace multiple slashes with one.
|
||||||
|
|
||||||
The handler returns as soon as it finds a path that resolves
|
The handler returns as soon as it finds a path that resolves correctly. The order of
|
||||||
correctly. The order of normalization conditions, if all are enabled, is 1) merge, 2) both merge and append
|
normalization conditions, if all are enabled, is 1) merge, 2) both merge and append and
|
||||||
and 3) append. If the path resolves with
|
3) append. If the path resolves with at least one of those conditions, it will redirect
|
||||||
at least one of those conditions, it will redirect to the new path.
|
to the new path.
|
||||||
|
|
||||||
If *append* is *true*, append slash when needed. If a resource is
|
If *append* is *true*, append slash when needed. If a resource is defined with trailing
|
||||||
defined with trailing slash and the request doesn't have one, it will
|
slash and the request doesn't have one, it will be appended automatically.
|
||||||
be appended automatically.
|
|
||||||
|
|
||||||
If *merge* is *true*, merge multiple consecutive slashes in the path into one.
|
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
|
## Using an Application Prefix to Compose Applications
|
||||||
|
|
||||||
The `web::scope()` method allows to set a specific application scope.
|
The `web::scope()` method allows to set a specific application scope. This scope represents
|
||||||
This scope represents a resource prefix that will be prepended to all resource patterns added
|
a resource prefix that will be prepended to all resource patterns added by the resource
|
||||||
by the resource configuration. This can be used to help mount a set of routes at a different
|
configuration. This can be used to help mount a set of routes at a different location
|
||||||
location than the included callable's author intended while still maintaining the same
|
than the included callable's author intended while still maintaining the same resource names.
|
||||||
resource names.
|
|
||||||
|
|
||||||
For example:
|
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
|
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
|
and returns *true* or *false*. Formally, a guard is any object that implements the
|
||||||
[`Guard`](../actix_web/guard/trait.Guard.html) trait. Actix provides
|
[`Guard`][guardtrait] trait. Actix provides several predicates, you can check
|
||||||
several predicates, you can check
|
[functions section][guardfuncs] of api docs.
|
||||||
[functions section](../../actix-web/actix_web/guard/index.html#functions) of api docs.
|
|
||||||
|
|
||||||
Here is a simple guard that check that a request contains a specific *header*:
|
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.
|
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()`.
|
Guards have access to the application's state via `HttpRequest::data()`. Also predicates
|
||||||
Also predicates can store extra information in
|
can store extra information in [request extensions][httprequest].
|
||||||
[request extensions](../../actix-web/actix_web/struct.HttpRequest.html#method.extensions).
|
|
||||||
|
|
||||||
## Modifying guard values
|
## Modifying guard values
|
||||||
|
|
||||||
@ -440,3 +423,22 @@ This method accepts a *configuration function* same as normal resource configura
|
|||||||
with `App::service()` method.
|
with `App::service()` method.
|
||||||
|
|
||||||
{{< include-example example="url-dispatch" file="dhandler.rs" section="default" >}}
|
{{< 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`
|
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
|
to a stream of [*ws::Message*][message] with a [*ws::WsStream*][wsstream] and then use stream
|
||||||
a [*ws::WsStream*](../../actix-web/actix_web/ws/struct.WsStream.html) and then use stream
|
|
||||||
combinators to handle actual messages, but it is simpler to handle websocket communications
|
combinators to handle actual messages, but it is simpler to handle websocket communications
|
||||||
with an http actor.
|
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" >}}
|
{{< include-example example="websockets" file="main.rs" section="websockets" >}}
|
||||||
|
|
||||||
> A simple websocket echo server example is available in the
|
> A simple websocket echo server example is available in the [examples directory][examples].
|
||||||
> [examples directory](https://github.com/actix/examples/tree/master/websocket/).
|
|
||||||
|
|
||||||
> An example chat server with the ability to chat over a websocket or tcp connection
|
> An example chat server with the ability to chat over a websocket or tcp connection
|
||||||
> is available in [websocket-chat directory](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…
x
Reference in New Issue
Block a user