tower_util/
service_fn.rs

1use std::future::Future;
2use std::task::{Context, Poll};
3use tower_service::Service;
4
5/// Returns a new `ServiceFn` with the given closure.
6pub fn service_fn<T>(f: T) -> ServiceFn<T> {
7    ServiceFn { f }
8}
9
10/// A `Service` implemented by a closure.
11#[derive(Copy, Clone, Debug)]
12pub struct ServiceFn<T> {
13    f: T,
14}
15
16impl<T, F, Request, R, E> Service<Request> for ServiceFn<T>
17where
18    T: FnMut(Request) -> F,
19    F: Future<Output = Result<R, E>>,
20{
21    type Response = R;
22    type Error = E;
23    type Future = F;
24
25    fn poll_ready(&mut self, _: &mut Context<'_>) -> Poll<Result<(), E>> {
26        Ok(()).into()
27    }
28
29    fn call(&mut self, req: Request) -> Self::Future {
30        (self.f)(req)
31    }
32}