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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
use std::path::{PathBuf, Component};
use std::fs::File;
use std::io::Read;
use futures::Future;
use hyper::{Method, StatusCode};
use hyper::header::ContentLength;
use plugins::{Plugin, PluginData};
pub struct Htdocs {
docroot: PathBuf,
index: Option<String>,
}
impl Htdocs {
pub fn new<P>(docroot: P, index: Option<String>) -> Htdocs
where PathBuf: From<P>
{
Htdocs {
docroot: From::from(docroot),
index: index,
}
}
}
impl<S,E> Plugin<S,E> for Htdocs
where S: Send + Sync + 'static,
E: Send + 'static
{
fn handle(&self, mut data: PluginData<S>)
-> Box<Future<Item = PluginData<S>, Error = E>>
{
match data.request.method() {
&Method::Get | &Method::Head => { },
_ => return Box::new(::futures::future::ok(data)),
}
let mut filepath = {
let input: PathBuf = From::from(data.request.path());
let mut output: PathBuf = PathBuf::new();
for component in input.components() {
match component {
Component::Normal(osstr) => output.push(osstr),
_ => {},
}
}
self.docroot.join(output)
};
let shared = data.shared.clone();
let index = self.index.clone();
Box::new(
shared.pool.spawn_fn(move|| {
if filepath.is_dir() {
if let Some(ref index) = index {
filepath.push(index);
} else {
return Ok(data);
}
}
if filepath.exists() {
match File::open(&filepath) {
Err(e) => {
warn!("Cannot open {:?}: {}", filepath, e);
data.response.set_status(StatusCode::InternalServerError);
},
Ok(mut f) => {
let mut buffer = Vec::new();
match f.read_to_end(&mut buffer) {
Ok(count) => {
data.response.headers_mut().set::<ContentLength>(
ContentLength(count as u64));
if data.request.method() != &Method::Head {
data.response.set_body(buffer);
}
data.response.set_status(StatusCode::Ok);
},
Err(e) => {
warn!("Cannot read {:?}: {}", filepath, e);
data.response.set_status(StatusCode::InternalServerError);
}
};
}
}
}
Ok(data)
})
)
}
}