Search code examples
rusthyper

How can I set HTTP status code in hyper HTTP Server handler?


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. =*)


Solution

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