Skip to content

Commit 33cf5a4

Browse files
committed
Translate fs errors to 404s instead of errors
1 parent d5ef065 commit 33cf5a4

File tree

1 file changed

+32
-8
lines changed

1 file changed

+32
-8
lines changed

src/conduit-static.rs

Lines changed: 32 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -36,10 +36,21 @@ impl Handler for Static {
3636
}
3737

3838
let mime = self.types.mime_for_path(&path);
39-
let file = try!(File::open(&path).map_err(|e| box e as Box<Show>));
39+
let mut file = match File::open(&path) {
40+
Ok(f) => f,
41+
Err(..) => {
42+
return Ok(Response {
43+
status: (404, "Not Found"),
44+
headers: HashMap::new(),
45+
body: box NullReader,
46+
})
47+
}
48+
};
49+
let stat = try!(file.stat().map_err(|e| box e as Box<Show>));
4050

4151
let mut headers = HashMap::new();
42-
headers.insert("Content-Type".to_str(), vec!(mime.to_str()));
52+
headers.insert("Content-Type".to_str(), vec![mime.to_str()]);
53+
headers.insert("Content-Length".to_str(), vec![stat.size.to_str()]);
4354

4455
Ok(Response {
4556
status: (200, "OK"),
@@ -69,9 +80,10 @@ mod tests {
6980
let mut res = handler.call(&mut req).ok().expect("No response");
7081
let body = res.body.read_to_str().ok().expect("No body");
7182
assert_eq!(body.as_slice(), "[package]");
72-
assert_eq!(res.headers.find_equiv(&"Content-Type")
73-
.expect("No content-type"),
74-
&vec!("text/plain".to_str()));
83+
assert_eq!(res.headers.find_equiv(&"Content-Type"),
84+
Some(&vec!("text/plain".to_str())));
85+
assert_eq!(res.headers.find_equiv(&"Content-Length"),
86+
Some(&vec!["9".to_str()]));
7587
}
7688

7789
#[test]
@@ -84,8 +96,20 @@ mod tests {
8496
let handler = Static::new(root.clone());
8597
let mut req = test::MockRequest::new(conduit::Get, "/src/fixture.css");
8698
let res = handler.call(&mut req).ok().expect("No response");
87-
assert_eq!(res.headers.find_equiv(&"Content-Type")
88-
.expect("No content-type"),
89-
&vec!("text/css".to_str()));
99+
assert_eq!(res.headers.find_equiv(&"Content-Type"),
100+
Some(&vec!("text/css".to_str())));
101+
assert_eq!(res.headers.find_equiv(&"Content-Length"),
102+
Some(&vec!["0".to_str()]));
103+
}
104+
105+
#[test]
106+
fn test_missing() {
107+
let td = TempDir::new("conduit-static").unwrap();
108+
let root = td.path();
109+
110+
let handler = Static::new(root.clone());
111+
let mut req = test::MockRequest::new(conduit::Get, "/nope");
112+
let res = handler.call(&mut req).ok().expect("No response");
113+
assert_eq!(res.status.val0(), 404);
90114
}
91115
}

0 commit comments

Comments
 (0)