Allow serving a single file

This commit is contained in:
Emi Tatsuo 2020-11-24 17:28:54 -05:00
parent 970813f295
commit 13b1eddd00
Signed by: Emi
GPG Key ID: 68FAB2E2E6DFC98B
2 changed files with 12 additions and 3 deletions

View File

@ -11,7 +11,8 @@ async fn main() -> Result<()> {
.init(); .init();
Server::bind(("localhost", GEMINI_PORT)) 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() .serve()
.await .await
} }

View File

@ -84,9 +84,14 @@ impl Handler {
}, },
#[cfg(feature = "serve_dir")] #[cfg(feature = "serve_dir")]
Self::FilesHandler(path) => { 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| { 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() Response::server_error("").unwrap()
}) })
}, },
@ -164,6 +169,9 @@ impl From<PathBuf> for Handler {
/// This is equivilent to serving files using [`util::serve_dir()`], and as such will /// This is equivilent to serving files using [`util::serve_dir()`], and as such will
/// include directory listings. /// 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() /// [`util::serve_dir()`]: crate::util::serve_dir()
fn from(path: PathBuf) -> Self { fn from(path: PathBuf) -> Self {
Self::FilesHandler(path) Self::FilesHandler(path)