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
use futures::{Future, Poll};
use std::path::PathBuf;
use endpoint::{ApplyContext, ApplyResult, Endpoint};
use error::{bad_request, Error};
use output::fs::OpenNamedFile;
use output::NamedFile;
#[inline]
pub fn file(path: impl Into<PathBuf>) -> File {
(File { path: path.into() }).with_output::<(NamedFile,)>()
}
#[allow(missing_docs)]
#[derive(Debug, Clone)]
pub struct File {
path: PathBuf,
}
impl<'a> Endpoint<'a> for File {
type Output = (NamedFile,);
type Future = FileFuture;
fn apply(&self, _: &mut ApplyContext<'_>) -> ApplyResult<Self::Future> {
Ok(FileFuture {
state: State::Opening(NamedFile::open(self.path.clone())),
})
}
}
#[inline]
pub fn dir(root: impl Into<PathBuf>) -> Dir {
(Dir { root: root.into() }).with_output::<(NamedFile,)>()
}
#[allow(missing_docs)]
#[derive(Debug, Clone)]
pub struct Dir {
root: PathBuf,
}
impl<'a> Endpoint<'a> for Dir {
type Output = (NamedFile,);
type Future = FileFuture;
fn apply(&self, ecx: &mut ApplyContext<'_>) -> ApplyResult<Self::Future> {
let path = {
match ecx.remaining_path().percent_decode() {
Ok(path) => Ok(PathBuf::from(path.into_owned())),
Err(e) => Err(e),
}
};
while let Some(..) = ecx.next_segment() {}
let path = match path {
Ok(path) => path,
Err(e) => {
return Ok(FileFuture {
state: State::Err(Some(bad_request(e))),
})
}
};
let mut path = self.root.join(path);
if path.is_dir() {
path = path.join("index.html");
}
Ok(FileFuture {
state: State::Opening(NamedFile::open(path)),
})
}
}
#[doc(hidden)]
#[derive(Debug)]
pub struct FileFuture {
state: State,
}
#[derive(Debug)]
enum State {
Err(Option<Error>),
Opening(OpenNamedFile),
}
impl Future for FileFuture {
type Item = (NamedFile,);
type Error = Error;
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
match self.state {
State::Err(ref mut err) => Err(err.take().unwrap()),
State::Opening(ref mut f) => f.poll().map(|x| x.map(|x| (x,))).map_err(Into::into),
}
}
}