Skip to main content

nimble_http/
handler.rs

1//! handler.rs
2
3use crate::IntoResponse;
4use hyper::{Body, Request, Response};
5use std::future::Future;
6
7/// Handler trait - 用于处理 HTTP 请求
8pub trait Handler<Args> {
9	type Future: Future<Output = Response<Body>> + Send;
10	fn call(&self, args: Args) -> Self::Future;
11}
12
13// 为零参数 handler 实现
14impl<F, Fut, Res> Handler<()> for F
15where
16	F: Fn() -> Fut + Send + Sync + 'static,
17	Fut: Future<Output = Res> + Send + 'static,
18	Res: IntoResponse,
19{
20	type Future = Pin<Box<dyn Future<Output = Response<Body>> + Send>>;
21
22	fn call(&self, _args: ()) -> Self::Future {
23		let fut = (self)();
24		Box::pin(async move { fut.await.into_response() })
25	}
26}
27
28// 为带 Request 参数的 handler 实现
29impl<F, Fut, Res> Handler<Request<Body>> for F
30where
31	F: Fn(Request<Body>) -> Fut + Send + Sync + 'static,
32	Fut: Future<Output = Res> + Send + 'static,
33	Res: IntoResponse,
34{
35	type Future = Pin<Box<dyn Future<Output = Response<Body>> + Send>>;
36
37	fn call(&self, args: Request<Body>) -> Self::Future {
38		let fut = (self)(args);
39		Box::pin(async move { fut.await.into_response() })
40	}
41}
42
43// 添加需要的导入
44use std::pin::Pin;