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
use std::{io, str::FromStr};
use async_compression::tokio::bufread;
use futures_util::TryStreamExt;
use tokio_util::io::{ReaderStream, StreamReader};
use crate::{
async_trait,
header::{HeaderValue, ACCEPT_ENCODING, CONTENT_ENCODING, CONTENT_LENGTH},
Body, Handler, IntoResponse, Request, Response, Result, Transform,
};
#[derive(Debug, Default)]
pub struct Config;
impl<H> Transform<H> for Config
where
H: Clone,
{
type Output = CompressionMiddleware<H>;
fn transform(&self, h: H) -> Self::Output {
CompressionMiddleware { h }
}
}
#[derive(Clone, Debug)]
pub struct CompressionMiddleware<H> {
h: H,
}
#[async_trait]
impl<H, O> Handler<Request> for CompressionMiddleware<H>
where
O: IntoResponse,
H: Handler<Request, Output = Result<O>> + Clone,
{
type Output = Result<Response>;
async fn call(&self, req: Request) -> Self::Output {
let accept_encoding = req
.headers()
.get(ACCEPT_ENCODING)
.and_then(|v| v.to_str().ok())
.and_then(parse_accept_encoding);
let raw = self.h.call(req).await?;
Ok(match accept_encoding {
Some(algo) => Compress::new(raw, algo).into_response(),
None => raw.into_response(),
})
}
}
#[derive(Debug)]
pub struct Compress<T> {
inner: T,
algo: ContentCoding,
}
impl<T> Compress<T> {
pub fn new(inner: T, algo: ContentCoding) -> Self {
Self { inner, algo }
}
}
impl<T: IntoResponse> IntoResponse for Compress<T> {
fn into_response(self) -> Response {
let mut res = self.inner.into_response();
match self.algo {
ContentCoding::Gzip | ContentCoding::Deflate | ContentCoding::Brotli => {
res = res.map(|body| {
let body = StreamReader::new(body.map_err(map_hyper_err));
if self.algo == ContentCoding::Gzip {
Body::wrap_stream(ReaderStream::new(bufread::GzipEncoder::new(body)))
} else if self.algo == ContentCoding::Deflate {
Body::wrap_stream(ReaderStream::new(bufread::DeflateEncoder::new(body)))
} else {
Body::wrap_stream(ReaderStream::new(bufread::BrotliEncoder::new(body)))
}
});
res.headers_mut()
.append(CONTENT_ENCODING, HeaderValue::from_static(self.algo.into()));
res.headers_mut().remove(CONTENT_LENGTH);
res
}
ContentCoding::Any => res,
}
}
}
#[derive(Debug, PartialEq)]
pub enum ContentCoding {
Gzip,
Deflate,
Brotli,
Any,
}
impl FromStr for ContentCoding {
type Err = ();
fn from_str(s: &str) -> Result<Self, Self::Err> {
if s.eq_ignore_ascii_case("deflate") {
Ok(ContentCoding::Deflate)
} else if s.eq_ignore_ascii_case("gzip") {
Ok(ContentCoding::Gzip)
} else if s.eq_ignore_ascii_case("br") {
Ok(ContentCoding::Brotli)
} else if s == "*" {
Ok(ContentCoding::Any)
} else {
Err(())
}
}
}
impl From<ContentCoding> for &'static str {
fn from(cc: ContentCoding) -> Self {
match cc {
ContentCoding::Gzip => "gzip",
ContentCoding::Deflate => "deflate",
ContentCoding::Brotli => "br",
ContentCoding::Any => "*",
}
}
}
fn parse_accept_encoding(s: &str) -> Option<ContentCoding> {
s.split(',')
.map(str::trim)
.filter_map(|v| {
Some(match v.split_once(";q=") {
Some((c, q)) => (
c.parse::<ContentCoding>().ok()?,
q.parse::<f32>().ok()? * 1000.,
),
None => (v.parse::<ContentCoding>().ok()?, 1000.),
})
})
.max_by_key(|(_, q)| *q as u16)
.map(|(c, _)| c)
}
fn map_hyper_err(e: hyper::Error) -> io::Error {
io::Error::new(io::ErrorKind::Other, e)
}