Move extension derived content type into ContentType.

This commit is contained in:
Sergio Benitez 2016-09-25 02:51:18 -07:00
parent cd4af6836a
commit b175de03ad
2 changed files with 24 additions and 19 deletions

View File

@ -51,6 +51,26 @@ impl ContentType {
is_some!(is_html: Application/Html); is_some!(is_html: Application/Html);
is_some!(is_form: Application/WwwFormUrlEncoded); is_some!(is_form: Application/WwwFormUrlEncoded);
is_some!(is_data: Multipart/FormData); is_some!(is_data: Multipart/FormData);
pub fn from_extension(ext: &str) -> ContentType {
let (top_level, sub_level) = match ext {
"txt" => (TopLevel::Text, SubLevel::Plain),
"html" => (TopLevel::Text, SubLevel::Html),
"xml" => (TopLevel::Application, SubLevel::Xml),
"js" => (TopLevel::Application, SubLevel::Javascript),
"css" => (TopLevel::Text, SubLevel::Css),
"json" => (TopLevel::Application, SubLevel::Json),
"png" => (TopLevel::Image, SubLevel::Png),
"gif" => (TopLevel::Image, SubLevel::Gif),
"bmp" => (TopLevel::Image, SubLevel::Bmp),
"jpeg" => (TopLevel::Image, SubLevel::Jpeg),
"jpg" => (TopLevel::Image, SubLevel::Jpeg),
"pdf" => (TopLevel::Application, SubLevel::Ext("pdf".into())),
_ => (TopLevel::Star, SubLevel::Star),
};
ContentType::of(top_level, sub_level)
}
} }
impl Default for ContentType { impl Default for ContentType {

View File

@ -1,7 +1,7 @@
use response::*; use response::*;
use content_type::ContentType;
use std::fs::File; use std::fs::File;
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
use response::mime::{Mime, TopLevel, SubLevel};
use std::io; use std::io;
use std::ops::{Deref, DerefMut}; use std::ops::{Deref, DerefMut};
@ -23,24 +23,9 @@ impl Responder for NamedFile {
fn respond<'a>(&mut self, mut res: FreshHyperResponse<'a>) -> Outcome<'a> { fn respond<'a>(&mut self, mut res: FreshHyperResponse<'a>) -> Outcome<'a> {
if let Some(ext) = self.path().extension() { if let Some(ext) = self.path().extension() {
let ext_string = ext.to_string_lossy().to_lowercase(); let ext_string = ext.to_string_lossy().to_lowercase();
let (top_level, sub_level) = match ext_string.as_str() { let content_type = ContentType::from_extension(&ext_string);
"txt" => (TopLevel::Text, SubLevel::Plain), if !content_type.is_any() {
"html" => (TopLevel::Text, SubLevel::Html), res.headers_mut().set(header::ContentType(content_type.into()));
"xml" => (TopLevel::Application, SubLevel::Xml),
"js" => (TopLevel::Application, SubLevel::Javascript),
"css" => (TopLevel::Text, SubLevel::Css),
"json" => (TopLevel::Application, SubLevel::Json),
"png" => (TopLevel::Image, SubLevel::Png),
"gif" => (TopLevel::Image, SubLevel::Gif),
"bmp" => (TopLevel::Image, SubLevel::Bmp),
"jpeg" => (TopLevel::Image, SubLevel::Jpeg),
"jpg" => (TopLevel::Image, SubLevel::Jpeg),
_ => (TopLevel::Star, SubLevel::Star),
};
if top_level != TopLevel::Star && sub_level != SubLevel::Star {
let mime = Mime(top_level, sub_level, vec![]);
res.headers_mut().set(header::ContentType(mime));
} }
} }