rusthyper

How can I return customizing headers in hyper? Rust


What I want to do is return custom headers in hyper (but return them and return the response body as well) For example, I'm going to take the code from the hyper documentation as an example:

async fn handle(_: Request<Body>) -> Result<Response<Body>, Infallible> {
    Ok(Response::new("Hello, World!".into()))
}

For example, this code only displays Hello World! on every request, and always returns a 200 status code. But for example, How can I send other types of custom headers? What I tried was to use Response::builder instead of Response::new (as you can see in my example I use ::new, what I tried separately was to use ::builder) but it gave errors since that type of data cannot be returned. So how can I return the header I want and as many as I want but keeping the "body"?


Solution

  • In general your idea of using Response::builder seems to be correct. Note however that it returns a Builder, which method body must be later used to create a Response. As body's documentation states:

    “Consumes” this builder, using the provided body to return a constructed Response.

    A working example of setting custom headers of a response (how many you like) you can see in the documentation of Builder::header. It looks like this:

    let body = "Hello, world!";
    
    let response = Response::builder()
        .header("Content-Type", "text/html")
        .header("X-Custom-Foo", "bar")
        .header("content-length", body.len())
        .body(body.into())
        .unwrap();