pub fn fn_layer<F, S, St, Req, In, Out, Err>(
f: F,
) -> FnMiddleware<F, S, St, Req, In, Out, Err>Expand description
Creates middleware from an asynchronous function.
This is the simplest way to write middleware. The function receives an
input request and an ApplyCtx that can call the wrapped service with
ApplyCtx::call or access pipeline state with ApplyCtx::st. Binding,
readiness, and shutdown of the wrapped service are forwarded automatically.
Each Middleware::create call clones the function into an Apply
wrapper; it does not invoke it. Request, response, and error types may
change, while the state type stays the same. The middleware implementation
requires Err: From<S::Error> to convert inner readiness errors. See
crate::apply_fn for lifecycle and call-time readiness semantics.
Annotate the request type, and the response or error type when the closure does not otherwise constrain them.
ยงExample
use ntex_service::{Middleware, Service, fn_layer, fn_service};
let log = fn_layer(async |req: u32, ctx| {
println!("request: {req}");
let res: u32 = ctx.call(req).await?;
println!("response: {res}");
Ok::<_, ()>(res)
});
let service = log.create(&(), fn_service(async |req: u32| Ok::<_, ()>(req + 1)));
assert_eq!(service.pipeline(()).call(1).await?, 2);