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
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
#[cfg(feature = "brotli")]
use async_compression::futures::bufread::BrotliEncoder;
#[cfg(feature = "deflate")]
use async_compression::futures::bufread::DeflateEncoder;
#[cfg(feature = "gzip")]
use async_compression::futures::bufread::GzipEncoder;
use futures_lite::io::BufReader;
use tide::http::cache::{CacheControl, CacheDirective};
use tide::http::conditional::Vary;
use tide::http::content::{AcceptEncoding, ContentEncoding, Encoding};
use tide::http::{headers, Body, Method};
use tide::{Middleware, Next, Request, Response};
const THRESHOLD: usize = 1024;
#[derive(Clone, Debug)]
pub struct CompressMiddleware {
threshold: usize,
}
impl Default for CompressMiddleware {
fn default() -> Self {
CompressMiddleware {
threshold: THRESHOLD,
}
}
}
impl CompressMiddleware {
pub fn new() -> Self {
Self::default()
}
pub fn with_threshold(threshold: usize) -> Self {
CompressMiddleware { threshold }
}
}
#[tide::utils::async_trait]
impl<State: Clone + Send + Sync + 'static> Middleware<State> for CompressMiddleware {
async fn handle(&self, req: Request<State>, next: Next<'_, State>) -> tide::Result {
let is_head = req.method() == Method::Head;
let accepts = AcceptEncoding::from_headers(&req)?;
let mut res: Response = next.run(req).await;
if is_head || accepts.is_none() {
return Ok(res);
}
let mut accepts = accepts.unwrap();
if let Some(cache_control) = CacheControl::from_headers(&res)? {
if cache_control
.iter()
.any(|directive| directive == &CacheDirective::NoTransform)
{
return Ok(res);
}
}
let mut vary = Vary::new();
vary.push(headers::ACCEPT_ENCODING)?;
vary.apply(&mut res);
if let Some(previous_encoding) = ContentEncoding::from_headers(&res)? {
if previous_encoding != Encoding::Identity {
return Ok(res);
}
}
if let Some(body_len) = res.len() {
if body_len < self.threshold {
return Ok(res);
}
}
let body = res.take_body();
let encoding = accepts.negotiate(&[
#[cfg(feature = "brotli")]
Encoding::Brotli,
#[cfg(feature = "gzip")]
Encoding::Gzip,
#[cfg(feature = "deflate")]
Encoding::Deflate,
])?;
res.set_body(get_encoder(body, &encoding));
encoding.apply(&mut res);
res.remove_header(headers::CONTENT_LENGTH);
Ok(res)
}
}
fn get_encoder(body: Body, encoding: &ContentEncoding) -> Body {
#[cfg(feature = "brotli")]
{
if *encoding == Encoding::Brotli {
return Body::from_reader(BufReader::new(BrotliEncoder::new(body)), None);
}
}
#[cfg(feature = "gzip")]
{
if *encoding == Encoding::Gzip {
return Body::from_reader(BufReader::new(GzipEncoder::new(body)), None);
}
}
#[cfg(feature = "deflate")]
{
if *encoding == Encoding::Deflate {
return Body::from_reader(BufReader::new(DeflateEncoder::new(body)), None);
}
}
body
}