I am writing a small http app and need to return hard coded response in a http handler written using Hyper.
The issue is that the response varies with the requst path, say /test
returns First response
, /no-test
returns Second response
, and so on.
A simple HTTP handler in hyper looks like this:
async fn raw_body(_: Request<Body>) -> Result<Response<Body>, anyhow::Error> {
Ok(Response::new(Body::from("Home page")))
}
which will desugar to (in my case)
fn raw_body(_: Request<Body>) -> impl Future<Output = Result<Response<Body>, anyhow::Error>> {
async { Ok(Response::new(Body::from("Home page"))) }
}
Which I understand and is working fine for me.
Now I want to be able to do something like this:
fn handler_factory(response_body: String, headers: HashMap<String, String>) -> Fn(Request<Body>) -> impl Future<Output=Result<Request<Body>, anyhow::Error>> {
return |_req: Request<Body>| {
async move {
Ok(Response::new(Body::from(response_body.as_ref()))
}
};
}
which does work, because impl is not allowed inside the return type of a function.
Then I tried something like this:
fn handler_factory<H, R>(response_body: String, headers: HashMap<String, String>) -> H
where
H: Fn(Request<Body>) -> R + 'static,
R: Future<Output=Result<Response<Body>, anyhow::Error>>
{
return |_req: Request<Body>| {
async move {
Ok(Response::new(Body::from(response_body.as_ref()))
}
};
}
Now I am out of ideas what could be a better way to achieve this. The library "routerify" does something similar while accepting the handler as an argument, but I can't seem to make it work while returning the function back to the caller. Can I please get some help on this?