From 37db7d8168edbab537bfe1f7cb78753220357de9 Mon Sep 17 00:00:00 2001 From: Nikolay Kim Date: Sun, 8 Apr 2018 10:53:58 -0700 Subject: [PATCH] allow to override status code for NamedFile --- src/fs.rs | 27 +++++++++++++++++++++++++-- 1 file changed, 25 insertions(+), 2 deletions(-) diff --git a/src/fs.rs b/src/fs.rs index 4155aca98..e526ffbc0 100644 --- a/src/fs.rs +++ b/src/fs.rs @@ -36,6 +36,7 @@ pub struct NamedFile { modified: Option, cpu_pool: Option, only_get: bool, + status_code: StatusCode, } impl NamedFile { @@ -54,7 +55,9 @@ impl NamedFile { let path = path.as_ref().to_path_buf(); let modified = md.modified().ok(); let cpu_pool = None; - Ok(NamedFile{path, file, md, modified, cpu_pool, only_get: false}) + Ok(NamedFile{path, file, md, modified, cpu_pool, + only_get: false, + status_code: StatusCode::OK}) } /// Allow only GET and HEAD methods @@ -96,6 +99,12 @@ impl NamedFile { self } + /// Set response **Status Code** + pub fn set_status_code(mut self, status: StatusCode) -> Self { + self.status_code = status; + self + } + fn etag(&self) -> Option { // This etag format is similar to Apache's. self.modified.as_ref().map(|mtime| { @@ -207,7 +216,7 @@ impl Responder for NamedFile { false }; - let mut resp = HttpResponse::Ok(); + let mut resp = HttpResponse::build(self.status_code); resp .if_some(self.path().extension(), |ext, resp| { @@ -509,6 +518,20 @@ mod tests { assert_eq!(resp.headers().get(header::CONTENT_TYPE).unwrap(), "text/x-toml") } + #[test] + fn test_named_file_status_code() { + let mut file = NamedFile::open("Cargo.toml").unwrap() + .set_status_code(StatusCode::NOT_FOUND) + .set_cpu_pool(CpuPool::new(1)); + { file.file(); + let _f: &File = &file; } + { let _f: &mut File = &mut file; } + + let resp = file.respond_to(HttpRequest::default()).unwrap(); + assert_eq!(resp.headers().get(header::CONTENT_TYPE).unwrap(), "text/x-toml"); + assert_eq!(resp.status(), StatusCode::NOT_FOUND); + } + #[test] fn test_named_file_not_allowed() { let req = TestRequest::default().method(Method::POST).finish();