Send the correct content type in Template contrib.

This commit is contained in:
Sergio Benitez 2016-09-25 03:06:02 -07:00
parent b175de03ad
commit 5b5cb7e087
4 changed files with 30 additions and 8 deletions

View File

@ -14,8 +14,8 @@ use std::path::{Path, PathBuf};
use std::collections::HashMap;
use self::serde::Serialize;
use rocket::response::{data, Outcome, FreshHyperResponse, Responder};
use rocket::Rocket;
use rocket::response::{Content, Outcome, FreshHyperResponse, Responder};
use rocket::{Rocket, ContentType};
use self::glob::glob;
lazy_static! {
@ -93,10 +93,13 @@ impl Template {
impl Responder for Template {
fn respond<'a>(&mut self, res: FreshHyperResponse<'a>) -> Outcome<'a> {
let content_type = match self.1 {
Some(ref ext) => ContentType::from_extension(ext),
None => ContentType::html()
};
match self.0 {
// FIXME: Detect the data type using the extension in self.1.
// Refactor response::named_file to use the extension map there.
Some(ref render) => data::HTML(render.as_str()).respond(res),
Some(ref render) => Content(content_type, render.as_str()).respond(res),
None => Outcome::Bad(res),
}
}

View File

@ -12,6 +12,14 @@ use router::Collider;
pub struct ContentType(pub TopLevel, pub SubLevel, pub Option<Vec<Param>>);
macro_rules! is_some {
($ct:ident, $name:ident: $top:ident/$sub:ident) => {
pub fn $ct() -> ContentType {
ContentType::of(TopLevel::$top, SubLevel::$sub)
}
is_some!($name: $top/$sub);
};
($name:ident: $top:ident/$sub:ident) => {
pub fn $name(&self) -> bool {
self.0 == TopLevel::$top && self.1 == SubLevel::$sub
@ -45,10 +53,10 @@ impl ContentType {
}
}
is_some!(is_json: Application/Json);
is_some!(is_xml: Application/Xml);
is_some!(json, is_json: Application/Json);
is_some!(xml, is_xml: Application/Xml);
is_some!(is_any: Star/Star);
is_some!(is_html: Application/Html);
is_some!(html, is_html: Application/Html);
is_some!(is_form: Application/WwwFormUrlEncoded);
is_some!(is_data: Multipart/FormData);

View File

@ -1,5 +1,15 @@
use response::{header, Responder, FreshHyperResponse, Outcome};
use response::mime::{Mime, TopLevel, SubLevel};
use ::ContentType;
pub struct Content<T: Responder>(pub ContentType, pub T);
impl<T: Responder> Responder for Content<T> {
fn respond<'b>(&mut self, mut res: FreshHyperResponse<'b>) -> Outcome<'b> {
res.headers_mut().set(header::ContentType(self.0.clone().into()));
self.1.respond(res)
}
}
macro_rules! impl_data_type_responder {
($name:ident: $top:ident/$sub:ident) => (

View File

@ -23,6 +23,7 @@ pub use self::outcome::Outcome;
pub use self::flash::Flash;
pub use self::named_file::NamedFile;
pub use self::stream::Stream;
pub use self::data::Content;
use std::ops::{Deref, DerefMut};