Skip to main content

spire_core/http/
response_ext.rs

1//! Responses and their crawl metadata.
2
3use ::http::Uri;
4use bytes::Bytes;
5
6use super::meta::ResponseMeta;
7
8/// An HTTP response with its body in memory by default. Sessions return
9/// complete responses; helpers may use another body type, such as `()`.
10pub type Response<B = Bytes> = ::http::Response<B>;
11
12/// Reads and writes crawl metadata on a [`Response`].
13pub trait ResponseExt {
14    /// Returns the URI the response was served from after redirects, if the
15    /// backend recorded it.
16    ///
17    /// Resolve relative links against this rather than the request URI.
18    fn final_uri(&self) -> Option<&Uri>;
19
20    /// Records the URI the response was served from; called by backends.
21    fn set_final_uri(&mut self, uri: Uri);
22}
23
24impl<B> ResponseExt for ::http::Response<B> {
25    fn final_uri(&self) -> Option<&Uri> {
26        self.extensions().get::<ResponseMeta>()?.final_uri.as_ref()
27    }
28
29    fn set_final_uri(&mut self, uri: Uri) {
30        let meta = self
31            .extensions_mut()
32            .get_or_insert_default::<ResponseMeta>();
33        meta.final_uri = Some(uri);
34    }
35}
36
37#[cfg(test)]
38mod tests {
39    use super::*;
40
41    #[test]
42    fn response_final_uri() {
43        let mut response = Response::new(());
44        assert_eq!(response.final_uri(), None);
45        response.set_final_uri(Uri::from_static("https://example.com/moved"));
46        assert_eq!(response.final_uri().unwrap(), "https://example.com/moved");
47    }
48}