Skip to content

Commit 70863ee

Browse files
committed
Use http_types::Error everywhere
1 parent 80fdce2 commit 70863ee

File tree

10 files changed

+73
-45
lines changed

10 files changed

+73
-45
lines changed

examples/chunked.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ fn main() -> Result<(), std::io::Error> {
1010
app.at("/").get(|_| async move {
1111
let file = fs::File::open(file!()).await.unwrap();
1212
let res = Response::new(StatusCode::Ok).body(BufReader::new(file));
13-
res
13+
Ok(res)
1414
});
1515
app.listen("127.0.0.1:8080").await?;
1616
Ok(())

src/endpoint.rs

Lines changed: 12 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,11 @@
1-
use std::sync::Arc;
2-
1+
use crate::response::IntoResponse;
32
use async_std::future::Future;
3+
use async_std::sync::Arc;
4+
use http_types::Result;
45

56
use crate::middleware::Next;
67
use crate::utils::BoxFuture;
7-
use crate::{response::IntoResponse, Middleware, Request, Response};
8+
use crate::{Middleware, Request, Response};
89

910
/// An HTTP request handler.
1011
///
@@ -50,20 +51,22 @@ use crate::{response::IntoResponse, Middleware, Request, Response};
5051
/// Tide routes will also accept endpoints with `Fn` signatures of this form, but using the `async` keyword has better ergonomics.
5152
pub trait Endpoint<State>: Send + Sync + 'static {
5253
/// Invoke the endpoint within the given context
53-
fn call<'a>(&'a self, req: Request<State>) -> BoxFuture<'a, Response>;
54+
fn call<'a>(&'a self, req: Request<State>) -> BoxFuture<'a, Result<Response>>;
5455
}
5556

5657
pub(crate) type DynEndpoint<State> = dyn Endpoint<State>;
5758

5859
impl<State, F: Send + Sync + 'static, Fut> Endpoint<State> for F
5960
where
6061
F: Fn(Request<State>) -> Fut,
61-
Fut: Future + Send + 'static,
62-
Fut::Output: IntoResponse,
62+
Fut: Future<Output = Result<Response>> + Send + 'static,
6363
{
64-
fn call<'a>(&'a self, req: Request<State>) -> BoxFuture<'a, Response> {
64+
fn call<'a>(&'a self, req: Request<State>) -> BoxFuture<'a, Result<Response>> {
6565
let fut = (self)(req);
66-
Box::pin(async move { fut.await.into_response() })
66+
Box::pin(async move {
67+
let res = fut.await?;
68+
Ok(res.into_response())
69+
})
6770
}
6871
}
6972

@@ -107,7 +110,7 @@ impl<E, State: 'static> Endpoint<State> for MiddlewareEndpoint<E, State>
107110
where
108111
E: Endpoint<State>,
109112
{
110-
fn call<'a>(&'a self, req: Request<State>) -> BoxFuture<'a, Response> {
113+
fn call<'a>(&'a self, req: Request<State>) -> BoxFuture<'a, Result<Response>> {
111114
let next = Next {
112115
endpoint: &self.endpoint,
113116
next_middleware: &self.middleware,

src/middleware/cookies.rs

Lines changed: 7 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,8 @@
1+
use crate::middleware::{Middleware, Next};
2+
use crate::response::CookieEvent;
13
use crate::utils::BoxFuture;
2-
use crate::{
3-
middleware::{Middleware, Next},
4-
response::CookieEvent,
5-
Request, Response,
6-
};
4+
use crate::{Request, Response, Result};
5+
76
use cookie::CookieJar;
87
use http_types::headers;
98

@@ -37,7 +36,7 @@ impl<State: Send + Sync + 'static> Middleware<State> for CookiesMiddleware {
3736
&'a self,
3837
mut ctx: Request<State>,
3938
next: Next<'a, State>,
40-
) -> BoxFuture<'a, Response> {
39+
) -> BoxFuture<'a, Result<Response>> {
4140
Box::pin(async move {
4241
let cookie_jar = if let Some(cookie_data) = ctx.local::<CookieData>() {
4342
cookie_data.content.clone()
@@ -49,7 +48,7 @@ impl<State: Send + Sync + 'static> Middleware<State> for CookiesMiddleware {
4948
content
5049
};
5150

52-
let mut res = next.run(ctx).await;
51+
let mut res = next.run(ctx).await?;
5352

5453
// add modifications from response to original
5554
for cookie in res.cookie_events.drain(..) {
@@ -66,7 +65,7 @@ impl<State: Send + Sync + 'static> Middleware<State> for CookiesMiddleware {
6665
let encoded_cookie = cookie.encoded().to_string();
6766
res = res.append_header(headers::SET_COOKIE, encoded_cookie);
6867
}
69-
res
68+
Ok(res)
7069
})
7170
}
7271
}

src/middleware/cors.rs

Lines changed: 11 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ use http_types::headers::HeaderValue;
55
use http_types::{headers, Method, StatusCode};
66

77
use crate::middleware::{Middleware, Next};
8-
use crate::{Request, Response};
8+
use crate::{Request, Response, Result};
99

