Function actix_service::fn_factory[][src]

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

Create ServiceFactory for function that can produce services

Example

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 mut srv = factory.new_service(()).await?;

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

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

    Ok(())
}