2

According to the documentation I could get mutable reference to the status by calling status_mut(). Unfortunately signature of the handler function, used to serve requests with hyper::Server contain immutable Response, so the following code gives me an error:

pub fn handle_request(req: Request, res: Response<Fresh>){
    let status: &mut StatusCode = res.status_mut();
}

error: cannot borrow immutable local variable `res` as mutable

Is there any way to set response status code in the request handler, used by hyper::server::Server?

UPD: Finally I have found the example. Right in the source code. =*)

hoxnox
  • 355
  • 1
  • 4
  • 16

1 Answers1

3

Mutability in Rust is inherited, so you can just mark the parameter as mutable to get mutability:

pub fn handle_request(req: Request, mut res: Response<Fresh>){
    let status: &mut StatusCode = res.status_mut();
}

This is possible because this function accepts Response<Fresh> by value - if it accepted it by reference: &Response<Fresh>, it would be impossible to modify it at all.

Vladimir Matveev
  • 120,085
  • 34
  • 287
  • 296
  • Thanks. But There is another problem - res bocme borrowed, when I call status_mut(), so I can't use res after this call. I simply try to answer with Response(StatusCode::Forbidden, "Auth failed") in the handler... – hoxnox Apr 14 '15 at 11:22
  • 1
    It is not really clear what you want to do, but there is a universal method when you want to limit borrow boundaries - take the code which creates and uses a borrow in curly braces: `{ let status = res.status_mut(); status.whatever(...); } /* here res is available again */`. – Vladimir Matveev Apr 14 '15 at 11:37