Rocket: Simple way to manually set response content-type

Created on 9 Feb 2017  路  6Comments  路  Source: SergioBenitez/Rocket

Is there a _simple_ way to manually set the content-type of a response?
Example

#[get("/foo")]
fn foo() -> String {
  ...
}

This, as expected, always responds with "text/plain". However, I need it to be "application/json".
I can not return JSON<...>, because I only have a JSON string, and its structure is _not known_ at compile time.

What would you suggest?

question

Most helpful comment

@mehcode's code is _almost_ the recommended approach. Here's what the guide and API docs recommend:

use rocket::response::content;

#[get("/foo")]
fn foo() -> content::JSON<String> {
  content::JSON(some_string)
}

This is cleaner and clearer as the type shows the intended content type.

By the way, if it feels like you're doing a lot of work for something that you feel is very common, there's almost certainly a very easy way to do it in Rocket. The documentation (guide, API docs, examples) should point it out. And if there isn't a way, then asking is definitely the right way to go. :)

All 6 comments

Answering my own question. Feel free to improve, correct, etc.

struct JsonString(String);
impl Responder<'static> for JsonString {
    fn respond(self) -> rocket::response::Result<'static> {
        rocket::response::content::JSON(self.0).respond()
    }
}

trait JsonStringConversion {
    fn to_json_string(&self) -> JsonString;
}
impl JsonStringConversion for String {
    fn to_json_string(&self) -> JsonString {
        JsonString(self.clone())
    }
}

#[get("/foo")]
fn foo() -> JsonString {
 some_string.to_json_string()
}

@fivethousand Are you trying to forward a string from some service or do dynamic construction?

I have to forward a string from some services, exactly.
Everything is dynamic (I don't even know the services at compile time), so I cannot do much more, right?

Don't use this if you do know the structure at compile time.

use rocket::response::content::Content;
use rocket::http::ContentType;

#[get("/foo")]
fn foo() -> Content<String> {
  Content(ContentType::JSON, some_string)
}

@mehcode's code is _almost_ the recommended approach. Here's what the guide and API docs recommend:

use rocket::response::content;

#[get("/foo")]
fn foo() -> content::JSON<String> {
  content::JSON(some_string)
}

This is cleaner and clearer as the type shows the intended content type.

By the way, if it feels like you're doing a lot of work for something that you feel is very common, there's almost certainly a very easy way to do it in Rocket. The documentation (guide, API docs, examples) should point it out. And if there isn't a way, then asking is definitely the right way to go. :)

That's exactly why I asked: I couldn't find it in the docs and my approach - well... ;-)

Thanks!

Was this page helpful?
0 / 5 - 0 ratings