From 15b7981c869adbfee4f279c6534000003fbc8eee Mon Sep 17 00:00:00 2001 From: tessereth Date: Sun, 1 Jul 2018 17:23:43 +1000 Subject: [PATCH] Use StaticFile default handler when file is inaccessible --- src/fs.rs | 26 +++++++++++++++++++++++--- 1 file changed, 23 insertions(+), 3 deletions(-) diff --git a/src/fs.rs b/src/fs.rs index b6ba47062..8c0d92246 100644 --- a/src/fs.rs +++ b/src/fs.rs @@ -673,7 +673,10 @@ impl Handler for StaticFiles { }; // full filepath - let path = self.directory.join(&relpath).canonicalize()?; + let path = match self.directory.join(&relpath).canonicalize() { + Ok(path) => path, + _ => return Ok(self.default.handle(req)) + }; if path.is_dir() { if let Some(ref redir_index) = self.index { @@ -696,8 +699,11 @@ impl Handler for StaticFiles { Ok(self.default.handle(req)) } } else { - NamedFile::open(path)? - .set_cpu_pool(self.cpu_pool.clone()) + let file = match NamedFile::open(path) { + Ok(file) => file, + _ => return Ok(self.default.handle(req)) + }; + file.set_cpu_pool(self.cpu_pool.clone()) .respond_to(&req)? .respond_to(&req) } @@ -806,6 +812,7 @@ mod tests { use super::*; use application::App; + use body::{Binary, Body}; use http::{header, Method, StatusCode}; use test::{self, TestRequest}; @@ -1210,6 +1217,19 @@ mod tests { assert!(format!("{:?}", resp.body()).contains("README.md")); } + #[test] + fn test_default_handler_file_missing() { + let st = StaticFiles::new(".") + .default_handler(|_req| "default content"); + let req = TestRequest::with_uri("/missing") + .param("tail", "missing").finish(); + + let resp = st.handle(req).respond_to(&HttpRequest::default()).unwrap(); + let resp = resp.as_msg(); + assert_eq!(resp.status(), StatusCode::OK); + assert_eq!(resp.body(), &Body::Binary(Binary::Slice(b"default content"))); + } + #[test] fn test_redirect_to_index() { let st = StaticFiles::new(".").index_file("index.html");