use std::convert::TryInto;
use request::Request;
use response::{Response, Responder};
use http::uri::Uri;
use http::Status;
#[derive(Debug)]
pub struct Redirect(Status, Option<Uri<'static>>);
impl Redirect {
pub fn to<U: TryInto<Uri<'static>>>(uri: U) -> Redirect {
Redirect(Status::SeeOther, uri.try_into().ok())
}
pub fn temporary<U: TryInto<Uri<'static>>>(uri: U) -> Redirect {
Redirect(Status::TemporaryRedirect, uri.try_into().ok())
}
pub fn permanent<U: TryInto<Uri<'static>>>(uri: U) -> Redirect {
Redirect(Status::PermanentRedirect, uri.try_into().ok())
}
pub fn found<U: TryInto<Uri<'static>>>(uri: U) -> Redirect {
Redirect(Status::Found, uri.try_into().ok())
}
pub fn moved<U: TryInto<Uri<'static>>>(uri: U) -> Redirect {
Redirect(Status::MovedPermanently, uri.try_into().ok())
}
}
impl<'a> Responder<'a> for Redirect {
fn respond_to(self, _: &Request) -> Result<Response<'static>, Status> {
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)
}
}
}