From 13b1eddd00b37fe7b3207481ba7e16a7aa260aa1 Mon Sep 17 00:00:00 2001 From: Emi Tatsuo Date: Tue, 24 Nov 2020 17:28:54 -0500 Subject: [PATCH] Allow serving a single file --- examples/serve_dir.rs | 3 ++- src/handling.rs | 12 ++++++++++-- 2 files changed, 12 insertions(+), 3 deletions(-) diff --git a/examples/serve_dir.rs b/examples/serve_dir.rs index b79c08d..cfdb345 100644 --- a/examples/serve_dir.rs +++ b/examples/serve_dir.rs @@ -11,7 +11,8 @@ async fn main() -> Result<()> { .init(); Server::bind(("localhost", GEMINI_PORT)) - .add_route("/", PathBuf::from("public")) + .add_route("/", PathBuf::from("public")) // Serve directory listings & file contents + .add_route("/about", PathBuf::from("README.md")) // Serve a single file .serve() .await } diff --git a/src/handling.rs b/src/handling.rs index de2d750..6f747b9 100644 --- a/src/handling.rs +++ b/src/handling.rs @@ -84,9 +84,14 @@ impl Handler { }, #[cfg(feature = "serve_dir")] Self::FilesHandler(path) => { - let resp = crate::util::serve_dir(path, request.trailing_segments()).await; + let resp = if path.is_dir() { + crate::util::serve_dir(path, request.trailing_segments()).await + } else { + let mime = crate::util::guess_mime_from_path(&path); + crate::util::serve_file(path, &mime).await + }; resp.unwrap_or_else(|e| { - warn!("Unexpected error serving from dir {}: {:?}", path.display(), e); + warn!("Unexpected error serving from {}: {:?}", path.display(), e); Response::server_error("").unwrap() }) }, @@ -164,6 +169,9 @@ impl From for Handler { /// This is equivilent to serving files using [`util::serve_dir()`], and as such will /// include directory listings. /// + /// The path to a single file can be passed in order to serve only a single file for + /// any and all requests. + /// /// [`util::serve_dir()`]: crate::util::serve_dir() fn from(path: PathBuf) -> Self { Self::FilesHandler(path)