1 | use std::sync::Arc; |
2 | |
3 | #[derive (Clone)] |
4 | pub(crate) struct OnInformational(Arc<dyn OnInformationalCallback + Send + Sync>); |
5 | |
6 | /// Add a callback for 1xx informational responses. |
7 | /// |
8 | /// # Example |
9 | /// |
10 | /// ``` |
11 | /// # let some_body = (); |
12 | /// let mut req = hyper::Request::new(some_body); |
13 | /// |
14 | /// hyper::ext::on_informational(&mut req, |res| { |
15 | /// println!("informational: {:?}" , res.status()); |
16 | /// }); |
17 | /// |
18 | /// // send request on a client connection... |
19 | /// ``` |
20 | pub fn on_informational<B, F>(req: &mut http::Request<B>, callback: F) |
21 | where |
22 | F: Fn(Response<'_>) + Send + Sync + 'static, |
23 | { |
24 | on_informational_raw(req, callback:OnInformationalClosure(callback)); |
25 | } |
26 | |
27 | pub(crate) fn on_informational_raw<B, C>(req: &mut http::Request<B>, callback: C) |
28 | where |
29 | C: OnInformationalCallback + Send + Sync + 'static, |
30 | { |
31 | req.extensions_mut() |
32 | .insert(val:OnInformational(Arc::new(data:callback))); |
33 | } |
34 | |
35 | // Sealed, not actually nameable bounds |
36 | pub(crate) trait OnInformationalCallback { |
37 | fn on_informational(&self, res: http::Response<()>); |
38 | } |
39 | |
40 | impl OnInformational { |
41 | pub(crate) fn call(&self, res: http::Response<()>) { |
42 | self.0.on_informational(res); |
43 | } |
44 | } |
45 | |
46 | struct OnInformationalClosure<F>(F); |
47 | |
48 | impl<F> OnInformationalCallback for OnInformationalClosure<F> |
49 | where |
50 | F: Fn(Response<'_>) + Send + Sync + 'static, |
51 | { |
52 | fn on_informational(&self, res: http::Response<()>) { |
53 | let res: Response<'_> = Response(&res); |
54 | (self.0)(res); |
55 | } |
56 | } |
57 | |
58 | // A facade over http::Response. |
59 | // |
60 | // It purposefully hides being able to move the response out of the closure, |
61 | // while also not being able to expect it to be a reference `&Response`. |
62 | // (Otherwise, a closure can be written as `|res: &_|`, and then be broken if |
63 | // we make the closure take ownership.) |
64 | // |
65 | // With the type not being nameable, we could change from being a facade to |
66 | // being either a real reference, or moving the http::Response into the closure, |
67 | // in a backwards-compatible change in the future. |
68 | #[derive (Debug)] |
69 | pub struct Response<'a>(&'a http::Response<()>); |
70 | |
71 | impl Response<'_> { |
72 | #[inline ] |
73 | pub fn status(&self) -> http::StatusCode { |
74 | self.0.status() |
75 | } |
76 | |
77 | #[inline ] |
78 | pub fn version(&self) -> http::Version { |
79 | self.0.version() |
80 | } |
81 | |
82 | #[inline ] |
83 | pub fn headers(&self) -> &http::HeaderMap { |
84 | self.0.headers() |
85 | } |
86 | } |
87 | |