Iron: ContentType as Modifier


#1

I’m using Iron for some JSON API-type stuff. As part of this, I would like to do this:

let content = serde_json::to_string(&obj).unwrap();
Ok(Response::with((status::Ok, ContentType::json(), content)))

However, that doesn’t work:

lib.rs:1291:8: 1291:22 error: the trait bound `iron::header::ContentType: iron::modifier::Modifier<iron::Response>` is not satisfied [E0277]
lib.rs:1291     Ok(Response::with((status::Ok, ContentType::json(), content)))
                                                                                           ^~~~~~~~~~~~~~
lib.rs:1291:8: 1291:22 help: run `rustc --explain E0277` to see a detailed explanation
lib.rs:1291:8: 1291:22 note: required because of the requirements on the impl of `iron::modifier::Modifier<iron::Response>` for `(iron::status::StatusCode, iron::header::ContentType, std::string::String)`
lib.rs:1291:8: 1291:22 note: required by `iron::Response::with`

According to the docs, ContentType::json() returns ContentType, ContentType implements Header and HeaderFormat, and Modifier<Response> is implemented for Header<H> where H: Header + HeaderFormat. So what gives?

This works, but seems less elegant:

let mut rsp = Response::with((status::Ok, content));
rsp.headers.set(ContentType::json());
Ok(rsp)

#2

Ohhh, any chance this might become a library someday? I"ve wanted to make one…


#3

There’s not a lot to it so far… Just serde_json and this little function:

fn json_response(obj: &Value) -> IronResult<Response> {
    let content = serde_json::to_string(&obj).unwrap();
    Ok(Response::with((status::Ok, ContentType::json(), content)))
}

(Generally calling this with a serde_json ObjectBuilder thing.)

This project is open source, though: https://github.com/letsauth/ladaemon


#4

Ah! I woke up really early this morning, and my brain thought you meant http://jsonapi.org/ . Whoops!


#5

There’s an unfortunate juggling of “headers” types that has to be done here:

use iron::{headers, status};
use iron::modifiers::Header;

Response::with((status::Ok, Header(headers::ContentType::json())))

Documentation


#6

Ugh, so there’s an iron::headers::Header and a iron::modifiers::Header? Why in the world is that?!