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
use chrono::{DateTime, SubsecRound, offset::Local as LocalTz};
use http::response::Builder as ResponseBuilder;
use http::{Method, Request, Response, Result, StatusCode, header};
use hyper::Body;
use std::fs::Metadata;
use super::FileChunkStream;
use tokio::fs::File;
#[derive(Clone,Debug,Default)]
pub struct FileResponseBuilder {
pub cache_headers: Option<u32>,
pub is_head: bool,
pub if_modified_since: Option<DateTime<LocalTz>>,
}
impl FileResponseBuilder {
pub fn new() -> Self {
Self::default()
}
pub fn from_request<B>(req: &Request<B>) -> Self {
let mut builder = Self::new();
builder.method(req.method());
builder.if_modified_since_header(req.headers().get(header::IF_MODIFIED_SINCE));
builder
}
pub fn cache_headers(&mut self, value: Option<u32>) -> &mut Self {
self.cache_headers = value;
self
}
pub fn method(&mut self, value: &Method) -> &mut Self {
self.is_head = *value == Method::HEAD;
self
}
pub fn if_modified_since_header(&mut self, value: Option<&header::HeaderValue>) -> &mut Self {
self.if_modified_since = value
.and_then(|v| v.to_str().ok())
.and_then(|v| DateTime::parse_from_rfc2822(v).ok())
.map(|v| v.with_timezone(&LocalTz));
self
}
pub fn build(&self, file: File, metadata: Metadata) -> Result<Response<Body>> {
let mut res = ResponseBuilder::new();
if let Ok(modified) = metadata.modified() {
let modified: DateTime<LocalTz> = modified.into();
match self.if_modified_since {
Some(v) if modified.trunc_subsecs(0) <= v.trunc_subsecs(0) => {
return ResponseBuilder::new()
.status(StatusCode::NOT_MODIFIED)
.body(Body::empty())
},
_ => {},
}
res.header(header::LAST_MODIFIED, modified.to_rfc2822().as_str());
res.header(header::ETAG, format!("W/\"{0:x}-{1:x}.{2:x}\"",
metadata.len(), modified.timestamp(), modified.timestamp_subsec_nanos()).as_str());
}
res.header(header::CONTENT_LENGTH, format!("{}", metadata.len()).as_str());
if let Some(seconds) = self.cache_headers {
res.header(header::CACHE_CONTROL,
format!("public, max-age={}", seconds).as_str());
}
res.body(if self.is_head {
Body::empty()
} else {
Body::wrap_stream(FileChunkStream::new(file))
})
}
}