Implement middleware with `wrap_fn`
wrap_fn is a lightweight way to create Actix middleware. We might want to use it to reduce boilerplate in the middlewares that aren't converted into extractors.
App::new()
.wrap_fn(|request, service| {
// Add a `text/plain` content type header to every response
let fut = service.call(request);
async {
let mut response = fut.await?;
response.headers_mut().insert(
CONTENT_TYPE, HeaderValue::from_static("text/plain"),
);
Ok(response)
}
})
This should be completed before #1249, since the middleware APIs changed in that version (there’s no point in having our middleware conform to the new APIs only to switch to using wrap_fn in the end.
This is how a standalone wrap_fn middleware function would look:
pub fn my_middleware(
request: ServiceRequest,
service: &mut impl Service<
Request = ServiceRequest,
Response = ServiceResponse,
Error = actix_web::Error,
>,
) -> impl Future<Output = Result<ServiceResponse, actix_web::Error>> {
let response = service.call(request);
async move { response.await }
}
I'm guessing that request isn't mutable, but we could still perform some of the same serverstate processing that we're currently doing, although it would be just as nice if the Response contained the Request so that things like request headers were reference-able.
The request can be mutable since we own it (passed by value). wrap_fn middleware have the same access to the request and response as regular middleware.
Ah! Good point.