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
use std::collections::HashMap;
use std::pin::Pin;
use std::sync::Arc;
use futures_util::future::{self, FutureExt};
use hyper::{Body, Response, StatusCode};
use log::trace;
use crate::handler::HandlerFuture;
use crate::state::{request_id, State};
use crate::router::response::extender::ResponseExtender;
#[derive(Clone)]
pub struct ResponseFinalizer {
data: Arc<HashMap<StatusCode, Box<dyn ResponseExtender<Body> + Send + Sync>>>,
}
pub struct ResponseFinalizerBuilder {
data: HashMap<StatusCode, Box<dyn ResponseExtender<Body> + Send + Sync>>,
}
impl ResponseFinalizerBuilder {
pub(in crate::router) fn new() -> Self {
let handlers = HashMap::new();
ResponseFinalizerBuilder { data: handlers }
}
pub fn add(
&mut self,
status_code: StatusCode,
extender: Box<dyn ResponseExtender<Body> + Send + Sync>,
) {
trace!(" adding response extender for {}", status_code);
self.data.insert(status_code, extender);
}
pub fn finalize(self) -> ResponseFinalizer {
ResponseFinalizer {
data: Arc::new(self.data),
}
}
}
impl ResponseFinalizer {
pub fn finalize(&self, mut state: State, mut res: Response<Body>) -> Pin<Box<HandlerFuture>> {
match self.data.get(&res.status()) {
Some(extender) => {
trace!(
"[{}] invoking {} response extender",
request_id(&state),
res.status()
);
extender.extend(&mut state, &mut res);
}
None => {
trace!(
"[{}] no response extender for {}",
request_id(&state),
res.status()
);
}
}
future::ok((state, res)).boxed()
}
}