serve command respects mime types (closes #1308)

This commit is contained in:
southerntofu 2021-01-15 21:36:07 +01:00
parent ca1a6dd69d
commit 347208f24e
3 changed files with 20 additions and 2 deletions

11
Cargo.lock generated
View file

@ -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",

View file

@ -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" }

View file

@ -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<Body>, mut root: PathBuf) -> Result<Respons
// Remove the trailing slash from the request path
// otherwise `PathBuf` will interpret it as an absolute path
root.push(&req.uri().path()[1..]);
let result = tokio::fs::read(root).await;
let result = tokio::fs::read(&root).await;
let contents = match result {
Err(err) => match err.kind() {
@ -125,7 +126,11 @@ async fn handle_request(req: Request<Body>, mut root: PathBuf) -> Result<Respons
Ok(contents) => 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<Body> {