2016-03-28 09:34:09 +00:00
|
|
|
use std::fs::File;
|
2019-08-20 01:13:49 +00:00
|
|
|
use std::io::Cursor;
|
2016-03-28 09:34:09 +00:00
|
|
|
|
2019-09-22 22:48:08 +00:00
|
|
|
use futures_util::future::ready;
|
|
|
|
use tokio_io::BufReader;
|
2019-06-30 16:45:17 +00:00
|
|
|
|
2019-06-13 01:48:02 +00:00
|
|
|
use crate::http::{Status, ContentType, StatusClass};
|
|
|
|
use crate::response::{self, Response, Body};
|
|
|
|
use crate::request::Request;
|
2016-10-25 11:03:50 +00:00
|
|
|
|
2016-12-21 08:09:22 +00:00
|
|
|
/// Trait implemented by types that generate responses for clients.
|
2016-11-03 14:09:01 +00:00
|
|
|
///
|
|
|
|
/// Types that implement this trait can be used as the return type of a handler,
|
2018-10-06 13:25:17 +00:00
|
|
|
/// as illustrated below with `T`:
|
2016-11-03 14:09:01 +00:00
|
|
|
///
|
2018-10-06 13:25:17 +00:00
|
|
|
/// ```rust
|
2019-08-20 23:53:00 +00:00
|
|
|
/// # #![feature(proc_macro_hygiene)]
|
2018-10-06 13:25:17 +00:00
|
|
|
/// # #[macro_use] extern crate rocket;
|
|
|
|
/// # type T = ();
|
|
|
|
/// #
|
2016-11-03 14:09:01 +00:00
|
|
|
/// #[get("/")]
|
2018-10-06 13:25:17 +00:00
|
|
|
/// fn index() -> T { /* ... */ }
|
2016-11-03 14:09:01 +00:00
|
|
|
/// ```
|
|
|
|
///
|
2018-10-06 13:25:17 +00:00
|
|
|
/// In this example, `T` can be any type, as long as it implements `Responder`.
|
2016-11-03 14:09:01 +00:00
|
|
|
///
|
2016-12-15 08:47:31 +00:00
|
|
|
/// # Return Value
|
2016-11-03 14:09:01 +00:00
|
|
|
///
|
2016-12-20 04:40:21 +00:00
|
|
|
/// A `Responder` returns an `Ok(Response)` or an `Err(Status)`:
|
2016-11-03 14:09:01 +00:00
|
|
|
///
|
2016-12-20 04:40:21 +00:00
|
|
|
/// * An `Ok` variant means that the `Responder` was successful in generating
|
|
|
|
/// a `Response`. The `Response` will be written out to the client.
|
2016-11-03 14:09:01 +00:00
|
|
|
///
|
2016-12-20 04:40:21 +00:00
|
|
|
/// * An `Err` variant means that the `Responder` could not or did not
|
|
|
|
/// generate a `Response`. The contained `Status` will be used to find the
|
|
|
|
/// relevant error catcher which then generates an error response.
|
2016-11-03 14:09:01 +00:00
|
|
|
///
|
2016-11-03 16:05:41 +00:00
|
|
|
/// # Provided Implementations
|
|
|
|
///
|
|
|
|
/// Rocket implements `Responder` for several standard library types. Their
|
|
|
|
/// behavior is documented here. Note that the `Result` implementation is
|
|
|
|
/// overloaded, allowing for two `Responder`s to be used at once, depending on
|
|
|
|
/// the variant.
|
|
|
|
///
|
2016-12-15 08:47:31 +00:00
|
|
|
/// * **&str**
|
2016-11-03 16:05:41 +00:00
|
|
|
///
|
2016-12-20 04:40:21 +00:00
|
|
|
/// Sets the `Content-Type` to `text/plain`. The string is used as the body
|
2016-12-15 08:47:31 +00:00
|
|
|
/// of the response, which is fixed size and not streamed. To stream a raw
|
|
|
|
/// string, use `Stream::from(Cursor::new(string))`.
|
2016-11-03 16:05:41 +00:00
|
|
|
///
|
2016-12-15 08:47:31 +00:00
|
|
|
/// * **String**
|
2016-11-03 16:05:41 +00:00
|
|
|
///
|
2017-09-22 01:48:39 +00:00
|
|
|
/// Sets the `Content-Type` to `text/plain`. The string is used as the body
|
2016-12-15 08:47:31 +00:00
|
|
|
/// of the response, which is fixed size and not streamed. To stream a
|
|
|
|
/// string, use `Stream::from(Cursor::new(string))`.
|
2016-11-03 16:05:41 +00:00
|
|
|
///
|
2018-07-14 20:48:56 +00:00
|
|
|
/// * **&\[u8\]**
|
|
|
|
///
|
|
|
|
/// Sets the `Content-Type` to `application/octet-stream`. The slice
|
|
|
|
/// is used as the body of the response, which is fixed size and not
|
|
|
|
/// streamed. To stream a slice of bytes, use
|
|
|
|
/// `Stream::from(Cursor::new(data))`.
|
|
|
|
///
|
|
|
|
/// * **Vec<u8>**
|
2017-09-22 01:48:39 +00:00
|
|
|
///
|
|
|
|
/// Sets the `Content-Type` to `application/octet-stream`. The vector's data
|
|
|
|
/// is used as the body of the response, which is fixed size and not
|
|
|
|
/// streamed. To stream a vector of bytes, use
|
|
|
|
/// `Stream::from(Cursor::new(vec))`.
|
|
|
|
///
|
2016-12-15 08:47:31 +00:00
|
|
|
/// * **File**
|
2016-11-03 16:05:41 +00:00
|
|
|
///
|
2017-07-04 08:34:43 +00:00
|
|
|
/// Responds with a streamed body containing the data in the `File`. No
|
2017-05-19 10:29:08 +00:00
|
|
|
/// `Content-Type` is set. To automatically have a `Content-Type` set based
|
2019-06-13 01:48:02 +00:00
|
|
|
/// on the file's extension, use [`NamedFile`](crate::response::NamedFile).
|
2016-11-03 16:05:41 +00:00
|
|
|
///
|
2016-12-20 04:40:21 +00:00
|
|
|
/// * **()**
|
2016-12-10 03:53:13 +00:00
|
|
|
///
|
2017-05-19 10:29:08 +00:00
|
|
|
/// Responds with an empty body. No `Content-Type` is set.
|
2016-12-10 03:53:13 +00:00
|
|
|
///
|
2016-12-15 08:47:31 +00:00
|
|
|
/// * **Option<T>**
|
2016-11-03 16:05:41 +00:00
|
|
|
///
|
|
|
|
/// If the `Option` is `Some`, the wrapped responder is used to respond to
|
2016-12-20 04:40:21 +00:00
|
|
|
/// the client. Otherwise, an `Err` with status **404 Not Found** is
|
|
|
|
/// returned and a warning is printed to the console.
|
2016-11-03 16:05:41 +00:00
|
|
|
///
|
2016-12-15 08:47:31 +00:00
|
|
|
/// * **Result<T, E>** _where_ **E: Debug**
|
2016-11-03 16:05:41 +00:00
|
|
|
///
|
|
|
|
/// If the `Result` is `Ok`, the wrapped responder is used to respond to the
|
2016-12-15 08:47:31 +00:00
|
|
|
/// client. Otherwise, an `Err` with status **500 Internal Server Error** is
|
|
|
|
/// returned and the error is printed to the console using the `Debug`
|
2016-11-03 16:05:41 +00:00
|
|
|
/// implementation.
|
|
|
|
///
|
2016-12-15 08:47:31 +00:00
|
|
|
/// * **Result<T, E>** _where_ **E: Debug + Responder**
|
2016-11-03 16:05:41 +00:00
|
|
|
///
|
|
|
|
/// If the `Result` is `Ok`, the wrapped `Ok` responder is used to respond
|
2016-12-15 08:47:31 +00:00
|
|
|
/// to the client. If the `Result` is `Err`, the wrapped `Err` responder is
|
2016-11-03 16:05:41 +00:00
|
|
|
/// used to respond to the client.
|
|
|
|
///
|
2016-11-03 14:09:01 +00:00
|
|
|
/// # Implementation Tips
|
|
|
|
///
|
|
|
|
/// This section describes a few best practices to take into account when
|
|
|
|
/// implementing `Responder`.
|
|
|
|
///
|
|
|
|
/// ## Debug
|
|
|
|
///
|
|
|
|
/// A type implementing `Responder` should implement the `Debug` trait when
|
|
|
|
/// possible. This is because the `Responder` implementation for `Result`
|
|
|
|
/// requires its `Err` type to implement `Debug`. Therefore, a type implementing
|
|
|
|
/// `Debug` can more easily be composed.
|
|
|
|
///
|
2016-12-15 08:47:31 +00:00
|
|
|
/// ## Joining and Merging
|
2016-11-03 14:09:01 +00:00
|
|
|
///
|
2016-12-15 08:47:31 +00:00
|
|
|
/// When chaining/wrapping other `Responder`s, use the
|
2018-10-06 13:25:17 +00:00
|
|
|
/// [`merge()`](Response::merge()) or [`join()`](Response::join()) methods on
|
|
|
|
/// the `Response` or `ResponseBuilder` struct. Ensure that you document the
|
|
|
|
/// merging or joining behavior appropriately.
|
2016-12-10 04:59:58 +00:00
|
|
|
///
|
2017-05-19 10:29:08 +00:00
|
|
|
/// ## Inspecting Requests
|
|
|
|
///
|
|
|
|
/// A `Responder` has access to the request it is responding to. Even so, you
|
|
|
|
/// should avoid using the `Request` value as much as possible. This is because
|
2018-07-12 03:44:09 +00:00
|
|
|
/// using the `Request` object makes your responder _impure_, and so the use of
|
2017-05-19 10:29:08 +00:00
|
|
|
/// the type as a `Responder` has less intrinsic meaning associated with it. If
|
2018-07-12 03:44:09 +00:00
|
|
|
/// the `Responder` were pure, however, it would always respond in the same manner,
|
2017-05-19 10:29:08 +00:00
|
|
|
/// regardless of the incoming request. Thus, knowing the type is sufficient to
|
|
|
|
/// fully determine its functionality.
|
|
|
|
///
|
2016-12-10 04:59:58 +00:00
|
|
|
/// # Example
|
|
|
|
///
|
|
|
|
/// Say that you have a custom type, `Person`:
|
|
|
|
///
|
|
|
|
/// ```rust
|
2017-02-02 10:16:21 +00:00
|
|
|
///
|
|
|
|
/// # #[allow(dead_code)]
|
2016-12-10 04:59:58 +00:00
|
|
|
/// struct Person {
|
|
|
|
/// name: String,
|
|
|
|
/// age: u16
|
|
|
|
/// }
|
|
|
|
/// ```
|
|
|
|
///
|
|
|
|
/// You'd like to use `Person` as a `Responder` so that you can return a
|
|
|
|
/// `Person` directly from a handler:
|
|
|
|
///
|
|
|
|
/// ```rust,ignore
|
|
|
|
/// #[get("/person/<id>")]
|
|
|
|
/// fn person(id: usize) -> Option<Person> {
|
|
|
|
/// Person::from_id(id)
|
|
|
|
/// }
|
|
|
|
/// ```
|
|
|
|
///
|
|
|
|
/// You want the `Person` responder to set two header fields: `X-Person-Name`
|
|
|
|
/// and `X-Person-Age` as well as supply a custom representation of the object
|
|
|
|
/// (`Content-Type: application/x-person`) in the body of the response. The
|
|
|
|
/// following `Responder` implementation accomplishes this:
|
|
|
|
///
|
|
|
|
/// ```rust
|
2019-08-20 23:53:00 +00:00
|
|
|
/// # #![feature(proc_macro_hygiene)]
|
2018-09-20 04:14:30 +00:00
|
|
|
/// # #[macro_use] extern crate rocket;
|
2016-12-21 02:07:14 +00:00
|
|
|
/// #
|
2016-12-10 04:59:58 +00:00
|
|
|
/// # #[derive(Debug)]
|
|
|
|
/// # struct Person { name: String, age: u16 }
|
|
|
|
/// #
|
2016-12-15 08:47:31 +00:00
|
|
|
/// use std::io::Cursor;
|
2016-12-10 04:59:58 +00:00
|
|
|
///
|
2017-05-19 10:29:08 +00:00
|
|
|
/// use rocket::request::Request;
|
2016-12-15 08:47:31 +00:00
|
|
|
/// use rocket::response::{self, Response, Responder};
|
2016-12-10 04:59:58 +00:00
|
|
|
/// use rocket::http::ContentType;
|
|
|
|
///
|
2019-08-14 16:30:59 +00:00
|
|
|
/// impl<'r> Responder<'r> for Person {
|
2019-08-07 00:08:00 +00:00
|
|
|
/// fn respond_to(self, _: &'r Request) -> response::ResultFuture<'r> {
|
|
|
|
/// Box::pin(async move {
|
|
|
|
/// Response::build()
|
|
|
|
/// .sized_body(Cursor::new(format!("{}:{}", self.name, self.age)))
|
|
|
|
/// .raw_header("X-Person-Name", self.name)
|
|
|
|
/// .raw_header("X-Person-Age", self.age.to_string())
|
|
|
|
/// .header(ContentType::new("application", "x-person"))
|
|
|
|
/// .ok()
|
|
|
|
/// })
|
2016-12-10 04:59:58 +00:00
|
|
|
/// }
|
|
|
|
/// }
|
2016-12-21 08:09:22 +00:00
|
|
|
/// #
|
2016-12-21 02:07:14 +00:00
|
|
|
/// # #[get("/person")]
|
|
|
|
/// # fn person() -> Person { Person { name: "a".to_string(), age: 20 } }
|
|
|
|
/// # fn main() { }
|
2016-12-10 04:59:58 +00:00
|
|
|
/// ```
|
2016-12-15 08:47:31 +00:00
|
|
|
pub trait Responder<'r> {
|
2016-12-20 21:40:02 +00:00
|
|
|
/// Returns `Ok` if a `Response` could be generated successfully. Otherwise,
|
|
|
|
/// returns an `Err` with a failing `Status`.
|
2016-11-03 14:09:01 +00:00
|
|
|
///
|
2017-05-19 10:29:08 +00:00
|
|
|
/// The `request` parameter is the `Request` that this `Responder` is
|
|
|
|
/// responding to.
|
|
|
|
///
|
2016-12-20 21:40:02 +00:00
|
|
|
/// When using Rocket's code generation, if an `Ok(Response)` is returned,
|
|
|
|
/// the response will be written out to the client. If an `Err(Status)` is
|
|
|
|
/// returned, the error catcher for the given status is retrieved and called
|
|
|
|
/// to generate a final error response, which is then written out to the
|
|
|
|
/// client.
|
2019-07-24 15:21:52 +00:00
|
|
|
fn respond_to(self, request: &'r Request<'_>) -> response::ResultFuture<'r>;
|
2016-03-28 09:34:09 +00:00
|
|
|
}
|
|
|
|
|
2016-12-20 21:40:02 +00:00
|
|
|
/// Returns a response with Content-Type `text/plain` and a fixed-size body
|
|
|
|
/// containing the string `self`. Always returns `Ok`.
|
2016-12-15 08:47:31 +00:00
|
|
|
impl<'r> Responder<'r> for &'r str {
|
2019-07-24 15:21:52 +00:00
|
|
|
fn respond_to(self, _: &Request<'_>) -> response::ResultFuture<'r> {
|
|
|
|
Box::pin(async move {
|
|
|
|
Response::build()
|
|
|
|
.header(ContentType::Plain)
|
|
|
|
.sized_body(Cursor::new(self))
|
|
|
|
.ok()
|
|
|
|
})
|
2016-03-28 09:34:09 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-04-14 07:43:24 +00:00
|
|
|
/// Returns a response with Content-Type `text/plain` and a fixed-size body
|
2016-12-20 21:40:02 +00:00
|
|
|
/// containing the string `self`. Always returns `Ok`.
|
2019-06-13 01:48:02 +00:00
|
|
|
impl Responder<'_> for String {
|
2019-07-24 15:21:52 +00:00
|
|
|
fn respond_to(self, _: &Request<'_>) -> response::ResultFuture<'static> {
|
|
|
|
Box::pin(async move {
|
|
|
|
Response::build()
|
|
|
|
.header(ContentType::Plain)
|
|
|
|
.sized_body(Cursor::new(self))
|
|
|
|
.ok()
|
|
|
|
})
|
2016-03-28 09:34:09 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-07-14 20:48:56 +00:00
|
|
|
/// Returns a response with Content-Type `application/octet-stream` and a
|
|
|
|
/// fixed-size body containing the data in `self`. Always returns `Ok`.
|
|
|
|
impl<'r> Responder<'r> for &'r [u8] {
|
2019-07-24 15:21:52 +00:00
|
|
|
fn respond_to(self, _: &Request<'_>) -> response::ResultFuture<'r> {
|
|
|
|
Box::pin(async move {
|
|
|
|
Response::build()
|
|
|
|
.header(ContentType::Binary)
|
|
|
|
.sized_body(Cursor::new(self))
|
|
|
|
.ok()
|
|
|
|
})
|
2018-07-14 20:48:56 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-09-22 01:48:39 +00:00
|
|
|
/// Returns a response with Content-Type `application/octet-stream` and a
|
|
|
|
/// fixed-size body containing the data in `self`. Always returns `Ok`.
|
2019-06-13 01:48:02 +00:00
|
|
|
impl Responder<'_> for Vec<u8> {
|
2019-07-24 15:21:52 +00:00
|
|
|
fn respond_to(self, _: &Request<'_>) -> response::ResultFuture<'static> {
|
|
|
|
Box::pin(async move {
|
|
|
|
Response::build()
|
|
|
|
.header(ContentType::Binary)
|
|
|
|
.sized_body(Cursor::new(self))
|
|
|
|
.ok()
|
|
|
|
})
|
2017-09-22 01:48:39 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-05-19 10:29:08 +00:00
|
|
|
/// Returns a response with a sized body for the file. Always returns `Ok`.
|
2019-06-13 01:48:02 +00:00
|
|
|
impl Responder<'_> for File {
|
2019-07-24 15:21:52 +00:00
|
|
|
fn respond_to(self, _: &Request<'_>) -> response::ResultFuture<'static> {
|
|
|
|
Box::pin(async move {
|
2019-09-22 22:48:08 +00:00
|
|
|
let file = tokio::fs::File::from(self);
|
2019-08-29 01:32:32 +00:00
|
|
|
let metadata = file.metadata().await;
|
|
|
|
let stream = BufReader::new(file);
|
2019-07-24 15:21:52 +00:00
|
|
|
match metadata {
|
|
|
|
Ok(md) => Response::build().raw_body(Body::Sized(stream, md.len())).ok(),
|
|
|
|
Err(_) => Response::build().streamed_body(stream).ok()
|
|
|
|
}
|
|
|
|
})
|
2016-03-28 09:34:09 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2016-12-20 21:40:02 +00:00
|
|
|
/// Returns an empty, default `Response`. Always returns `Ok`.
|
2019-06-13 01:48:02 +00:00
|
|
|
impl Responder<'_> for () {
|
2019-07-24 15:21:52 +00:00
|
|
|
fn respond_to(self, _: &Request<'_>) -> response::ResultFuture<'static> {
|
|
|
|
Box::pin(async move {
|
|
|
|
Ok(Response::new())
|
|
|
|
})
|
2016-12-10 03:53:13 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2016-12-20 21:40:02 +00:00
|
|
|
/// If `self` is `Some`, responds with the wrapped `Responder`. Otherwise prints
|
|
|
|
/// a warning message and returns an `Err` of `Status::NotFound`.
|
2019-07-24 15:21:52 +00:00
|
|
|
impl<'r, R: Responder<'r> + Send + 'r> Responder<'r> for Option<R> {
|
|
|
|
fn respond_to(self, req: &'r Request<'_>) -> response::ResultFuture<'r> {
|
2019-09-06 16:56:06 +00:00
|
|
|
match self {
|
|
|
|
Some(r) => r.respond_to(req),
|
|
|
|
None => {
|
|
|
|
warn_!("Response was `None`.");
|
2019-09-22 22:48:08 +00:00
|
|
|
Box::pin(ready(Err(Status::NotFound)))
|
2019-09-06 16:56:06 +00:00
|
|
|
},
|
|
|
|
}
|
2016-03-28 09:34:09 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2016-12-20 21:40:02 +00:00
|
|
|
/// Responds with the wrapped `Responder` in `self`, whether it is `Ok` or
|
|
|
|
/// `Err`.
|
2019-07-24 15:21:52 +00:00
|
|
|
impl<'r, R: Responder<'r> + Send + 'r, E: Responder<'r> + Send + 'r> Responder<'r> for Result<R, E> {
|
|
|
|
fn respond_to(self, req: &'r Request<'_>) -> response::ResultFuture<'r> {
|
2019-09-06 16:56:06 +00:00
|
|
|
match self {
|
|
|
|
Ok(responder) => responder.respond_to(req),
|
|
|
|
Err(responder) => responder.respond_to(req),
|
|
|
|
}
|
2016-03-28 09:34:09 +00:00
|
|
|
}
|
|
|
|
}
|
2018-10-31 10:51:45 +00:00
|
|
|
|
|
|
|
/// The response generated by `Status` depends on the status code itself. The
|
|
|
|
/// table below summarizes the functionality:
|
|
|
|
///
|
|
|
|
/// | Status Code Range | Response |
|
|
|
|
/// |-------------------|---------------------------------------|
|
|
|
|
/// | [400, 599] | Forwards to catcher for given status. |
|
|
|
|
/// | 100, [200, 205] | Empty with status of `self`. |
|
|
|
|
/// | All others. | Invalid. Errors to `500` catcher. |
|
|
|
|
///
|
|
|
|
/// In short, a client or server error status codes will forward to the
|
|
|
|
/// corresponding error catcher, a successful status code less than `206` or
|
|
|
|
/// `100` responds with any empty body and the given status code, and all other
|
|
|
|
/// status code emit an error message and forward to the `500` (internal server
|
|
|
|
/// error) catcher.
|
2019-07-24 15:21:52 +00:00
|
|
|
impl<'r> Responder<'r> for Status {
|
|
|
|
fn respond_to(self, _: &'r Request<'_>) -> response::ResultFuture<'r> {
|
|
|
|
Box::pin(async move {
|
|
|
|
match self.class() {
|
|
|
|
StatusClass::ClientError | StatusClass::ServerError => Err(self),
|
|
|
|
StatusClass::Success if self.code < 206 => {
|
|
|
|
Response::build().status(self).ok()
|
|
|
|
}
|
|
|
|
StatusClass::Informational if self.code == 100 => {
|
|
|
|
Response::build().status(self).ok()
|
|
|
|
}
|
|
|
|
_ => {
|
|
|
|
error_!("Invalid status used as responder: {}.", self);
|
|
|
|
warn_!("Fowarding to 500 (Internal Server Error) catcher.");
|
|
|
|
Err(Status::InternalServerError)
|
|
|
|
}
|
2018-10-31 10:51:45 +00:00
|
|
|
}
|
2019-07-24 15:21:52 +00:00
|
|
|
})
|
2018-10-31 10:51:45 +00:00
|
|
|
}
|
|
|
|
}
|