rama_http_types/response/
redirect.rs

1use super::IntoResponse;
2use crate::{HeaderValue, Response, StatusCode, header};
3
4#[derive(Debug, Clone)]
5/// Utility struct to easily create a redirect response.
6pub struct Redirect {
7    loc: HeaderValue,
8    status: StatusCode,
9}
10
11impl Redirect {
12    /// Create a new temporary (307) redirect response.
13    ///
14    /// # Panics
15    ///
16    /// This function panics if the `loc` argument contains invalid header value characters.
17    pub fn temporary(loc: impl AsRef<str>) -> Self {
18        Redirect {
19            loc: HeaderValue::from_str(loc.as_ref()).unwrap(),
20            status: StatusCode::TEMPORARY_REDIRECT,
21        }
22    }
23
24    /// Create a new permanent (308) redirect response.
25    ///
26    /// # Panics
27    ///
28    /// This function panics if the `loc` argument contains invalid header value characters.
29    pub fn permanent(loc: impl AsRef<str>) -> Self {
30        Redirect {
31            loc: HeaderValue::from_str(loc.as_ref()).unwrap(),
32            status: StatusCode::PERMANENT_REDIRECT,
33        }
34    }
35}
36
37impl IntoResponse for Redirect {
38    fn into_response(self) -> Response {
39        ([(header::LOCATION, self.loc)], self.status).into_response()
40    }
41}