use http::{Request, Response, StatusCode};
use tower_async_layer::Layer;
use tower_async_service::Service;
#[derive(Debug, Clone, Copy)]
pub struct SetStatusLayer {
status: StatusCode,
}
impl SetStatusLayer {
pub fn new(status: StatusCode) -> Self {
SetStatusLayer { status }
}
}
impl<S> Layer<S> for SetStatusLayer {
type Service = SetStatus<S>;
fn layer(&self, inner: S) -> Self::Service {
SetStatus::new(inner, self.status)
}
}
#[derive(Debug, Clone, Copy)]
pub struct SetStatus<S> {
inner: S,
status: StatusCode,
}
impl<S> SetStatus<S> {
pub fn new(inner: S, status: StatusCode) -> Self {
Self { status, inner }
}
define_inner_service_accessors!();
pub fn layer(status: StatusCode) -> SetStatusLayer {
SetStatusLayer::new(status)
}
}
impl<S, ReqBody, ResBody> Service<Request<ReqBody>> for SetStatus<S>
where
S: Service<Request<ReqBody>, Response = Response<ResBody>>,
{
type Response = S::Response;
type Error = S::Error;
async fn call(&self, req: Request<ReqBody>) -> Result<Self::Response, Self::Error> {
let mut response = self.inner.call(req).await?;
*response.status_mut() = self.status;
Ok(response)
}
}