syncstorage-rs icon indicating copy to clipboard operation
syncstorage-rs copied to clipboard

Implement middleware with `wrap_fn`

Open AzureMarker opened this issue 5 years ago • 5 comments

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.

AzureMarker avatar Jul 06 '20 20:07 AzureMarker

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 }
}

AzureMarker avatar Jul 22 '20 13:07 AzureMarker

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.

jrconlin avatar Jul 23 '20 17:07 jrconlin

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.

AzureMarker avatar Jul 23 '20 17:07 AzureMarker

Ah! Good point.

jrconlin avatar Jul 23 '20 17:07 jrconlin

JIRA

ethowitz avatar Mar 14 '22 19:03 ethowitz