actix_web::dev

Function fn_factory

source
pub fn fn_factory<F, Cfg, Srv, Req, Fut, Err>(
    f: F,
) -> FnServiceNoConfig<F, Cfg, Srv, Req, Fut, Err>
where F: Fn() -> Fut, Fut: Future<Output = Result<Srv, Err>>, Srv: Service<Req>,
Expand description

Create ServiceFactory for function that can produce services

ยงExamples

use std::io;
use actix_service::{fn_factory, fn_service, Service, ServiceFactory};
use futures_util::future::ok;

/// Service that divides two usize values.
async fn div((x, y): (usize, usize)) -> Result<usize, io::Error> {
    if y == 0 {
        Err(io::Error::new(io::ErrorKind::Other, "divide by zero"))
    } else {
        Ok(x / y)
    }
}

#[actix_rt::main]
async fn main() -> io::Result<()> {
    // Create service factory that produces `div` services
    let factory = fn_factory(|| {
        ok::<_, io::Error>(fn_service(div))
    });

    // construct new service
    let srv = factory.new_service(()).await?;

    // now we can use `div` service
    let result = srv.call((10, 20)).await?;

    println!("10 / 20 = {}", result);

    Ok(())
}