How to call async static service methods in hyper?

Playground Rust Playground

Can we impl custom Service with async static methods that we can call while returning future responses?

use std::env::var;
use std::marker::PhantomData;
use std::pin::Pin;
use std::task::{Context, Poll};
use futures::Future;
use hyper::service::Service;
use hyper::{Body, Request, Response, StatusCode};

pub struct MakeSvc<'a> {
    pub(crate) _lifetime: PhantomData<&'a ()>
}

#[derive(Clone)]
pub struct Svc<'a> {
    pub(crate) _lifetime: PhantomData<&'a ()>
}

impl <'a> Svc<'a> {
    pub async fn kool(&'a self)->i32{
        99
    }
}

impl<'a,T> Service<T> for MakeSvc<'a>{
    type Response = Svc<'a>;
    type Error = hyper::Error;
    type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>> + Send>>;
    fn poll_ready(&mut self, _: &mut Context) -> Poll<Result<(), Self::Error>> {
        Poll::Ready(Ok(()))
    }
    fn call(&mut self, _: T) -> Self::Future {
        let fut = async move {
            Ok(Svc {   _lifetime: Default::default() })
        };
        Box::pin(fut)
    }
}

impl<'a> Service<Request<Body>> for Svc<'a> {
    type Response = Response<Body>;
    type Error = hyper::Error;
    type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>>  +'a + Send>>;
    fn poll_ready(&mut self, _: &mut Context) -> Poll<Result<(), Self::Error>> {
        Poll::Ready(Ok(()))
    }
    fn call(&mut self, req: Request<Body>) -> Self::Future {
        let res = async move {
            match (req.method(), req.uri().path()) {
                _ => {
                    self.kool();
                    Ok(Response::builder()
                        .status(StatusCode::NOT_FOUND)
                        .body("sorry".into())
                        .unwrap())
                }
            }
        };
        Box::pin(res)
    }
}

You're not allowed to use self in the future returned by call. The lifetimes in the Service trait do not allow it.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.