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

rename FromRequest trait to Responder

This commit is contained in:
Nikolay Kim 2017-12-14 09:43:42 -08:00
parent 355f54efe2
commit c98d320f8c
9 changed files with 76 additions and 72 deletions

View File

@ -4,14 +4,14 @@ A request handler can by any object that implements
[`Handler` trait](../actix_web/dev/trait.Handler.html#implementors).
Request handling happen in two stages. First handler object get called.
Handle can return any object that implements
[`FromRequest` trait](../actix_web/trait.FromRequest.html#foreign-impls).
Then `from_request()` get called on returned object. And finally
result of the `from_request()` call get converted to `Reply` object.
[*Responder trait*](../actix_web/trait.Responder.html#foreign-impls).
Then `respond_to()` get called on returned object. And finally
result of the `respond_to()` call get converted to `Reply` object.
By default actix provides several `FromRequest` implementations for some standard types,
By default actix provides `Responder` implementations for some standard types,
like `&'static str`, `String`, etc.
For complete list of implementations check
[FromRequest documentation](../actix_web/trait.FromRequest.html#foreign-impls).
[Responder documentation](../actix_web/trait.Responder.html#foreign-impls).
Examples of valid handlers:
@ -59,11 +59,11 @@ struct MyObj {
}
/// we have to convert Error into HttpResponse as well
impl FromRequest for MyObj {
impl Responder for MyObj {
type Item = HttpResponse;
type Error = Error;
fn from_request(self, req: HttpRequest) -> Result<HttpResponse> {
fn respond_to(self, req: HttpRequest) -> Result<HttpResponse> {
let body = serde_json::to_string(&self)?;
// Create response and set content type

View File

@ -5,11 +5,11 @@ and [`ResponseError` trait](../actix_web/error/trait.ResponseError.html)
for handling handler's errors.
Any error that implements `ResponseError` trait can be returned as error value.
*Handler* can return *Result* object, actix by default provides
`FromRequest` implemenation for compatible result object. Here is implementation
`Responder` implemenation for compatible result object. Here is implementation
definition:
```rust,ignore
impl<T: FromRequest, E: Into<Error>> FromRequest for Result<T, E>
impl<T: Responder, E: Into<Error>> Responder for Result<T, E>
```
And any error that implements `ResponseError` can be converted into `Error` object.

View File

@ -10,7 +10,7 @@ use std::ops::{Deref, DerefMut};
use mime_guess::get_mime_type;
use param::FromParam;
use handler::{Handler, FromRequest};
use handler::{Handler, Responder};
use httprequest::HttpRequest;
use httpresponse::HttpResponse;
use httpcodes::HTTPOk;
@ -77,11 +77,11 @@ impl DerefMut for NamedFile {
}
}
impl FromRequest for NamedFile {
impl Responder for NamedFile {
type Item = HttpResponse;
type Error = io::Error;
fn from_request(mut self, _: HttpRequest) -> Result<HttpResponse, io::Error> {
fn respond_to(mut self, _: HttpRequest) -> Result<HttpResponse, io::Error> {
let mut resp = HTTPOk.build();
if let Some(ext) = self.path().extension() {
let mime = get_mime_type(&ext.to_string_lossy());
@ -124,11 +124,11 @@ impl Directory {
}
}
impl FromRequest for Directory {
impl Responder for Directory {
type Item = HttpResponse;
type Error = io::Error;
fn from_request(self, req: HttpRequest) -> Result<HttpResponse, io::Error> {
fn respond_to(self, req: HttpRequest) -> Result<HttpResponse, io::Error> {
let index_of = format!("Index of {}", req.path());
let mut body = String::new();
let base = Path::new(req.path());
@ -176,14 +176,14 @@ pub enum FilesystemElement {
Directory(Directory),
}
impl FromRequest for FilesystemElement {
impl Responder for FilesystemElement {
type Item = HttpResponse;
type Error = io::Error;
fn from_request(self, req: HttpRequest) -> Result<HttpResponse, io::Error> {
fn respond_to(self, req: HttpRequest) -> Result<HttpResponse, io::Error> {
match self {
FilesystemElement::File(file) => file.from_request(req),
FilesystemElement::Directory(dir) => dir.from_request(req),
FilesystemElement::File(file) => file.respond_to(req),
FilesystemElement::Directory(dir) => dir.respond_to(req),
}
}
}
@ -294,7 +294,7 @@ mod tests {
let _f: &File = &file; }
{ let _f: &mut File = &mut file; }
let resp = file.from_request(HttpRequest::default()).unwrap();
let resp = file.respond_to(HttpRequest::default()).unwrap();
assert_eq!(resp.headers().get(header::CONTENT_TYPE).unwrap(), "text/x-toml")
}
@ -312,7 +312,7 @@ mod tests {
req.match_info_mut().add("tail", "");
st.show_index = true;
let resp = st.handle(req).from_request(HttpRequest::default()).unwrap();
let resp = st.handle(req).respond_to(HttpRequest::default()).unwrap();
assert_eq!(resp.headers().get(header::CONTENT_TYPE).unwrap(), "text/html; charset=utf-8");
assert!(resp.body().is_binary());
assert!(format!("{:?}", resp.body()).contains("README.md"));

View File

@ -18,26 +18,30 @@ use httpresponse::HttpResponse;
pub trait Handler<S>: 'static {
/// The type of value that handler will return.
type Result: FromRequest;
type Result: Responder;
/// Handle request
fn handle(&self, req: HttpRequest<S>) -> Self::Result;
}
pub trait FromRequest {
/// Trait implemented by types that generate responses for clients.
///
/// Types that implement this trait can be used as the return type of a handler.
pub trait Responder {
/// The associated item which can be returned.
type Item: Into<Reply>;
/// The associated error which can be returned.
type Error: Into<Error>;
fn from_request(self, req: HttpRequest) -> Result<Self::Item, Self::Error>;
/// Convert itself to `Reply` or `Error`.
fn respond_to(self, req: HttpRequest) -> Result<Self::Item, Self::Error>;
}
/// Handler<S> for Fn()
impl<F, R, S> Handler<S> for F
where F: Fn(HttpRequest<S>) -> R + 'static,
R: FromRequest + 'static
R: Responder + 'static
{
type Result = R;
@ -93,20 +97,20 @@ impl Reply {
}
}
impl FromRequest for Reply {
impl Responder for Reply {
type Item = Reply;
type Error = Error;
fn from_request(self, _: HttpRequest) -> Result<Reply, Error> {
fn respond_to(self, _: HttpRequest) -> Result<Reply, Error> {
Ok(self)
}
}
impl FromRequest for HttpResponse {
impl Responder for HttpResponse {
type Item = Reply;
type Error = Error;
fn from_request(self, _: HttpRequest) -> Result<Reply, Error> {
fn respond_to(self, _: HttpRequest) -> Result<Reply, Error> {
Ok(Reply(ReplyItem::Message(Box::new(self))))
}
}
@ -118,14 +122,14 @@ impl From<HttpResponse> for Reply {
}
}
impl<T: FromRequest, E: Into<Error>> FromRequest for Result<T, E>
impl<T: Responder, E: Into<Error>> Responder for Result<T, E>
{
type Item = <T as FromRequest>::Item;
type Item = <T as Responder>::Item;
type Error = Error;
fn from_request(self, req: HttpRequest) -> Result<Self::Item, Self::Error> {
fn respond_to(self, req: HttpRequest) -> Result<Self::Item, Self::Error> {
match self {
Ok(val) => match val.from_request(req) {
Ok(val) => match val.respond_to(req) {
Ok(val) => Ok(val),
Err(err) => Err(err.into()),
},
@ -143,12 +147,12 @@ impl<E: Into<Error>> From<Result<Reply, E>> for Reply {
}
}
impl<A: Actor<Context=HttpContext<A, S>>, S: 'static> FromRequest for HttpContext<A, S>
impl<A: Actor<Context=HttpContext<A, S>>, S: 'static> Responder for HttpContext<A, S>
{
type Item = Reply;
type Error = Error;
fn from_request(self, _: HttpRequest) -> Result<Reply, Error> {
fn respond_to(self, _: HttpRequest) -> Result<Reply, Error> {
Ok(Reply(ReplyItem::Actor(Box::new(self))))
}
}
@ -160,12 +164,12 @@ impl<A: Actor<Context=HttpContext<A, S>>, S: 'static> From<HttpContext<A, S>> fo
}
}
impl FromRequest for Box<Future<Item=HttpResponse, Error=Error>>
impl Responder for Box<Future<Item=HttpResponse, Error=Error>>
{
type Item = Reply;
type Error = Error;
fn from_request(self, _: HttpRequest) -> Result<Reply, Error> {
fn respond_to(self, _: HttpRequest) -> Result<Reply, Error> {
Ok(Reply(ReplyItem::Future(self)))
}
}
@ -179,7 +183,7 @@ pub(crate) trait RouteHandler<S>: 'static {
pub(crate)
struct WrapHandler<S, H, R>
where H: Handler<S, Result=R>,
R: FromRequest,
R: Responder,
S: 'static,
{
h: H,
@ -188,7 +192,7 @@ struct WrapHandler<S, H, R>
impl<S, H, R> WrapHandler<S, H, R>
where H: Handler<S, Result=R>,
R: FromRequest,
R: Responder,
S: 'static,
{
pub fn new(h: H) -> Self {
@ -198,12 +202,12 @@ impl<S, H, R> WrapHandler<S, H, R>
impl<S, H, R> RouteHandler<S> for WrapHandler<S, H, R>
where H: Handler<S, Result=R>,
R: FromRequest + 'static,
R: Responder + 'static,
S: 'static,
{
fn handle(&self, req: HttpRequest<S>) -> Reply {
let req2 = req.clone_without_state();
match self.h.handle(req).from_request(req2) {
match self.h.handle(req).respond_to(req2) {
Ok(reply) => reply.into(),
Err(err) => Reply::response(err.into()),
}
@ -265,11 +269,11 @@ impl<S, R, F> RouteHandler<S> for AsyncHandler<S, R, F>
/// ```
pub struct Json<T: Serialize> (pub T);
impl<T: Serialize> FromRequest for Json<T> {
impl<T: Serialize> Responder for Json<T> {
type Item = HttpResponse;
type Error = Error;
fn from_request(self, _: HttpRequest) -> Result<HttpResponse, Error> {
fn respond_to(self, _: HttpRequest) -> Result<HttpResponse, Error> {
let body = serde_json::to_string(&self.0)?;
Ok(HttpResponse::Ok()
@ -406,7 +410,7 @@ mod tests {
#[test]
fn test_json() {
let json = Json(MyObj{name: "test"});
let resp = json.from_request(HttpRequest::default()).unwrap();
let resp = json.respond_to(HttpRequest::default()).unwrap();
assert_eq!(resp.headers().get(header::CONTENT_TYPE).unwrap(), "application/json");
}

View File

@ -3,7 +3,7 @@
use http::{StatusCode, Error as HttpError};
use body::Body;
use handler::{Reply, Handler, RouteHandler, FromRequest};
use handler::{Reply, Handler, RouteHandler, Responder};
use httprequest::HttpRequest;
use httpresponse::{HttpResponse, HttpResponseBuilder};
@ -81,11 +81,11 @@ impl<S> RouteHandler<S> for StaticResponse {
}
}
impl FromRequest for StaticResponse {
impl Responder for StaticResponse {
type Item = HttpResponse;
type Error = HttpError;
fn from_request(self, _: HttpRequest) -> Result<HttpResponse, HttpError> {
fn respond_to(self, _: HttpRequest) -> Result<HttpResponse, HttpError> {
self.build().body(Body::Empty)
}
}

View File

@ -12,7 +12,7 @@ use cookie::Cookie;
use body::Body;
use error::Error;
use handler::FromRequest;
use handler::Responder;
use encoding::ContentEncoding;
use httprequest::HttpRequest;
@ -431,11 +431,11 @@ impl From<HttpResponseBuilder> for HttpResponse {
}
}
impl FromRequest for HttpResponseBuilder {
impl Responder for HttpResponseBuilder {
type Item = HttpResponse;
type Error = HttpError;
fn from_request(mut self, _: HttpRequest) -> Result<HttpResponse, HttpError> {
fn respond_to(mut self, _: HttpRequest) -> Result<HttpResponse, HttpError> {
self.finish()
}
}
@ -449,11 +449,11 @@ impl From<&'static str> for HttpResponse {
}
}
impl FromRequest for &'static str {
impl Responder for &'static str {
type Item = HttpResponse;
type Error = HttpError;
fn from_request(self, _: HttpRequest) -> Result<HttpResponse, HttpError> {
fn respond_to(self, _: HttpRequest) -> Result<HttpResponse, HttpError> {
HttpResponse::build(StatusCode::OK)
.content_type("text/plain; charset=utf-8")
.body(self)
@ -469,11 +469,11 @@ impl From<&'static [u8]> for HttpResponse {
}
}
impl FromRequest for &'static [u8] {
impl Responder for &'static [u8] {
type Item = HttpResponse;
type Error = HttpError;
fn from_request(self, _: HttpRequest) -> Result<HttpResponse, HttpError> {
fn respond_to(self, _: HttpRequest) -> Result<HttpResponse, HttpError> {
HttpResponse::build(StatusCode::OK)
.content_type("application/octet-stream")
.body(self)
@ -489,11 +489,11 @@ impl From<String> for HttpResponse {
}
}
impl FromRequest for String {
impl Responder for String {
type Item = HttpResponse;
type Error = HttpError;
fn from_request(self, _: HttpRequest) -> Result<HttpResponse, HttpError> {
fn respond_to(self, _: HttpRequest) -> Result<HttpResponse, HttpError> {
HttpResponse::build(StatusCode::OK)
.content_type("text/plain; charset=utf-8")
.body(self)
@ -509,11 +509,11 @@ impl<'a> From<&'a String> for HttpResponse {
}
}
impl<'a> FromRequest for &'a String {
impl<'a> Responder for &'a String {
type Item = HttpResponse;
type Error = HttpError;
fn from_request(self, _: HttpRequest) -> Result<HttpResponse, HttpError> {
fn respond_to(self, _: HttpRequest) -> Result<HttpResponse, HttpError> {
HttpResponse::build(StatusCode::OK)
.content_type("text/plain; charset=utf-8")
.body(self)
@ -529,11 +529,11 @@ impl From<Bytes> for HttpResponse {
}
}
impl FromRequest for Bytes {
impl Responder for Bytes {
type Item = HttpResponse;
type Error = HttpError;
fn from_request(self, _: HttpRequest) -> Result<HttpResponse, HttpError> {
fn respond_to(self, _: HttpRequest) -> Result<HttpResponse, HttpError> {
HttpResponse::build(StatusCode::OK)
.content_type("application/octet-stream")
.body(self)
@ -549,11 +549,11 @@ impl From<BytesMut> for HttpResponse {
}
}
impl FromRequest for BytesMut {
impl Responder for BytesMut {
type Item = HttpResponse;
type Error = HttpError;
fn from_request(self, _: HttpRequest) -> Result<HttpResponse, HttpError> {
fn respond_to(self, _: HttpRequest) -> Result<HttpResponse, HttpError> {
HttpResponse::build(StatusCode::OK)
.content_type("application/octet-stream")
.body(self)
@ -689,7 +689,7 @@ mod tests {
assert_eq!(resp.status(), StatusCode::OK);
assert_eq!(resp.body().binary().unwrap(), &Binary::from("test"));
let resp: HttpResponse = "test".from_request(req.clone()).ok().unwrap();
let resp: HttpResponse = "test".respond_to(req.clone()).ok().unwrap();
assert_eq!(resp.status(), StatusCode::OK);
assert_eq!(resp.headers().get(header::CONTENT_TYPE).unwrap(),
header::HeaderValue::from_static("text/plain; charset=utf-8"));
@ -703,7 +703,7 @@ mod tests {
assert_eq!(resp.status(), StatusCode::OK);
assert_eq!(resp.body().binary().unwrap(), &Binary::from(b"test".as_ref()));
let resp: HttpResponse = b"test".as_ref().from_request(req.clone()).ok().unwrap();
let resp: HttpResponse = b"test".as_ref().respond_to(req.clone()).ok().unwrap();
assert_eq!(resp.status(), StatusCode::OK);
assert_eq!(resp.headers().get(header::CONTENT_TYPE).unwrap(),
header::HeaderValue::from_static("application/octet-stream"));
@ -717,7 +717,7 @@ mod tests {
assert_eq!(resp.status(), StatusCode::OK);
assert_eq!(resp.body().binary().unwrap(), &Binary::from("test".to_owned()));
let resp: HttpResponse = "test".to_owned().from_request(req.clone()).ok().unwrap();
let resp: HttpResponse = "test".to_owned().respond_to(req.clone()).ok().unwrap();
assert_eq!(resp.status(), StatusCode::OK);
assert_eq!(resp.headers().get(header::CONTENT_TYPE).unwrap(),
header::HeaderValue::from_static("text/plain; charset=utf-8"));
@ -731,7 +731,7 @@ mod tests {
assert_eq!(resp.status(), StatusCode::OK);
assert_eq!(resp.body().binary().unwrap(), &Binary::from((&"test".to_owned())));
let resp: HttpResponse = (&"test".to_owned()).from_request(req.clone()).ok().unwrap();
let resp: HttpResponse = (&"test".to_owned()).respond_to(req.clone()).ok().unwrap();
assert_eq!(resp.status(), StatusCode::OK);
assert_eq!(resp.headers().get(header::CONTENT_TYPE).unwrap(),
header::HeaderValue::from_static("text/plain; charset=utf-8"));
@ -747,7 +747,7 @@ mod tests {
assert_eq!(resp.body().binary().unwrap(), &Binary::from(Bytes::from_static(b"test")));
let b = Bytes::from_static(b"test");
let resp: HttpResponse = b.from_request(req.clone()).ok().unwrap();
let resp: HttpResponse = b.respond_to(req.clone()).ok().unwrap();
assert_eq!(resp.status(), StatusCode::OK);
assert_eq!(resp.headers().get(header::CONTENT_TYPE).unwrap(),
header::HeaderValue::from_static("application/octet-stream"));
@ -763,7 +763,7 @@ mod tests {
assert_eq!(resp.body().binary().unwrap(), &Binary::from(BytesMut::from("test")));
let b = BytesMut::from("test");
let resp: HttpResponse = b.from_request(req.clone()).ok().unwrap();
let resp: HttpResponse = b.respond_to(req.clone()).ok().unwrap();
assert_eq!(resp.status(), StatusCode::OK);
assert_eq!(resp.headers().get(header::CONTENT_TYPE).unwrap(),
header::HeaderValue::from_static("application/octet-stream"));

View File

@ -122,7 +122,7 @@ pub use application::Application;
pub use httprequest::HttpRequest;
pub use httpresponse::HttpResponse;
pub use payload::{Payload, PayloadItem};
pub use handler::{Reply, FromRequest, Json, NormalizePath};
pub use handler::{Reply, Responder, Json, NormalizePath};
pub use route::Route;
pub use resource::Resource;
pub use server::HttpServer;

View File

@ -5,7 +5,7 @@ use http::{Method, StatusCode};
use pred;
use body::Body;
use route::Route;
use handler::{Reply, Handler, FromRequest};
use handler::{Reply, Handler, Responder};
use httprequest::HttpRequest;
use httpresponse::HttpResponse;
@ -120,7 +120,7 @@ impl<S: 'static> Resource<S> {
/// ```
pub fn f<F, R>(&mut self, handler: F)
where F: Fn(HttpRequest<S>) -> R + 'static,
R: FromRequest + 'static,
R: Responder + 'static,
{
self.routes.push(Route::default());
self.routes.last_mut().unwrap().f(handler)

View File

@ -2,7 +2,7 @@ use futures::Future;
use error::Error;
use pred::Predicate;
use handler::{Reply, Handler, FromRequest, RouteHandler, AsyncHandler, WrapHandler};
use handler::{Reply, Handler, Responder, RouteHandler, AsyncHandler, WrapHandler};
use httpcodes::HTTPNotFound;
use httprequest::HttpRequest;
use httpresponse::HttpResponse;
@ -58,7 +58,7 @@ impl<S: 'static> Route<S> {
/// during route configuration, because it does not return reference to self.
pub fn f<F, R>(&mut self, handler: F)
where F: Fn(HttpRequest<S>) -> R + 'static,
R: FromRequest + 'static,
R: Responder + 'static,
{
self.handler = Box::new(WrapHandler::new(handler));
}