1
0
Fork 0
mirror of https://github.com/actix/actix-web.git synced 2024-12-19 06:36:36 +00:00

optimize with and with2 method impls and tests

This commit is contained in:
Nikolay Kim 2018-03-28 21:33:40 -07:00
parent 90e3aaaf8a
commit 45dec8d0c0
4 changed files with 142 additions and 25 deletions

View file

@ -15,6 +15,16 @@ pub trait HttpRequestExtractor<S>: Sized where S: 'static
fn extract(req: &HttpRequest<S>) -> Self::Result;
}
impl<S: 'static> HttpRequestExtractor<S> for HttpRequest<S>
{
type Result = FutureResult<Self, Error>;
#[inline]
fn extract(req: &HttpRequest<S>) -> Self::Result {
result(Ok(req.clone()))
}
}
/// Extract typed information from the request's path.
///
/// `S` - application state type

View file

@ -255,8 +255,8 @@ mod tests {
let mut handler = with(|data: Json<MyObject>| data);
let req = HttpRequest::default();
let mut json = handler.handle(req).into_future();
assert!(json.poll().is_err());
let err = handler.handle(req).as_response().unwrap().error().is_some();
assert!(err);
let mut req = HttpRequest::default();
req.headers_mut().insert(header::CONTENT_TYPE,
@ -264,7 +264,7 @@ mod tests {
req.headers_mut().insert(header::CONTENT_LENGTH,
header::HeaderValue::from_static("16"));
req.payload_mut().unread_data(Bytes::from_static(b"{\"name\": \"test\"}"));
let mut json = handler.handle(req).into_future();
assert!(json.poll().is_ok())
let ok = handler.handle(req).as_response().unwrap().error().is_none();
assert!(ok)
}
}

View file

@ -45,7 +45,7 @@ fn with<T, S, H>(h: H) -> With<T, S, H>
}
pub struct With<T, S, H>
where H: WithHandler<T, S>,
where H: WithHandler<T, S> + 'static,
T: HttpRequestExtractor<S>,
S: 'static,
{
@ -62,15 +62,33 @@ impl<T, S, H> Handler<S> for With<T, S, H>
type Result = Reply;
fn handle(&mut self, req: HttpRequest<S>) -> Self::Result {
let fut = Box::new(T::extract(&req));
Reply::async(
WithHandlerFut{
req,
hnd: Rc::clone(&self.hnd),
fut1: Some(fut),
fut2: None,
})
let mut fut = T::extract(&req);
match fut.poll() {
Ok(Async::Ready(item)) => {
let hnd: &mut H = unsafe{&mut *self.hnd.get()};
match hnd.handle(item).respond_to(req.without_state()) {
Ok(item) => match item.into().into() {
ReplyItem::Message(resp) => Reply::response(resp),
ReplyItem::Future(fut) => Reply::async(
WithHandlerFut{
req,
hnd: Rc::clone(&self.hnd),
fut1: None,
fut2: Some(fut),
})
},
Err(e) => Reply::response(e.into()),
}
}
Ok(Async::NotReady) => Reply::async(
WithHandlerFut{
req,
hnd: Rc::clone(&self.hnd),
fut1: Some(Box::new(fut)),
fut2: None,
}),
Err(e) => Reply::response(e),
}
}
}
@ -154,17 +172,52 @@ impl<T1, T2, S, F, R> Handler<S> for With2<T1, T2, S, F, R>
type Result = Reply;
fn handle(&mut self, req: HttpRequest<S>) -> Self::Result {
let fut = Box::new(T1::extract(&req));
Reply::async(
WithHandlerFut2{
req,
hnd: Rc::clone(&self.hnd),
item: None,
fut1: Some(fut),
fut2: None,
fut3: None,
})
let mut fut = T1::extract(&req);
match fut.poll() {
Ok(Async::Ready(item1)) => {
let mut fut = T2::extract(&req);
match fut.poll() {
Ok(Async::Ready(item2)) => {
let hnd: &mut F = unsafe{&mut *self.hnd.get()};
match (*hnd)(item1, item2).respond_to(req.without_state()) {
Ok(item) => match item.into().into() {
ReplyItem::Message(resp) => Reply::response(resp),
ReplyItem::Future(fut) => Reply::async(
WithHandlerFut2{
req,
item: None,
hnd: Rc::clone(&self.hnd),
fut1: None,
fut2: None,
fut3: Some(fut),
})
},
Err(e) => Reply::response(e.into()),
}
},
Ok(Async::NotReady) => Reply::async(
WithHandlerFut2{
req,
hnd: Rc::clone(&self.hnd),
item: Some(item1),
fut1: None,
fut2: Some(Box::new(fut)),
fut3: None,
}),
Err(e) => Reply::response(e),
}
},
Ok(Async::NotReady) => Reply::async(
WithHandlerFut2{
req,
hnd: Rc::clone(&self.hnd),
item: None,
fut1: Some(Box::new(fut)),
fut2: None,
fut3: None,
}),
Err(e) => Reply::response(e),
}
}
}

View file

@ -62,6 +62,60 @@ fn test_query_extractor() {
assert_eq!(response.status(), StatusCode::BAD_REQUEST);
}
#[test]
fn test_path_and_query_extractor() {
let mut srv = test::TestServer::new(|app| {
app.resource(
"/{username}/index.html", |r| r.route().with2(
|p: Path<PParam>, q: Query<PParam>|
format!("Welcome {} - {}!", p.username, q.username)));
}
);
// client request
let request = srv.get().uri(srv.url("/test1/index.html?username=test2"))
.finish().unwrap();
let response = srv.execute(request.send()).unwrap();
assert!(response.status().is_success());
// read response
let bytes = srv.execute(response.body()).unwrap();
assert_eq!(bytes, Bytes::from_static(b"Welcome test1 - test2!"));
// client request
let request = srv.get().uri(srv.url("/test1/index.html"))
.finish().unwrap();
let response = srv.execute(request.send()).unwrap();
assert_eq!(response.status(), StatusCode::BAD_REQUEST);
}
#[test]
fn test_path_and_query_extractor2() {
let mut srv = test::TestServer::new(|app| {
app.resource(
"/{username}/index.html", |r| r.route().with3(
|_: HttpRequest, p: Path<PParam>, q: Query<PParam>|
format!("Welcome {} - {}!", p.username, q.username)));
}
);
// client request
let request = srv.get().uri(srv.url("/test1/index.html?username=test2"))
.finish().unwrap();
let response = srv.execute(request.send()).unwrap();
assert!(response.status().is_success());
// read response
let bytes = srv.execute(response.body()).unwrap();
assert_eq!(bytes, Bytes::from_static(b"Welcome test1 - test2!"));
// client request
let request = srv.get().uri(srv.url("/test1/index.html"))
.finish().unwrap();
let response = srv.execute(request.send()).unwrap();
assert_eq!(response.status(), StatusCode::BAD_REQUEST);
}
#[test]
fn test_non_ascii_route() {
let mut srv = test::TestServer::new(|app| {