rustiron

How to add a header in Iron's AfterMiddleware?


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.


Solution

  • 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.