1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
use std::fs::File;
use std::path::{PathBuf, Path};
use std::io::Read;
use hyper::uri::RequestUri::AbsolutePath;
use hyper::method::Method::{Get, Head, Options};
use hyper::status::StatusCode;
use hyper::header;
use request::Request;
use response::Response;
use middleware::{Continue, Middleware, MiddlewareResult};
use mimes::MediaType;
pub struct FaviconHandler {
icon: Vec<u8>,
icon_path: PathBuf,
}
impl<D> Middleware<D> for FaviconHandler {
fn invoke<'a, 'server>(&'a self, req: &mut Request<'a, 'server, D>, res: Response<'a, D>)
-> MiddlewareResult<'a, D> {
if FaviconHandler::is_favicon_request(req) {
self.handle_request(req, res)
} else {
Ok(Continue(res))
}
}
}
impl FaviconHandler {
pub fn new<P: AsRef<Path>>(icon_path: P) -> FaviconHandler {
let icon_path = icon_path.as_ref().to_path_buf();
let mut icon = vec![];
File::open(&icon_path).unwrap().read_to_end(&mut icon).unwrap();
FaviconHandler {
icon: icon,
icon_path: icon_path,
}
}
#[inline]
pub fn is_favicon_request<D>(req: &Request<D>) -> bool {
match req.origin.uri {
AbsolutePath(ref path) => &**path == "/favicon.ico",
_ => false
}
}
pub fn handle_request<'a, D>(&self, req: &Request<D>, mut res: Response<'a, D>) -> MiddlewareResult<'a, D> {
match req.origin.method {
Get | Head => {
self.send_favicon(req, res)
},
Options => {
res.set(StatusCode::Ok);
res.set(header::Allow(vec![Get, Head, Options]));
res.send("")
},
_ => {
res.set(StatusCode::MethodNotAllowed);
res.set(header::Allow(vec![Get, Head, Options]));
res.send("")
}
}
}
pub fn send_favicon<'a, D>(&self, req: &Request<D>, mut res: Response<'a, D>) -> MiddlewareResult<'a, D> {
debug!("{:?} {:?}", req.origin.method, self.icon_path.display());
res.set(MediaType::Ico);
res.send(&*self.icon)
}
}