use crate::Request;
use crate::Response;
use crate::service::web::response;
use rama_core::Service;
use rama_http_headers::{HeaderMapExt, Location};
use rama_http_types::body::OptionalBody;
use std::{convert::Infallible, fmt, marker::PhantomData};
pub struct RedirectStatic<ResBody> {
resp: response::Redirect,
_marker: PhantomData<fn() -> ResBody>,
}
impl<ResBody> RedirectStatic<ResBody> {
pub fn to(loc: impl response::redirect::IntoRedirectLoc) -> Self {
Self {
resp: response::Redirect::to(loc),
_marker: PhantomData,
}
}
pub fn moved(loc: impl response::redirect::IntoRedirectLoc) -> Self {
Self {
resp: response::Redirect::moved(loc),
_marker: PhantomData,
}
}
pub fn found(loc: impl response::redirect::IntoRedirectLoc) -> Self {
Self {
resp: response::Redirect::found(loc),
_marker: PhantomData,
}
}
pub fn temporary(loc: impl response::redirect::IntoRedirectLoc) -> Self {
Self {
resp: response::Redirect::temporary(loc),
_marker: PhantomData,
}
}
pub fn permanent(loc: impl response::redirect::IntoRedirectLoc) -> Self {
Self {
resp: response::Redirect::permanent(loc),
_marker: PhantomData,
}
}
}
impl<Body, ResBody> Service<Request<Body>> for RedirectStatic<ResBody>
where
Body: Send + 'static,
ResBody: Send + 'static,
{
type Output = Response<OptionalBody<ResBody>>;
type Error = Infallible;
async fn serve(&self, _req: Request<Body>) -> Result<Self::Output, Self::Error> {
let mut res = Response::default();
*res.status_mut() = self.resp.status_code();
res.headers_mut()
.typed_insert(Location::new(self.resp.location().clone()));
Ok(res)
}
}
impl<ResBody> fmt::Debug for RedirectStatic<ResBody> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("RedirectStatic")
.field("response", &self.resp)
.finish()
}
}
impl<ResBody> Clone for RedirectStatic<ResBody> {
fn clone(&self) -> Self {
Self {
resp: self.resp.clone(),
_marker: PhantomData,
}
}
}