-
Notifications
You must be signed in to change notification settings - Fork 327
Expand file tree
/
Copy pathlib.rs
More file actions
63 lines (54 loc) · 1.63 KB
/
lib.rs
File metadata and controls
63 lines (54 loc) · 1.63 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
//! Crate that provides helpers and/or middlewares for Tide
//! related to http headers.
#![warn(
nonstandard_style,
rust_2018_idioms,
future_incompatible,
missing_debug_implementations
)]
use futures::future::BoxFuture;
use log::trace;
use http::{
header::{HeaderValue, IntoHeaderName},
HeaderMap, HttpTryFrom,
};
use tide_core::{
middleware::{Middleware, Next},
Context, Response,
};
/// Middleware for providing a set of default headers for all responses.
#[derive(Clone, Default, Debug)]
pub struct DefaultHeaders {
headers: HeaderMap,
}
impl DefaultHeaders {
/// Construct a new instance with an empty list of headers.
pub fn new() -> DefaultHeaders {
Self::default()
}
/// Add a header to the default header list.
pub fn header<K, V>(mut self, key: K, value: V) -> Self
where
K: IntoHeaderName,
HeaderValue: HttpTryFrom<V>,
{
let value = HeaderValue::try_from(value)
.map_err(Into::into)
.expect("Cannot create default header");
self.headers.append(key, value);
self
}
}
impl<State: Send + Sync + 'static> Middleware<State> for DefaultHeaders {
fn handle<'a>(&'a self, cx: Context<State>, next: Next<'a, State>) -> BoxFuture<'a, Response> {
Box::pin(async move {
let mut res = next.run(cx).await;
let headers = res.headers_mut();
for (key, value) in self.headers.iter() {
trace!("add default: {} {:?}", &key, &value);
headers.entry(key).unwrap().or_insert_with(|| value.clone());
}
res
})
}
}