1

Say I have this route handler in rocket (v. 0.5.0-rc.1):

#[get("/route")]
pub async fn my_route() -> content::Json<String> {
    let json =
        rocket::serde::json::serde_json::to_string(&my_data).unwrap();
    content::Json(json)
}

how could I add another header (apart from content-type: application/json) to the response?

I thought of something like this, but it does not work:

#[get("/route")]
pub async fn my_route() -> content::Json<String> {
    let json =
        rocket::serde::json::serde_json::to_string(&my_data).unwrap();
    let mut content = content::Json(json);
    content.set_raw_header("Cache-Control", "max-age=120");
    content
}

I would be fine with using a raw rocket::Response and setting the content-type: application/json header myself, but I was unable to figure out how to set the body from a variable length string without running into lifetime issues.

frankenapps
  • 5,800
  • 6
  • 28
  • 69
  • In the documentation (https://rocket.rs/v0.4/guide/responses/) they say to use `use rocket::response::content; ... fn json() -> content::Json<&'static str>` – Zeppi Nov 10 '21 at 12:32

1 Answers1

0

You can get a raw response with the JSON string like so:

let json =
    rocket::serde::json::serde_json::to_string(&[1, 2, 3]).unwrap();
let response = Response::build()
    .header(ContentType::JSON)
    .raw_header("Cache-Control", "max-age=120")
    .sized_body(json.len(), Cursor::new(json))
    .finalize();
Aplet123
  • 33,825
  • 1
  • 29
  • 55
  • This lead my on the right path. I had to define a struct, implement the `Responder` trait for it and then build the response in the `respond_to(self, _request: &'r rocket::Request<'_>) -> rocket::response::Result<'static> {` function. – frankenapps Nov 10 '21 at 15:57