From 347208f24e1179591345c0f46ee52c822008d22c Mon Sep 17 00:00:00 2001 From: southerntofu Date: Fri, 15 Jan 2021 21:36:07 +0100 Subject: [PATCH] serve command respects mime types (closes #1308) --- Cargo.lock | 11 +++++++++++ Cargo.toml | 2 ++ src/cmd/serve.rs | 9 +++++++-- 3 files changed, 20 insertions(+), 2 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index fbe36145..190754a4 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1355,6 +1355,16 @@ version = "0.3.16" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2a60c7ce501c71e03a9c9c0d35b861413ae925bd979cc7a4e30d060069aaac8d" +[[package]] +name = "mime_guess" +version = "2.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2684d4c2e97d99848d30b324b00c8fcc7e5c897b7cbb5819b09e7c90e8baf212" +dependencies = [ + "mime", + "unicase", +] + [[package]] name = "minify-html" version = "0.4.1" @@ -3254,6 +3264,7 @@ dependencies = [ "globset", "hyper", "lazy_static", + "mime_guess", "notify", "open", "percent-encoding", diff --git a/Cargo.toml b/Cargo.toml index 7f813bfe..33ec011b 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -37,6 +37,8 @@ open = "1.2" globset = "0.4" relative-path = "1" serde_json = "1.0" +# For mimetype detection in serve mode +mime_guess = "2.0" site = { path = "components/site" } errors = { path = "components/errors" } diff --git a/src/cmd/serve.rs b/src/cmd/serve.rs index 39ab47f9..122f83d4 100644 --- a/src/cmd/serve.rs +++ b/src/cmd/serve.rs @@ -32,6 +32,7 @@ use hyper::header; use hyper::server::Server; use hyper::service::{make_service_fn, service_fn}; use hyper::{Body, Method, Request, Response, StatusCode}; +use mime_guess::from_path as mimetype_from_path; use chrono::prelude::*; use notify::{watcher, RecursiveMode, Watcher}; @@ -109,7 +110,7 @@ async fn handle_request(req: Request, mut root: PathBuf) -> Result match err.kind() { @@ -125,7 +126,11 @@ async fn handle_request(req: Request, mut root: PathBuf) -> Result contents, }; - Ok(Response::builder().status(StatusCode::OK).body(Body::from(contents)).unwrap()) + Ok(Response::builder() + .status(StatusCode::OK) + .header("Content-Type", mimetype_from_path(&root).first_or_octet_stream().essence_str()) + .body(Body::from(contents)) + .unwrap()) } fn livereload_js() -> Response {