use crate::http::headers::LOCATION;
use crate::StatusCode;
use crate::{Endpoint, Request, Response};
#[derive(Debug, Clone)]
pub struct Redirect<T: AsRef<str>> {
status: StatusCode,
location: T,
}
impl<T: AsRef<str>> Redirect<T> {
pub fn new(location: T) -> Self {
Self {
status: StatusCode::Found,
location,
}
}
pub fn permanent(location: T) -> Self {
Self {
status: StatusCode::PermanentRedirect,
location,
}
}
pub fn temporary(location: T) -> Self {
Self {
status: StatusCode::TemporaryRedirect,
location,
}
}
pub fn see_other(location: T) -> Self {
Self {
status: StatusCode::SeeOther,
location,
}
}
}
#[async_trait::async_trait]
impl<State, T> Endpoint<State> for Redirect<T>
where
State: Clone + Send + Sync + 'static,
T: AsRef<str> + Send + Sync + 'static,
{
async fn call(&self, _req: Request<State>) -> crate::Result<Response> {
Ok(self.into())
}
}
impl<T: AsRef<str>> Into<Response> for Redirect<T> {
fn into(self) -> Response {
(&self).into()
}
}
impl<T: AsRef<str>> Into<Response> for &Redirect<T> {
fn into(self) -> Response {
let mut res = Response::new(self.status);
res.insert_header(LOCATION, self.location.as_ref());
res
}
}