use crate::request::Request;
use crate::response::{self, Response, Responder};
use crate::http::uri::Reference;
use crate::http::Status;
#[derive(Debug)]
pub struct Redirect(Status, Option<Reference<'static>>);
impl Redirect {
pub fn to<U: TryInto<Reference<'static>>>(uri: U) -> Redirect {
Redirect(Status::SeeOther, uri.try_into().ok())
}
pub fn temporary<U: TryInto<Reference<'static>>>(uri: U) -> Redirect {
Redirect(Status::TemporaryRedirect, uri.try_into().ok())
}
pub fn permanent<U: TryInto<Reference<'static>>>(uri: U) -> Redirect {
Redirect(Status::PermanentRedirect, uri.try_into().ok())
}
pub fn found<U: TryInto<Reference<'static>>>(uri: U) -> Redirect {
Redirect(Status::Found, uri.try_into().ok())
}
pub fn moved<U: TryInto<Reference<'static>>>(uri: U) -> Redirect {
Redirect(Status::MovedPermanently, uri.try_into().ok())
}
}
impl<'r> Responder<'r, 'static> for Redirect {
fn respond_to(self, _: &'r Request<'_>) -> response::Result<'static> {
if let Some(uri) = self.1 {
Response::build()
.status(self.0)
.raw_header("Location", uri.to_string())
.ok()
} else {
error!("Invalid URI used for redirect.");
Err(Status::InternalServerError)
}
}
}