Trait rocket::response::Responder[][src]

pub trait Responder<'r, 'o: 'r> {
    fn respond_to(self, request: &'r Request<'_>) -> Result<'o>;
}
Expand description

Trait implemented by types that generate responses for clients.

Types that implement this trait can be used as the return type of a handler, as illustrated below with T:

#[get("/")]
fn index() -> T { /* ... */ }

In this example, T can be any type, as long as it implements Responder.

Return Value

A Responder returns a Future whose output type is an Ok(Response) or an Err(Status):

  • An Ok variant means that the Responder was successful in generating a Response. The Response will be written out to the client.

  • 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.

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 Responders to be used at once, depending on the variant.

  • &str

    Sets the Content-Type to text/plain. The string is used as the body of the response, which is fixed size and not streamed. To stream a raw string, use Stream::from(Cursor::new(string)).

  • String

    Sets the Content-Type to text/plain. The string is used as the body of the response, which is fixed size and not streamed. To stream a string, use Stream::from(Cursor::new(string)).

  • &[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>

    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)).

  • File

    Responds with a streamed body containing the data in the File. No Content-Type is set. To automatically have a Content-Type set based on the file’s extension, use NamedFile.

  • ()

    Responds with an empty body. No Content-Type is set.

  • Option<T>

    If the Option is Some, the wrapped responder is used to respond to the client. Otherwise, an Err with status 404 Not Found is returned and a warning is printed to the console.

  • Result<T, E>

    If the Result is Ok, the wrapped Ok responder is used to respond to the client. If the Result is Err, the wrapped Err responder is used to respond to the client.

Implementation Tips

This section describes a few best practices to take into account when implementing Responder.

Joining and Merging

When chaining/wrapping other Responders, use the merge() or join() methods on the Response or ResponseBuilder struct. Ensure that you document the merging or joining behavior appropriately.

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 using the Request object makes your responder impure, and so the use of the type as a Responder has less intrinsic meaning associated with it. If the Responder were pure, however, it would always respond in the same manner, regardless of the incoming request. Thus, knowing the type is sufficient to fully determine its functionality.

Lifetimes

Responder has two lifetimes: Responder<'r, 'o: 'r>. The first lifetime, 'r, refers to the reference to the &'r Request, while the second lifetime refers to the returned Response<'o>. The bound 'o: 'r allows 'o to be any lifetime that lives at least as long as the Request. In particular, this includes borrows from the Request itself (where 'o would be 'r as in impl<'r> Responder<'r, 'r>) as well as 'static data (where 'o would be 'static as in impl<'r> Responder<'r, 'static>).

Example

Say that you have a custom type, Person:

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:

#[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:

use std::io::Cursor;

use rocket::request::Request;
use rocket::response::{self, Response, Responder};
use rocket::http::ContentType;

impl<'r> Responder<'r, 'static> for Person {
    fn respond_to(self, _: &'r Request<'_>) -> response::Result<'static> {
        let person_string = format!("{}:{}", self.name, self.age);
        Response::build()
            .sized_body(person_string.len(), Cursor::new(person_string))
            .raw_header("X-Person-Name", self.name)
            .raw_header("X-Person-Age", self.age.to_string())
            .header(ContentType::new("application", "x-person"))
            .ok()
    }
}

Required methods

fn respond_to(self, request: &'r Request<'_>) -> Result<'o>[src]

Returns Ok if a Response could be generated successfully. Otherwise, returns an Err with a failing Status.

The request parameter is the Request that this Responder is responding to.

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.

Implementations on Foreign Types

impl<'r, 'o: 'r> Responder<'r, 'o> for &'o str[src]

Returns a response with Content-Type text/plain and a fixed-size body containing the string self. Always returns Ok.

fn respond_to(self, _: &'r Request<'_>) -> Result<'o>[src]

impl<'r> Responder<'r, 'static> for String[src]

Returns a response with Content-Type text/plain and a fixed-size body containing the string self. Always returns Ok.

fn respond_to(self, _: &'r Request<'_>) -> Result<'static>[src]

impl<'r, 'o: 'r> Responder<'r, 'o> for &'o [u8][src]

