Actix-web, middleware: how to access a custom header, please help

Hi,

I'm learning actix_web::middleware... And I'm stuck. Please help.

I have this endpoint service handler, and it works:

#[post("/login")]
pub async fn login1(
    _: HttpRequest
) -> impl Responder {
    let serve_login_page = || -> HttpResponse {
        HttpResponse::Ok()
            .status(StatusCode::TEMPORARY_REDIRECT)
            .append_header((header::LOCATION, "/login"))
            .finish()
    };

    let serve_home_page = || -> HttpResponse {
        HttpResponse::Ok()
            .status(StatusCode::TEMPORARY_REDIRECT)
            .append_header(("behai-header", "behai_sample_header"))
            .append_header((header::LOCATION, "/home"))
            .finish()                    
    };

    let condition: bool = true;

    if condition {
        serve_home_page()
    }
    else {
        serve_login_page()
    }
}

The redirect in the closure serve_home_page eventually goes to the middleware method:

fn call(&self, request: ServiceRequest) -> Self::Future

In call, how to do I access my custom header behai-header to print out behai_sample_header, please?

I don't even know if it's a response header or a request header in call :(...

Thank you and best regards,

...behai.

fn call(&self, req: ServiceRequest) -> Self::Future {
        let behai_header_value = req.headers().get("behai-header").expect("There was no behai-header on the request");
}
1 Like

Hi moy2010,

Thank you very much for your prompt helps... I have tried it out, there is no behai-header found.

Best regards,

...behai.

Sorry, I didn't read carefully your first comment and thought you wanted to access a header from the request.

Can you try this instead?

fn call(&self, req: ServiceRequest) -> Self::Future {
  let fut = self.service.call(req);

  Box::pin(async move {
      let res: ServiceResponse<B> = fut.await.unwrap();

      let behai_header_value = res.headers().get("behai-header").expect("There was no behai-header on the response");

      Ok(res)
  })
}

Hi,

Thank you. I do apologise, it's my bad, I forgot to mention that, in the middleware the Response is type Response = ServiceResponse<EitherBody<B>>;.

I don't know what to replace Ok(res) with yet?

I don't think I need to use EitherBody. I will try to refactor it and continue with this.

Best regards,

...behai.

Hi,

This actually IS the solution I've been looking for.

My thinking was wrong: I assumed having behai-header ONLY under specific situtations, while I should assume it's always present or not in all requests.

Thank you kindly for your helps @firebits.io. I appreciate it.

Best regards,

...behai.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.