use http::{
header::{self, HeaderValue},
status::StatusCode,
};
use super::IntoResponse;
use crate::{body::Body, response::Response};
pub struct Redirect {
status: StatusCode,
location: HeaderValue,
}
impl Redirect {
pub fn with_status_code(status: StatusCode, location: &str) -> Self {
debug_assert!(status.is_redirection());
Self {
status,
location: HeaderValue::from_str(location)
.expect("The target location is not a valid header value"),
}
}
pub fn moved_permanently(location: &str) -> Self {
Self::with_status_code(StatusCode::MOVED_PERMANENTLY, location)
}
pub fn found(location: &str) -> Self {
Self::with_status_code(StatusCode::FOUND, location)
}
pub fn see_other(location: &str) -> Self {
Self::with_status_code(StatusCode::SEE_OTHER, location)
}
pub fn temporary_redirect(location: &str) -> Self {
Self::with_status_code(StatusCode::TEMPORARY_REDIRECT, location)
}
pub fn permanent_redirect(location: &str) -> Self {
Self::with_status_code(StatusCode::PERMANENT_REDIRECT, location)
}
}
impl IntoResponse for Redirect {
fn into_response(self) -> Response {
Response::builder()
.status(self.status)
.header(header::LOCATION, self.location)
.body(Body::default())
.expect("infallible")
}
}