Returns a response with Content-Type application/octet-stream and a fixed-size body containing the data in self. Always returns Ok.

fn respond_to(self, _: &'r Request<'_>) -> Result<'o>[src]

impl<'r> Responder<'r, 'static> for Vec<u8>[src]

Returns a response with Content-Type application/octet-stream and a fixed-size body containing the data in self. Always returns Ok.

fn respond_to(self, _: &'r Request<'_>) -> Result<'static>[src]

impl<'r> Responder<'r, 'static> for File[src]

Returns a response with a sized body for the file. Always returns Ok.

fn respond_to(self, req: &'r Request<'_>) -> Result<'static>[src]

impl<'r> Responder<'r, 'static> for File[src]

Returns a response with a sized body for the file. Always returns Ok.

fn respond_to(self, _: &'r Request<'_>) -> Result<'static>[src]

impl<'r> Responder<'r, 'static> for ()[src]

Returns an empty, default Response. Always returns Ok.

fn respond_to(self, _: &'r Request<'_>) -> Result<'static>[src]

impl<'r, 'o: 'r, R: ?Sized + ToOwned> Responder<'r, 'o> for Cow<'o, R> where
    &'o R: Responder<'r, 'o> + 'o,
    <R as ToOwned>::Owned: Responder<'r, 'o> + 'r, 
[src]

Responds with the inner Responder in Cow.

fn respond_to(self, req: &'r Request<'_>) -> Result<'o>[src]

impl<'r, 'o: 'r, R: Responder<'r, 'o>> Responder<'r, 'o> for Option<R>[src]

If self is Some, responds with the wrapped Responder. Otherwise prints a warning message and returns an Err of Status::NotFound.

fn respond_to(self, req: &'r Request<'_>) -> Result<'o>[src]

impl<'r, 'o: 'r, 't: 'o, 'e: 'o, T, E> Responder<'r, 'o> for Result<T, E> where
    T: Responder<'r, 't>,
    E: Responder<'r, 'e>, 
[src]

Err.

fn respond_to(self, req: &'r Request<'_>) -> Result<'o>[src]

impl<'r, 'o: 'r, 't: 'o, 'e: 'o, T, E> Responder<'r, 'o> for Either<T, E> where
    T: Responder<'r, 't>,
    E: Responder<'r, 'e>, 
[src]

Right.

fn respond_to(self, req: &'r Request<'_>) -> Result<'o>[src]

impl<'r> Responder<'r, 'static> for Error[src]

Prints a warning with the error and forwards to the 500 error catcher.

fn respond_to(self, _: &'r Request<'_>) -> Result<'static>[src]

impl<'r, 'o: 'r, R: Responder<'r, 'o>> Responder<'r, 'o> for (ContentType, R)[src]

fn respond_to(self, request: &'r Request<'_>) -> Result<'o>[src]

impl<'r, 'o: 'r, R: Responder<'r, 'o>> Responder<'r, 'o> for (Status, R)[src]

fn respond_to(self, request: &'r Request<'_>) -> Result<'o>[src]

Implementors

impl<'r> Responder<'r, 'static> for Value[src]

This is supported on crate feature json only.

Serializes the value into JSON. Returns a response with Content-Type JSON and a fixed-size body with the serialized value.

fn respond_to(self, req: &'r Request<'_>) -> Result<'static>[src]

impl<'r> Responder<'r, 'static> for NamedFile[src]

Streams the named file to the client. Sets or overrides the Content-Type in the response according to the file’s extension if the extension is recognized. See ContentType::from_extension() for more information. If you would like to stream a file with a different Content-Type than that implied by its extension, use a File directly.

fn respond_to(self, req: &'r Request<'_>) -> Result<'static>[src]

impl<'r> Responder<'r, 'static> for Status[src]

The response generated by Status depends on the status code itself. The table below summarizes the functionality:

