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
use itertools::Itertools;
use std::collections::{BTreeMap, HashMap};
use crate::headers::HeaderValue;
#[derive(Debug, Clone, PartialEq)]
pub struct Response {
pub status: u16,
pub headers: BTreeMap<String, Vec<HeaderValue>>,
pub body: Option<Vec<u8>>,
}
impl Response {
pub fn default() -> Response {
Response {
status: 200,
headers: BTreeMap::new(),
body: None,
}
}
pub fn has_header(&self, header: &str) -> bool {
self.headers
.keys()
.find(|k| k.to_uppercase() == header.to_uppercase())
.is_some()
}
pub fn add_header(&mut self, header: &str, values: Vec<HeaderValue>) {
self.headers.insert(header.to_string(), values);
}
pub fn add_headers(&mut self, headers: HashMap<String, Vec<String>>) {
for (k, v) in headers {
self.headers
.insert(k, v.iter().map(HeaderValue::basic).collect());
}
}
pub fn add_cors_headers(&mut self, allowed_methods: &Vec<&str>) {
let cors_headers = Response::cors_headers(allowed_methods);
for (k, v) in cors_headers {
self.add_header(k.as_str(), v.iter().map(HeaderValue::basic).collect());
}
}
pub fn cors_headers(allowed_methods: &Vec<&str>) -> HashMap<String, Vec<String>> {
hashmap! {
"Access-Control-Allow-Origin".to_string() => vec!["*".to_string()],
"Access-Control-Allow-Methods".to_string() => allowed_methods.iter().cloned().map_into().collect(),
"Access-Control-Allow-Headers".to_string() => vec!["Content-Type".to_string()]
}
}
pub fn has_body(&self) -> bool {
match &self.body {
&None => false,
&Some(ref body) => !body.is_empty(),
}
}
}