1
0
mirror of https://github.com/actix/actix-extras.git synced 2024-11-24 16:02:59 +01:00

Guide: updates to Middleware chapter.

This commit is contained in:
memoryruins 2018-04-06 18:29:18 -04:00
parent 1f08100f6f
commit a88e97edba

View File

@ -1,23 +1,25 @@
# Middleware # Middleware
Actix' middleware system allows to add additional behavior to request/response processing. Actix's middleware system allows us to add additional behavior to request/response processing.
Middleware can hook into incoming request process and modify request or halt request Middleware can hook into an incoming request process, enabling the ability to modify requests
processing and return response early. Also it can hook into response processing. as well as the ability to halt request processing and return response early.
Typically middlewares are involved in the following actions: Middleware can also hook into response processing.
Typically, middleware is involved in the following actions:
* Pre-process the Request * Pre-process the Request
* Post-process a Response * Post-process a Response
* Modify application state * Modify application state
* Access external services (redis, logging, sessions) * Access external services (redis, logging, sessions)
Middlewares are registered for each application and are executed in same order as Middleware is registered for each application and executed in same order as
registration order. In general, a *middleware* is a type that implements the registration. In general, a *middleware* is a type that implements the
[*Middleware trait*](../actix_web/middlewares/trait.Middleware.html). Each method [*Middleware trait*](../actix_web/middlewares/trait.Middleware.html). Each method
in this trait has a default implementation. Each method can return a result immediately in this trait has a default implementation. Each method can return a result immediately
or a *future* object. or a *future* object.
Here is an example of a simple middleware that adds request and response headers: The following is an example of a simple middleware that adds request and response headers:
```rust ```rust
# extern crate http; # extern crate http;
@ -57,16 +59,17 @@ fn main() {
} }
``` ```
Actix provides several useful middlewares, like *logging*, *user sessions*, etc. > Actix provides several useful middlewares, such as *logging*, *user sessions*, etc.
## Logging ## Logging
Logging is implemented as a middleware. Logging is implemented as a middleware.
It is common to register a logging middleware as the first middleware for the application. It is common to register a logging middleware as the first middleware for the application.
Logging middleware has to be registered for each application. *Logger* middleware Logging middleware must be registered for each application.
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/) or similar). 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/) or similar).
### Usage ### Usage
@ -76,6 +79,7 @@ Default `Logger` can be created with `default` method, it uses the default forma
```ignore ```ignore
%a %t "%r" %s %b "%{Referer}i" "%{User-Agent}i" %T %a %t "%r" %s %b "%{Referer}i" "%{User-Agent}i" %T
``` ```
```rust ```rust
# extern crate actix_web; # extern crate actix_web;
extern crate env_logger; extern crate env_logger;
@ -93,7 +97,7 @@ fn main() {
} }
``` ```
Here is an example of the default logging format: The following is an example of the default logging format:
``` ```
INFO:actix_web::middleware::logger: 127.0.0.1:59934 [02/Dec/2017:00:21:43 -0800] "GET / HTTP/1.1" 302 0 "-" "curl/7.54.0" 0.000397 INFO:actix_web::middleware::logger: 127.0.0.1:59934 [02/Dec/2017:00:21:43 -0800] "GET / HTTP/1.1" 302 0 "-" "curl/7.54.0" 0.000397
@ -126,12 +130,11 @@ INFO:actix_web::middleware::logger: 127.0.0.1:59947 [02/Dec/2017:00:22:40 -0800]
`%{FOO}e` os.environ['FOO'] `%{FOO}e` os.environ['FOO']
## Default headers ## Default headers
To set default response headers the `DefaultHeaders` middleware can be used. The To set default response headers, the `DefaultHeaders` middleware can be used. The
*DefaultHeaders* middleware does not set the header if response headers already contain *DefaultHeaders* middleware does not set the header if response headers already contain
the specified header. a specified header.
```rust ```rust
# extern crate actix_web; # extern crate actix_web;
@ -153,27 +156,28 @@ fn main() {
## User sessions ## User sessions
Actix provides a general solution for session management. The Actix provides a general solution for session management. The
[*Session storage*](../actix_web/middleware/struct.SessionStorage.html) middleware can be [**SessionStorage**](../actix_web/middleware/struct.SessionStorage.html) 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
could be added later.
[*Cookie session backend*](../actix_web/middleware/struct.CookieSessionBackend.html) > By default, only cookie session backend is implemented. Other backend implementations
uses signed cookies as session storage. *Cookie session backend* creates sessions which > can be added.
are limited to storing fewer than 4000 bytes of data (as the payload must fit into a
single cookie). Internal server error is generated if session contains more than 4000 bytes.
You need to pass a random value to the constructor of *CookieSessionBackend*. [**CookieSessionBackend**](../actix_web/middleware/struct.CookieSessionBackend.html)
This is private key for cookie session. When this value is changed, all session data is lost. uses signed cookies as session storage. `CookieSessionBackend` creates sessions which
Note that whatever you write into your session is visible by the user (but not modifiable). 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.
In general case, you create You need to pass a random value to the constructor of `CookieSessionBackend`.
[*Session storage*](../actix_web/middleware/struct.SessionStorage.html) middleware This is a private key for cookie session. When this value is changed, all session data is lost.
and initializes it with specific backend implementation, like *CookieSessionBackend*.
To access session data > **Note**: anything you write into the session is visible by the user, but it is not modifiable.
In general, you create a
`SessionStorage` middleware and initialize it with specific backend implementation,
such as a `CookieSessionBackend`. To access session data,
[*HttpRequest::session()*](../actix_web/middleware/trait.RequestSession.html#tymethod.session) [*HttpRequest::session()*](../actix_web/middleware/trait.RequestSession.html#tymethod.session)
has to be used. This method returns a must be used. This method returns a
[*Session*](../actix_web/middleware/struct.Session.html) object, which allows to get or set [*Session*](../actix_web/middleware/struct.Session.html) object, which allows us to get or set
session data. session data.
```rust ```rust
@ -212,12 +216,12 @@ fn main() {
## Error handlers ## Error handlers
`ErrorHandlers` middleware allows to provide custom handlers for responses. `ErrorHandlers` middleware allows us to provide custom handlers for responses.
You can use `ErrorHandlers::handler()` method to register a custom error handler You can use the `ErrorHandlers::handler()` method to register a custom error handler
for specific status code. You can modify existing response or create completly new for specific status code. You can modify an existing response or create completly new
one. Error handler can return response immediately or return future that resolves one. The error handler can return a response immediately or return a future that resolves
to a response. into a response.
```rust ```rust
# extern crate actix_web; # extern crate actix_web;