Skip to main content

from_fn

Function from_fn 

Source
pub fn from_fn<F, S, St, In>(f: F) -> FromFn<F, S, St, In>
where St: State, F: AsyncFn(WebRequest<In>, Next<'_, S, St>) -> Result<WebResponse, WebError<St, St::Error>> + Clone,
Expand description

Creates web middleware from an async closure.

The closure receives the request and a Next handle. Call Next::call() to run the rest of the pipeline, or return a response without calling it to short-circuit. Binding, readiness, and shutdown are forwarded to the inner service automatically.

Closure types are inferred, no annotations are needed:

use ntex::http::header::{HeaderName, HeaderValue};
use ntex::web::{self, App, HttpResponse, middleware::from_fn};

let server = web::HttpServer::new(async |_| {
    App::new()
        .middleware(from_fn(async |req, next| {
            if !req.headers().contains_key("authorization") {
                return Ok(req.into_response(HttpResponse::Unauthorized().build()));
            }
            let mut res = next.call(req).await?;
            res.headers_mut().insert(
                HeaderName::from_static("x-application"),
                HeaderValue::from_static("example"),
            );
            Ok(res)
        }))
        .route("/", web::get().to(async || "Hello"))
});

Return Err(web::WebError::from_err(err)) to reject a request with any WebResponseError. To read application state with Next::st(), annotate the state type of next:

use ntex::http::header::{HeaderName, HeaderValue};
use ntex::web::{self, App, AppState, middleware::{Next, from_fn}, test};

let app = test::init_service_st(
    AppState::new("example"),
    App::new()
        .middleware(from_fn(async |req, next: Next<'_, _, AppState<&str>>| {
            let name = **next.st();
            let mut res = next.call(req).await?;
            res.headers_mut().insert(
                HeaderName::from_static("x-application"),
                HeaderValue::from_static(name),
            );
            Ok(res)
        }))
        .route("/", web::get().to(async || "Hello")),
)
.await;