Responder

Types that implement Responder know how to generate a Response from their values. A Response includes an HTTP status, headers, and body. The body may either be fixed-sized or streaming. The given Responder implementation decides which to use. For instance, String uses a fixed-sized body, while File uses a streamed response. Responders may dynamically adjust their responses according to the incoming Request they are responding to.

Wrapping

Before we describe a few responders, we note that it is typical for responders to wrap other responders. That is, responders can be of the following form, where R is some type that implements Responder:

  1. struct WrappingResponder<R>(R);

A wrapping responder modifies the response returned by R before responding with that same response. For instance, Rocket provides Responders in the status module that override the status code of the wrapped Responder. As an example, the Accepted type sets the status to 202 - Accepted. It can be used as follows:

  1. use rocket::response::status;
  2. #[post("/<id>")]
  3. fn new(id: usize) -> status::Accepted<String> {
  4. status::Accepted(Some(format!("id: '{}'", id)))
  5. }

Similarly, the types in the content module can be used to override the Content-Type of a response. For instance, to set the Content-Type an &'static str to JSON, you can use the content::Json type as follows:

  1. use rocket::response::content;
  2. #[get("/")]
  3. fn json() -> content::Json<&'static str> {
  4. content::Json("{ 'hi': 'world' }")
  5. }

Errors

Responders may fail; they need not always generate a response. Instead, they can return an Err with a given status code. When this happens, Rocket forwards the request to the error catcher for the given status code.

If an error catcher has been registered for the given status code, Rocket will invoke it. The catcher creates and returns a response to the client. If no error catcher has been registered and the error status code is one of the standard HTTP status code, a default error catcher will be used. Default error catchers return an HTML page with the status code and description. If there is no catcher for a custom status code, Rocket uses the 500 error catcher to return a response.

While not encouraged, you can also forward a request to a catcher manually by using the Failure type. For instance, to forward to the catcher for 406 - Not Acceptable, you would write:

  1. #[get("/")]
  2. fn just_fail() -> Failure {
  3. Failure(Status::NotAcceptable)
  4. }