-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmiddlewares.rs
More file actions
76 lines (66 loc) · 2.3 KB
/
Copy pathmiddlewares.rs
File metadata and controls
76 lines (66 loc) · 2.3 KB
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
use crate::http::HeaderName;
use crate::http::compression::Encoding;
use crate::request::HttpRequest;
use crate::response::HttpResponse;
use flate2::Compression;
use flate2::write::GzEncoder;
use std::io::Write;
pub type Middleware = fn(&HttpRequest, &mut HttpResponse);
pub struct MiddlewarePipeline {
middlewares: Vec<Middleware>,
}
impl MiddlewarePipeline {
pub fn new() -> Self {
Self {
middlewares: Vec::new(),
}
}
pub fn add(mut self, middleware: Middleware) -> Self {
self.middlewares.push(middleware);
self
}
pub fn run(&self, req: &HttpRequest, res: &mut HttpResponse) {
for middleware in &self.middlewares {
middleware(req, res);
}
}
}
pub fn apply_keep_alive_headers(req: &HttpRequest, res: &mut HttpResponse) {
let close: &'static str = "close";
if !req.keep_alive {
res.headers
.insert(HeaderName::Connection, close.to_string());
}
}
pub fn apply_encoding(req: &HttpRequest, res: &mut HttpResponse) {
if let Some(content_encoding) = req.headers.get("accept-encoding") {
let matched = content_encoding
.split(',')
.find_map(|s| s.trim().parse::<Encoding>().ok());
if let Some(encoding) = matched {
match encoding {
Encoding::Gzip => {
if res.body.is_empty() {
return;
}
let mut encoder = GzEncoder::new(Vec::new(), Compression::default());
match encoder.write_all(&res.body) {
Ok(_) => match encoder.finish() {
Ok(encoded) => {
res.body = encoded;
res.headers
.insert(HeaderName::ContentEncoding, "gzip".to_string());
}
Err(e) => eprintln!("error encoding finish(): {}", e),
},
Err(e) => eprintln!("error encoding write_all: {}", e),
}
}
};
}
}
}
pub fn apply_content_length(_: &HttpRequest, res: &mut HttpResponse) {
res.headers
.insert(HeaderName::ContentLength, res.body.len().to_string());
}