Creating responses
Let's implement a custom response for the User
type. In Rocket, all types that implement rocket::response::Responder
can be used as a return type in a function that handles routes.
Let's take a look at the signature of the Responder
trait. This trait requires two lifetimes, 'r
and 'o
. The result 'o
lifetime must at least be equal to the 'r
lifetime:
pub trait Responder<'r, 'o: 'r> {
fn respond_to(self, request: &'r Request<'_>) ->
Result<'o>;
}
First, we can include the required module to be used for implementing the Responder
trait for the User
struct:
use rocket::http::ContentType;
use rocket::response::{self, Responder, Response};
use std::io::Cursor;
After that, add the implementation signature for the User
struct:
impl<'r> Responder<'r, 'r> for &'r User {...