1
0
mirror of https://github.com/fafhrd91/actix-web synced 2024-12-04 12:21:56 +01:00
actix-web/guide/src/qs_10.md

207 lines
6.8 KiB
Markdown
Raw Normal View History

2017-12-04 05:47:15 +01:00
# Middlewares
2017-12-26 16:58:21 +01:00
Actix middlewares system allows to add additional behaviour to request/response processing.
Middleware can hook into incomnig request process and modify request or halt request
processing and return response early. Also it can hook into response processing.
Typically middlewares involves in following actions:
* Pre-process the Request
* Post-process a Response
* Modify application state
* Access external services (redis, logging, sessions)
2017-12-27 04:59:41 +01:00
Middlewares are registered for each application and get executed in same order as
registraton order. In general, *middleware* is a type that implements
2017-12-26 16:58:21 +01:00
[*Middleware trait*](../actix_web/middlewares/trait.Middleware.html). Each method
in this trait has default implementation. Each method can return result immidietly
or *future* object.
Here is example of simple middleware that adds request and response headers:
```rust
# extern crate http;
# extern crate actix_web;
use http::{header, HttpTryFrom};
use actix_web::*;
2017-12-27 04:59:41 +01:00
use actix_web::middleware::{Middleware, Started, Response};
2017-12-26 16:58:21 +01:00
struct Headers; // <- Our middleware
/// Middleware implementation, middlewares are generic over application state,
/// so you can access state with `HttpRequest::state()` method.
impl<S> Middleware<S> for Headers {
/// Method is called when request is ready. It may return
/// future, which should resolve before next middleware get called.
fn start(&self, req: &mut HttpRequest<S>) -> Started {
req.headers_mut().insert(
header::CONTENT_TYPE, header::HeaderValue::from_static("text/plain"));
Started::Done
}
/// Method is called when handler returns response,
/// but before sending http message to peer.
fn response(&self, req: &mut HttpRequest<S>, mut resp: HttpResponse) -> Response {
resp.headers_mut().insert(
header::HeaderName::try_from("X-VERSION").unwrap(),
header::HeaderValue::from_static("0.2"));
Response::Done(resp)
}
}
fn main() {
Application::new()
.middleware(Headers) // <- Register middleware, this method could be called multiple times
.resource("/", |r| r.h(httpcodes::HTTPOk));
}
```
Active provides several useful middlewares, like *logging*, *user sessions*, etc.
2017-12-04 05:47:15 +01:00
## Logging
2017-12-26 16:58:21 +01:00
Logging is implemented as middleware.
2017-12-04 05:47:15 +01:00
It is common to register logging middleware as first middleware for application.
Logging middleware has to be registered for each application.
### Usage
2017-12-27 04:59:41 +01:00
Create `Logger` middleware with the specified `format`.
2017-12-04 05:47:15 +01:00
Default `Logger` could be created with `default` method, it uses the default format:
```ignore
%a %t "%r" %s %b "%{Referrer}i" "%{User-Agent}i" %T
```
```rust
2017-12-06 20:00:39 +01:00
# extern crate actix_web;
2017-12-04 05:47:15 +01:00
use actix_web::Application;
2017-12-27 04:59:41 +01:00
use actix_web::middleware::Logger;
2017-12-04 05:47:15 +01:00
fn main() {
Application::new()
2017-12-04 05:47:15 +01:00
.middleware(Logger::default())
.middleware(Logger::new("%a %{User-Agent}i"))
.finish();
}
```
Here is example of default logging format:
```
2017-12-27 04:59:41 +01:00
INFO:actix_web::middleware::logger: 127.0.0.1:59934 [02/Dec/2017:00:21:43 -0800] "GET / HTTP/1.1" 302 0 "-" "curl/7.54.0" 0.000397
INFO:actix_web::middleware::logger: 127.0.0.1:59947 [02/Dec/2017:00:22:40 -0800] "GET /index.html HTTP/1.1" 200 0 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.13; rv:57.0) Gecko/20100101 Firefox/57.0" 0.000646
2017-12-04 05:47:15 +01:00
```
### Format
`%%` The percent sign
`%a` Remote IP-address (IP-address of proxy if using reverse proxy)
`%t` Time when the request was started to process
`%P` The process ID of the child that serviced the request
`%r` First line of request
`%s` Response status code
`%b` Size of response in bytes, including HTTP headers
2017-12-04 22:32:05 +01:00
`%T` Time taken to serve the request, in seconds with floating fraction in .06f format
2017-12-04 05:47:15 +01:00
`%D` Time taken to serve the request, in milliseconds
`%{FOO}i` request.headers['FOO']
`%{FOO}o` response.headers['FOO']
`%{FOO}e` os.environ['FOO']
## Default headers
2017-12-11 23:27:09 +01:00
To set default response headers `DefaultHeaders` middleware could be used.
2017-12-20 00:44:25 +01:00
*DefaultHeaders* middleware does not set header if response headers already contains
specified header.
2017-12-04 05:47:15 +01:00
```rust
2017-12-06 20:00:39 +01:00
# extern crate actix_web;
2017-12-04 05:47:15 +01:00
use actix_web::*;
fn main() {
let app = Application::new()
2017-12-04 05:47:15 +01:00
.middleware(
2017-12-27 04:59:41 +01:00
middleware::DefaultHeaders::build()
2017-12-04 05:47:15 +01:00
.header("X-Version", "0.2")
.finish())
.resource("/test", |r| {
r.method(Method::GET).f(|req| httpcodes::HTTPOk);
r.method(Method::HEAD).f(|req| httpcodes::HTTPMethodNotAllowed);
2017-12-04 05:47:15 +01:00
})
.finish();
}
```
## User sessions
2017-12-14 07:36:28 +01:00
2017-12-20 00:44:25 +01:00
Actix provides general solution for session management.
2017-12-27 04:59:41 +01:00
[*Session storage*](../actix_web/middleware/struct.SessionStorage.html) middleare can be
2017-12-20 00:44:25 +01:00
use 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.
2017-12-27 04:59:41 +01:00
[*Cookie session backend*](../actix_web/middleware/struct.CookieSessionBackend.html)
uses signed cookies as session storage. *Cookie session backend* creates sessions which
are limited to storing fewer than 4000 bytes of data (as the payload must fit into a
2017-12-20 00:44:25 +01:00
single cookie). Internal server error get generated if session contains more than 4000 bytes.
You need to pass a random value to the constructor of *CookieSessionBackend*.
This is private key for cookie session. When this value is changed, all session data is lost.
Note that whatever you write into your session is visible by the user (but not modifiable).
In general case, you cretate
2017-12-27 04:59:41 +01:00
[*Session storage*](../actix_web/middleware/struct.SessionStorage.html) middleware
and initializes it with specific backend implementation, like *CookieSessionBackend*.
2017-12-20 00:44:25 +01:00
To access session data
2017-12-27 04:59:41 +01:00
[*HttpRequest::session()*](../actix_web/middleware/trait.RequestSession.html#tymethod.session)
2017-12-20 00:44:25 +01:00
method has to be used. This method returns
2017-12-27 04:59:41 +01:00
[*Session*](../actix_web/middleware/struct.Session.html) object, which allows to get or set
2017-12-20 00:44:25 +01:00
session data.
```rust
# extern crate actix;
# extern crate actix_web;
use actix_web::*;
2017-12-27 04:59:41 +01:00
use actix_web::middleware::{RequestSession, SessionStorage, CookieSessionBackend};
2017-12-20 00:44:25 +01:00
fn index(mut req: HttpRequest) -> Result<&'static str> {
// access session data
if let Some(count) = req.session().get::<i32>("counter")? {
println!("SESSION value: {}", count);
req.session().set("counter", count+1)?;
} else {
req.session().set("counter", 1)?;
}
Ok("Welcome!")
}
fn main() {
# let sys = actix::System::new("basic-example");
HttpServer::new(
|| Application::new()
2017-12-27 04:59:41 +01:00
.middleware(SessionStorage::new( // <- create session middleware
2017-12-20 03:38:02 +01:00
CookieSessionBackend::build(&[0; 32]) // <- create cookie session backend
2017-12-20 00:44:25 +01:00
.secure(false)
.finish()
2017-12-27 04:59:41 +01:00
)))
2017-12-20 00:44:25 +01:00
.bind("127.0.0.1:59880").unwrap()
.start();
# actix::Arbiter::system().send(actix::msgs::SystemExit(0));
# let _ = sys.run();
}
```