Set Content-Type on 'MsgPack' responses.

Fixes #1009.
This commit is contained in:
Sergio Benitez 2019-05-23 17:16:59 -07:00
parent 6bf751fb22
commit 8434a98d5c
2 changed files with 5 additions and 6 deletions

View File

@ -16,13 +16,13 @@
extern crate serde; extern crate serde;
extern crate rmp_serde; extern crate rmp_serde;
use std::io::Read;
use std::ops::{Deref, DerefMut}; use std::ops::{Deref, DerefMut};
use std::io::{Cursor, Read};
use rocket::request::Request; use rocket::request::Request;
use rocket::outcome::Outcome::*; use rocket::outcome::Outcome::*;
use rocket::data::{Outcome, Transform, Transform::*, Transformed, Data, FromData}; use rocket::data::{Outcome, Transform, Transform::*, Transformed, Data, FromData};
use rocket::response::{self, Responder, Response}; use rocket::response::{self, Responder, content};
use rocket::http::Status; use rocket::http::Status;
use self::serde::Serialize; use self::serde::Serialize;
@ -153,14 +153,12 @@ impl<'a, T: Deserialize<'a>> FromData<'a> for MsgPack<T> {
/// Content-Type `MsgPack` and a fixed-size body with the serialization. If /// Content-Type `MsgPack` and a fixed-size body with the serialization. If
/// serialization fails, an `Err` of `Status::InternalServerError` is returned. /// serialization fails, an `Err` of `Status::InternalServerError` is returned.
impl<T: Serialize> Responder<'static> for MsgPack<T> { impl<T: Serialize> Responder<'static> for MsgPack<T> {
fn respond_to(self, _: &Request) -> response::Result<'static> { fn respond_to(self, req: &Request) -> response::Result<'static> {
rmp_serde::to_vec(&self.0).map_err(|e| { rmp_serde::to_vec(&self.0).map_err(|e| {
error_!("MsgPack failed to serialize: {:?}", e); error_!("MsgPack failed to serialize: {:?}", e);
Status::InternalServerError Status::InternalServerError
}).and_then(|buf| { }).and_then(|buf| {
Response::build() content::MsgPack(buf).respond_to(req)
.sized_body(Cursor::new(buf))
.ok()
}) })
} }
} }

View File

@ -13,6 +13,7 @@ fn msgpack_get() {
let client = Client::new(rocket()).unwrap(); let client = Client::new(rocket()).unwrap();
let mut res = client.get("/message/1").header(ContentType::MsgPack).dispatch(); let mut res = client.get("/message/1").header(ContentType::MsgPack).dispatch();
assert_eq!(res.status(), Status::Ok); assert_eq!(res.status(), Status::Ok);
assert_eq!(res.content_type(), Some(ContentType::MsgPack));
// Check that the message is `[1, "Hello, world!"]` // Check that the message is `[1, "Hello, world!"]`
assert_eq!(&res.body_bytes().unwrap(), assert_eq!(&res.body_bytes().unwrap(),