Search code examples
rustrust-rocket

How to add custom headers to content::JSON in Rocket?


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.


Solution

  • 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();