2

I want to add Access-Control-Allow-Origin: * for every response my app will make.

According to the docs, AfterMiddleware is exactly for this

In the common case, a complete response is generated by the Chain's Handler and AfterMiddleware simply do post-processing of that Response, such as adding headers or logging.

So I tried to use this like:

struct CorsMiddleware;

impl AfterMiddleware for CorsMiddleware {
    fn after(&self, req: &mut Request, res: Response) -> IronResult<Response> {
        res.headers.set(hyper::header::AccessControlAllowOrigin::Any);
        Ok(res)
    }
}

But I get the error cannot borrow immutable field "res.headers" as mutable. I'm not sure if this caused by immutable Response variable type, but as this is the trait function signature, I can't change it. So, how am I supposed to mutate something immutable? It would be weird to copy the whole response just to add one header, if that's even possible.

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Tommi
  • 3,199
  • 1
  • 24
  • 38
  • 1
    Also it would be awesome if the guy who clicked downvote will explain what exactly I did wrong when created this question. – Tommi Mar 29 '16 at 16:58

1 Answers1

4

Simplest solution

use mut variable

struct CorsMiddleware;

impl AfterMiddleware for CorsMiddleware {
    fn after(&self, req: &mut Request, mut res: Response) -> IronResult<Response> {
        res.headers.set(hyper::header::AccessControlAllowOrigin::Any);
        Ok(res)
    }
}

In Rust when you are the owner of data you can do anything with them, so this should solve your problem.

Hauleth
  • 22,873
  • 4
  • 61
  • 112
  • Thank you, it works. Actually it was exactly what I wanted to do, but for unknown reason I did `res: &mut Response` instead, and this, obviously, is illegal. My understanding of Rust syntax is a big mess for now because I tried to read too much info in a short time period. – Tommi Mar 29 '16 at 17:40
  • 1
    The left hand side of an argument in a function declaration is a pattern, so just like `let mut res = …` would work to make a mutable binding, `mut res` works to make a mutable binding. – Chris Morgan Mar 30 '16 at 01:24
  • 1
    Instead of use Hyper dependecie, you can do it like that: `use iron::headers::{ AccessControlAllowOrigin }; ` `res.headers.set(AccessControlAllowOrigin::Any); ` – NotBad4U Mar 01 '17 at 10:30