1
0
mirror of https://github.com/fafhrd91/actix-web synced 2024-11-27 17:52:56 +01:00

Implement Responder for Option #294 (#297)

This commit is contained in:
David McNeil 2018-06-11 05:05:41 -06:00 committed by Douman
parent 9afc3b6737
commit 0d54b6f38e
2 changed files with 39 additions and 0 deletions

View File

@ -737,6 +737,7 @@ impl<S: 'static> Iterator for App<S> {
#[cfg(test)]
mod tests {
use super::*;
use body::{Body, Binary};
use http::StatusCode;
use httprequest::HttpRequest;
use httpresponse::HttpResponse;
@ -957,4 +958,21 @@ mod tests {
let response = srv.execute(request.send()).unwrap();
assert_eq!(response.status(), StatusCode::NOT_FOUND);
}
#[test]
fn test_option_responder() {
let mut app = App::new()
.resource("/none", |r| r.f(|_| -> Option<&'static str> { None }))
.resource("/some", |r| r.f(|_| Some("some")))
.finish();
let req = TestRequest::with_uri("/none").finish();
let resp = app.run(req);
assert_eq!(resp.as_msg().status(), StatusCode::NOT_FOUND);
let req = TestRequest::with_uri("/some").finish();
let resp = app.run(req);
assert_eq!(resp.as_msg().status(), StatusCode::OK);
assert_eq!(resp.as_msg().body(), &Body::Binary(Binary::Slice(b"some")));
}
}

View File

@ -5,6 +5,7 @@ use futures::future::{err, ok, Future};
use futures::{Async, Poll};
use error::Error;
use http::StatusCode;
use httprequest::HttpRequest;
use httpresponse::HttpResponse;
@ -132,6 +133,26 @@ where
}
}
impl<T> Responder for Option<T>
where
T: Responder,
{
type Item = AsyncResult<HttpResponse>;
type Error = Error;
fn respond_to<S: 'static>(
self, req: &HttpRequest<S>,
) -> Result<AsyncResult<HttpResponse>, Error> {
match self {
Some(t) => match t.respond_to(req) {
Ok(val) => Ok(val.into()),
Err(err) => Err(err.into()),
},
None => Ok(req.build_response(StatusCode::NOT_FOUND).finish().into()),
}
}
}
/// Convenience trait that converts `Future` object to a `Boxed` future
///
/// For example loading json from request's body is async operation.