1
0
mirror of https://github.com/actix/examples synced 2024-11-27 16:02:57 +01:00

fix redirect middleware example

This commit is contained in:
Rob Ede 2022-02-22 12:01:01 +00:00
parent 1206905a11
commit f229251f0d
No known key found for this signature in database
GPG Key ID: 97C636207D3EF933

View File

@ -12,6 +12,7 @@ impl<S, B> Transform<S, ServiceRequest> for CheckLogin
where where
S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = Error>, S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = Error>,
S::Future: 'static, S::Future: 'static,
B: 'static,
{ {
type Response = ServiceResponse<EitherBody<B>>; type Response = ServiceResponse<EitherBody<B>>;
type Error = Error; type Error = Error;
@ -31,6 +32,7 @@ impl<S, B> Service<ServiceRequest> for CheckLoginMiddleware<S>
where where
S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = Error>, S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = Error>,
S::Future: 'static, S::Future: 'static,
B: 'static,
{ {
type Response = ServiceResponse<EitherBody<B>>; type Response = ServiceResponse<EitherBody<B>>;
type Error = Error; type Error = Error;
@ -38,26 +40,28 @@ where
dev::forward_ready!(service); dev::forward_ready!(service);
fn call(&self, req: ServiceRequest) -> Self::Future { fn call(&self, request: ServiceRequest) -> Self::Future {
// We only need to hook into the `start` for this middleware. // We only need to hook into the `start` for this middleware.
let is_logged_in = false; // Change this to see the change in outcome in the browser let is_logged_in = false; // Change this to see the change in outcome in the browser
let (request, payload) = req.into_parts();
let svc_response = self
.service
.call(ServiceRequest::from_parts(request.clone(), payload));
Box::pin(async move {
// Don't forward to /login if we are already on /login // Don't forward to /login if we are already on /login
if is_logged_in || request.path() == "/login" { if is_logged_in || request.path() == "/login" {
svc_response.await.map(ServiceResponse::map_into_left_body) let (request, _pl) = request.into_parts();
} else {
let response = HttpResponse::Found() let response = HttpResponse::Found()
.insert_header((http::header::LOCATION, "/login")) .insert_header((http::header::LOCATION, "/login"))
.finish() .finish()
// constructed responses map to "right" body
.map_into_right_body(); .map_into_right_body();
Ok(ServiceResponse::new(request, response)) return Box::pin(async { Ok(ServiceResponse::new(request, response)) });
} }
let res = self.service.call(request);
Box::pin(async move {
// forwarded responses map to "left" body
res.await.map(ServiceResponse::map_into_left_body)
}) })
} }
} }