Status Code RangeResponse
[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.

fn respond_to(self, _: &'r Request<'_>) -> Result<'static>[src]

impl<'r> Responder<'r, 'static> for NoContent[src]

Sets the status code of the response to 204 No Content.

fn respond_to(self, _: &'r Request<'_>) -> Result<'static>[src]

impl<'r> Responder<'r, 'static> for Redirect[src]

Constructs a response with the appropriate status code and the given URL in the Location header field. The body of the response is empty. If the URI value used to create the Responder is an invalid URI, an error of Status::InternalServerError is returned.

fn respond_to(self, _: &'r Request<'_>) -> Result<'static>[src]

impl<'r, 'o: 'r, R: Responder<'r, 'o>> Responder<'r, 'o> for Css<R>[src]

Sets the Content-Type of the response then delegates the remainder of the response to the wrapped responder.

fn respond_to(self, req: &'r Request<'_>) -> Result<'o>[src]

impl<'r, 'o: 'r, R: Responder<'r, 'o>> Responder<'r, 'o> for rocket::response::content::Custom<R>[src]

Overrides the Content-Type of the response to the wrapped ContentType then delegates the remainder of the response to the wrapped responder.

fn respond_to(self, req: &'r Request<'_>) -> Result<'o>[src]

impl<'r, 'o: 'r, R: Responder<'r, 'o>> Responder<'r, 'o> for Html<R>[src]

Sets the Content-Type of the response then delegates the remainder of the response to the wrapped responder.

fn respond_to(self, req: &'r Request<'_>) -> Result<'o>[src]

impl<'r, 'o: 'r, R: Responder<'r, 'o>> Responder<'r, 'o> for JavaScript<R>[src]

Sets the Content-Type of the response then delegates the remainder of the response to the wrapped responder.

fn respond_to(self, req: &'r Request<'_>) -> Result<'o>[src]

impl<'r, 'o: 'r, R: Responder<'r, 'o>> Responder<'r, 'o> for rocket::response::content::Json<R>[src]

Sets the Content-Type of the response then delegates the remainder of the response to the wrapped responder.

fn respond_to(self, req: &'r Request<'_>) -> Result<'o>[src]

impl<'r, 'o: 'r, R: Responder<'r, 'o>> Responder<'r, 'o> for rocket::response::content::MsgPack<R>[src]

Sets the Content-Type of the response then delegates the remainder of the response to the wrapped responder.

fn respond_to(self, req: &'r Request<'_>) -> Result<'o>[src]

impl<'r, 'o: 'r, R: Responder<'r, 'o>> Responder<'r, 'o> for Plain<R>[src]

Sets the Content-Type of the response then delegates the remainder of the response to the wrapped responder.

fn respond_to(self, req: &'r Request<'_>) -> Result<'o>[src]

impl<'r, 'o: 'r, R: Responder<'r, 'o>> Responder<'r, 'o> for Xml<R>[src]

Sets the Content-Type of the response then delegates the remainder of the response to the wrapped responder.

fn respond_to(self, req: &'r Request<'_>) -> Result<'o>[src]

impl<'r, 'o: 'r, R: Responder<'r, 'o>> Responder<'r, 'o> for Accepted<R>[src]

Sets the status code of the response to 202 Accepted. If the responder is Some, it is used to finalize the response.

fn respond_to(self, req: &'r Request<'_>) -> Result<'o>[src]

impl<'r, 'o: 'r, R: Responder<'r, 'o>> Responder<'r, 'o> for BadRequest<R>[src]

Sets the status code of the response to 400 Bad Request. If the responder is Some, it is used to finalize the response.

fn respond_to(self, req: &'r Request<'_>) -> Result<'o>[src]

impl<'r, 'o: 'r, R: Responder<'r, 'o>> Responder<'r, 'o> for Conflict<R>[src]

Sets the status code of the response to 409 Conflict. If the responder is Some, it is used to finalize the response.

fn respond_to(self, req: &'r Request<'_>) -> Result<'o>[src]

impl<'r, 'o: 'r, R: Responder<'r, 'o>> Responder<'r, 'o> for Created<R>[src]

Sets the status code of the response to 201 Created. Sets the Location header to the parameter in the Created::new() constructor.

The optional responder, set via Created::body() or Created::tagged_body() finalizes the response if it exists. The wrapped responder should write the body of the response so that it contains information about the created resource. If no responder is provided, the response body will be empty.

In addition to setting the status code, Location header, and finalizing the response with the Responder, the ETag header is set conditionally if a hashable Responder is provided via Created::tagged_body(). The ETag header is set to a hash value of the responder.

fn respond_to(self, req: &'r Request<'_>) -> Result<'o>[src]

impl<'r, 'o: 'r, R: Responder<'r, 'o>> Responder<'r, 'o> for rocket::response::status::Custom<R>[src]

Sets the status code of the response and then delegates the remainder of the response to the wrapped responder.

fn respond_to(self, req: &'r Request<'_>) -> Result<'o>[src]

impl<'r, 'o: 'r, R: Responder<'r, 'o>> Responder<'r, 'o> for Forbidden<R>[src]

Sets the status code of the response to 403 Forbidden. If the responder is Some, it is used to finalize the response.

fn respond_to(self, req: &'r Request<'_>) -> Result<'o>[src]

impl<'r, 'o: 'r, R: Responder<'r, 'o>> Responder<'r, 'o> for NotFound<R>[src]

Sets the status code of the response to 404 Not Found.

fn respond_to(self, req: &'r Request<'_>) -> Result<'o>[src]

impl<'r, 'o: 'r, R: Responder<'r, 'o>> Responder<'r, 'o> for Unauthorized<R>[src]

Sets the status code of the response to 401 Unauthorized. If the responder is Some, it is used to finalize the response.

fn respond_to(self, req: &'r Request<'_>) -> Result<'o>[src]

impl<'r, 'o: 'r, R: Responder<'r, 'o>> Responder<'r, 'o> for Flash<R>[src]

Sets the message cookie and then uses the wrapped responder to complete the response. In other words, simply sets a cookie and delegates the rest of the response handling to the wrapped responder. As a result, the Outcome of the response is the Outcome of the wrapped Responder.

fn respond_to(self, req: &'r Request<'_>) -> Result<'o>[src]

impl<'r, 'o: 'r, T: Responder<'r, 'o>> Responder<'r, 'o> for Capped<T>[src]

fn respond_to(self, request: &'r Request<'_>) -> Result<'o>[src]

impl<'r, E: Debug> Responder<'r, 'static> for Debug<E>[src]

fn respond_to(self, _: &'r Request<'_>) -> Result<'static>[src]

impl<'r, S: Stream> Responder<'r, 'r> for ByteStream<S> where
    S: Send + 'r,
    S::Item: AsRef<[u8]> + Send + Unpin + 'r, 
[src]

fn respond_to(self, _: &'r Request<'_>) -> Result<'r>[src]

impl<'r, S: Stream> Responder<'r, 'r> for ReaderStream<S> where
    S: Send + 'r,
    S::Item: AsyncRead + Send
[src]

fn respond_to(self, _: &'r Request<'_>) -> Result<'r>[src]

impl<'r, S: Stream> Responder<'r, 'r> for TextStream<S> where
    S: Send + 'r,
    S::Item: AsRef<str> + Send + Unpin + 'r, 
[src]

fn respond_to(self, _: &'r Request<'_>) -> Result<'r>[src]

impl<'r, S: Stream<Item = Event> + Send + 'r> Responder<'r, 'r> for EventStream<S>[src]

fn respond_to(self, _: &'r Request<'_>) -> Result<'r>[src]

impl<'r, T: Serialize> Responder<'r, 'static> for rocket::serde::json::Json<T>[src]

This is supported on crate feature json only.

Serializes the wrapped value into JSON. Returns a response with Content-Type JSON and a fixed-size body with the serialized value. If serialization fails, an Err of Status::InternalServerError is returned.

fn respond_to(self, req: &'r Request<'_>) -> Result<'static>[src]

impl<'r, T: Serialize> Responder<'r, 'static> for rocket::serde::msgpack::MsgPack<T>[src]

This is supported on crate feature msgpack only.

Serializes the wrapped value into MessagePack. Returns a response with Content-Type MsgPack and a fixed-size body with the serialization. If serialization fails, an Err of Status::InternalServerError is returned.

fn respond_to(self, req: &'r Request<'_>) -> Result<'static>[src]