Skip to content

Commit e2adbb7

Browse files
committed
feat(service): add service::HttpService that extends service::Service
1 parent e936399 commit e2adbb7

File tree

2 files changed

+54
-1
lines changed

2 files changed

+54
-1
lines changed

src/service/http.rs

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
use std::error::Error as StdError;
2+
3+
use crate::body::HttpBody;
4+
use crate::common::Future;
5+
use crate::service::service::Service;
6+
use crate::{Request, Response};
7+
8+
/// An asynchronous function from `Request` to `Response`.
9+
pub trait HttpService<ReqBody>: sealed::Sealed<ReqBody> {
10+
/// The `HttpBody` body of the `http::Response`.
11+
type ResBody: HttpBody;
12+
13+
/// The error type that can occur within this `Service`.
14+
///
15+
/// Note: Returning an `Error` to a hyper server will cause the connection
16+
/// to be abruptly aborted. In most cases, it is better to return a `Response`
17+
/// with a 4xx or 5xx status code.
18+
type Error: Into<Box<dyn StdError + Send + Sync>>;
19+
20+
/// The `Future` returned by this `Service`.
21+
type Future: Future<Output = Result<Response<Self::ResBody>, Self::Error>>;
22+
23+
#[doc(hidden)]
24+
fn call(&mut self, req: Request<ReqBody>) -> Self::Future;
25+
}
26+
27+
impl<T, B1, B2> HttpService<B1> for T
28+
where
29+
T: Service<Request<B1>, Response = Response<B2>>,
30+
B2: HttpBody,
31+
T::Error: Into<Box<dyn StdError + Send + Sync>>,
32+
{
33+
type ResBody = B2;
34+
35+
type Error = T::Error;
36+
type Future = T::Future;
37+
38+
fn call(&mut self, req: Request<B1>) -> Self::Future {
39+
Service::call(self, req)
40+
}
41+
}
42+
43+
impl<T, B1, B2> sealed::Sealed<B1> for T
44+
where
45+
T: Service<Request<B1>, Response = Response<B2>>,
46+
B2: HttpBody,
47+
{
48+
}
49+
50+
mod sealed {
51+
pub trait Sealed<T> {}
52+
}

src/service/mod.rs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,8 +21,9 @@
2121
//! if you need to implement `Service` for a type manually, you can follow the example
2222
//! in `service_struct_impl.rs`.
2323
24-
mod tower_http;
24+
mod http;
2525
mod service;
26+
mod tower_http;
2627
mod util;
2728

2829
pub(super) use self::tower_http::TowerHttpService;

0 commit comments

Comments
 (0)