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
use crate::{resolve, ResponseBuilder};
use http::{Request, Response};
use hyper::{service::Service, Body};
use std::future::Future;
use std::io::Error as IoError;
use std::path::PathBuf;
use std::pin::Pin;
use std::task::{Context, Poll};
#[derive(Clone)]
pub struct Static {
pub root: PathBuf,
pub cache_headers: Option<u32>,
}
impl Static {
pub fn new(root: impl Into<PathBuf>) -> Self {
let root = root.into();
Static {
root,
cache_headers: None,
}
}
pub fn cache_headers(&mut self, value: Option<u32>) -> &mut Self {
self.cache_headers = value;
self
}
pub async fn serve<B>(self, request: Request<B>) -> Result<Response<Body>, IoError> {
let Self {
root,
cache_headers,
} = self;
resolve(root, &request).await.map(|result| {
ResponseBuilder::new()
.request(&request)
.cache_headers(cache_headers)
.build(result)
.expect("unable to build response")
})
}
}
impl<B: 'static> Service<Request<B>> for Static {
type Response = Response<Body>;
type Error = IoError;
type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>>>>;
fn poll_ready(&mut self, _cx: &mut Context) -> Poll<Result<(), Self::Error>> {
Poll::Ready(Ok(()))
}
fn call(&mut self, request: Request<B>) -> Self::Future {
Box::pin(self.clone().serve(request))
}
}