1010
/// Middleware for CORS
1111
///
@@ -147,7 +147,11 @@ impl Cors {
147147
}
148148

149149
impl<State: Send + Sync + 'static> Middleware<State> for Cors {
150-
fn handle<'a>(&'a self, req: Request<State>, next: Next<'a, State>) -> BoxFuture<'a, Response> {
150+
fn handle<'a>(
151+
&'a self,
152+
req: Request<State>,
153+
next: Next<'a, State>,
154+
) -> BoxFuture<'a, Result<Response>> {
151155
Box::pin(async move {
152156
let origins = req.header(&headers::ORIGIN).cloned().unwrap_or_default();
153157

@@ -161,15 +165,15 @@ impl<State: Send + Sync + 'static> Middleware<State> for Cors {
161165
};
162166

163167
if !self.is_valid_origin(origin) {
164-
return http_types::Response::new(StatusCode::Unauthorized).into();
168+
return Ok(http_types::Response::new(StatusCode::Unauthorized).into());
165169
}
166170

167171
// Return results immediately upon preflight request
168172
if req.method() == Method::Options {
169-
return self.build_preflight_response(&origins).into();
173+
return Ok(self.build_preflight_response(&origins).into());
170174
}
171175

172-
let mut response: http_service::Response = next.run(req).await.into();
176+
let mut response: http_service::Response = next.run(req).await?.into();
173177
response
174178
.insert_header(
175179
headers::ACCESS_CONTROL_ALLOW_ORIGIN,
@@ -188,7 +192,7 @@ impl<State: Send + Sync + 'static> Middleware<State> for Cors {
188192
.insert_header(headers::ACCESS_CONTROL_EXPOSE_HEADERS, expose_headers)
189193
.unwrap();
190194
}
191-
response.into()
195+
Ok(response.into())
192196
})
193197
}
194198
}
@@ -261,7 +265,7 @@ mod test {
261265

262266
fn app() -> crate::Server<()> {
263267
let mut app = crate::Server::new();
264-
app.at(ENDPOINT).get(|_| async move { "Hello World" });
268+
app.at(ENDPOINT).get(|_| async move { Ok("Hello World") });
265269

266270
app
267271
}

src/middleware/logger.rs

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -25,12 +25,12 @@ impl RequestLogger {
2525
&'a self,
2626
ctx: Request<State>,
2727
next: Next<'a, State>,
28-
) -> Response {
28+
) -> crate::Result<Response> {
2929
let path = ctx.uri().path().to_owned();
3030
let method = ctx.method().to_string();
3131
log::trace!("IN => {} {}", method, path);
3232
let start = std::time::Instant::now();
33-
let res = next.run(ctx).await;
33+
let res = next.run(ctx).await?;
3434
let status = res.status();
3535
log::info!(
3636
"{} {} {} {}ms",
@@ -39,12 +39,16 @@ impl RequestLogger {
3939
status,
4040
start.elapsed().as_millis()
4141
);
42-
res
42+
Ok(res)
4343
}
4444
}
4545

4646
impl<State: Send + Sync + 'static> Middleware<State> for RequestLogger {
47-
fn handle<'a>(&'a self, ctx: Request<State>, next: Next<'a, State>) -> BoxFuture<'a, Response> {
47+
fn handle<'a>(
48+
&'a self,
49+
ctx: Request<State>,
50+
next: Next<'a, State>,
51+
) -> BoxFuture<'a, crate::Result<Response>> {
4852
Box::pin(async move { self.log_basic(ctx, next).await })
4953
}
5054
}

src/middleware/mod.rs

Lines changed: 13 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ use std::sync::Arc;
44

55
#[doc(inline)]
66
pub use http_service::HttpService;
7+
use http_types::Result;
78

89
use crate::endpoint::DynEndpoint;
910
use crate::utils::BoxFuture;
@@ -23,17 +24,25 @@ pub use logger::RequestLogger;
2324
/// Middleware that wraps around remaining middleware chain.
2425
pub trait Middleware<State>: 'static + Send + Sync {
2526
/// Asynchronously handle the request, and return a response.
26-
fn handle<'a>(&'a self, cx: Request<State>, next: Next<'a, State>) -> BoxFuture<'a, Response>;
27+
fn handle<'a>(
28+
&'a self,
29+
cx: Request<State>,
30+
next: Next<'a, State>,
31+
) -> BoxFuture<'a, Result<Response>>;
2732
}
2833

2934
impl<State, F> Middleware<State> for F
3035
where
3136
F: Send
3237
+ Sync
3338
+ 'static
34-
+ for<'a> Fn(Request<State>, Next<'a, State>) -> BoxFuture<'a, Response>,
39+
+ for<'a> Fn(Request<State>, Next<'a, State>) -> BoxFuture<'a, crate::Result<Response>>,
3540
{
36-
fn handle<'a>(&'a self, req: Request<State>, next: Next<'a, State>) -> BoxFuture<'a, Response> {
41+
fn handle<'a>(
42+
&'a self,
43+
req: Request<State>,
44+
next: Next<'a, State>,
45+
) -> BoxFuture<'a, crate::Result<Response>> {
3746
(self)(req, next)
3847
}
3948
}
@@ -47,7 +56,7 @@ pub struct Next<'a, State> {
4756

4857
impl<'a, State: 'static> Next<'a, State> {
4958
/// Asynchronously execute the remaining middleware chain.
50-
pub fn run(mut self, req: Request<State>) -> BoxFuture<'a, Response> {
59+
pub fn run(mut self, req: Request<State>) -> BoxFuture<'a, Result<Response>> {
5160
if let Some((current, next)) = self.next_middleware.split_first() {
5261
self.next_middleware = next;
5362
current.handle(req, self)

src/redirect.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -31,9 +31,9 @@ pub struct Redirect {
3131
}
3232

3333
impl<State> Endpoint<State> for Redirect {
34-
fn call<'a>(&'a self, _req: Request<State>) -> BoxFuture<'a, Response> {
34+
fn call<'a>(&'a self, _req: Request<State>) -> BoxFuture<'a, crate::Result<Response>> {
3535
let res = Response::new(StatusCode::TemporaryRedirect)
3636
.set_header("location".parse().unwrap(), self.location.clone());
37-
Box::pin(async move { res })
37+
Box::pin(async move { Ok(res) })
3838
}
3939
}

src/router.rs

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
use http_types::Result;
12
use route_recognizer::{Match, Params, Router as MethodRouter};
23
use std::collections::HashMap;
34

@@ -86,10 +87,14 @@ impl<State: 'static> Router<State> {
8687
}
8788
}
8889

89-
fn not_found_endpoint<State>(_cx: Request<State>) -> BoxFuture<'static, Response> {
90-
Box::pin(async move { Response::new(http_types::StatusCode::NotFound.into()) })
90+
fn not_found_endpoint<State>(_cx: Request<State>) -> BoxFuture<'static, Result<Response>> {
91+
Box::pin(async move { Ok(Response::new(http_types::StatusCode::NotFound.into())) })
9192
}
9293

93-
fn method_not_allowed<State>(_cx: Request<State>) -> BoxFuture<'static, Response> {
94-
Box::pin(async move { Response::new(http_types::StatusCode::MethodNotAllowed.into()) })
94+
fn method_not_allowed<State>(_cx: Request<State>) -> BoxFuture<'static, Result<Response>> {
95+
Box::pin(async move {
96+
Ok(Response::new(
97+
http_types::StatusCode::MethodNotAllowed.into(),
98+
))
99+
})
95100
}

src/server/mod.rs

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -337,8 +337,8 @@ impl<State: Sync + Send + 'static> HttpService for Service<State> {
337337
type Connection = ();
338338
type ConnectionFuture = ReadyFuture;
339339
type ConnectionError = io::Error;
340-
type ResponseFuture = BoxFuture<'static, Result<http_service::Response, io::Error>>;
341-
type ResponseError = io::Error;
340+
type ResponseFuture = BoxFuture<'static, Result<http_service::Response, http_types::Error>>;
341+
type ResponseError = http_types::Error;
342342

343343
fn connect(&self) -> Self::ConnectionFuture {
344344
ReadyFuture {}
@@ -347,14 +347,14 @@ impl<State: Sync + Send + 'static> HttpService for Service<State> {
347347
fn respond(&self, _conn: (), req: http_service::Request) -> Self::ResponseFuture {
348348
let req = Request::new(self.state.clone(), req, Vec::new());
349349
let service = self.clone();
350-
Box::pin(async move { Ok(service.call(req).await.into()) })
350+
Box::pin(async move { Ok(service.call(req).await?.into()) })
351351
}
352352
}
353353

354354
impl<State: Sync + Send + 'static, InnerState: Sync + Send + 'static> Endpoint<State>
355355
for Service<InnerState>
356356
{
357-
fn call<'a>(&'a self, req: Request<State>) -> BoxFuture<'a, Response> {
357+
fn call<'a>(&'a self, req: Request<State>) -> BoxFuture<'a, crate::Result<Response>> {
358358
let Request {
359359
request: req,
360360
mut route_params,
@@ -376,7 +376,8 @@ impl<State: Sync + Send + 'static, InnerState: Sync + Send + 'static> Endpoint<S
376376
next_middleware: &middleware,
377377
};
378378

379-
next.run(req).await
379+
let res = next.run(req).await?;
380+
Ok(res)
380381
})
381382
}
382383
}

src/server/route.rs

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -229,7 +229,10 @@ impl<E> Clone for StripPrefixEndpoint<E> {
229229
}
230230

231231
impl<State, E: Endpoint<State>> Endpoint<State> for StripPrefixEndpoint<E> {
232-
fn call<'a>(&'a self, mut req: crate::Request<State>) -> BoxFuture<'a, Response> {
232+
fn call<'a>(
233+
&'a self,
234+
mut req: crate::Request<State>,
235+
) -> BoxFuture<'a, crate::Result<Response>> {
233236
let rest = req.rest().unwrap_or("");
234237
let uri = req.uri();
235238
let mut new_uri = uri.clone();

0 commit comments

Comments
 (0)