1

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"?

DFG
  • 31
  • 1
  • 13
  • Could you please show your code that used `Response::builer` and what errors did you got. This seems to be a correct way of solving your problems. Maybe you missed something. – Aleksander Krauze Oct 27 '22 at 22:24

1 Answers1

1

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();
Aleksander Krauze
  • 3,115
  • 7
  • 18
  • When executing the exact code you give me and returning it with `Ok(response)` I get this error: `expected struct Body, found &str` – DFG Oct 27 '22 at 23:52
  • @New1 Fixed. I forgot to call `into`. – Aleksander Krauze Oct 28 '22 at 07:10
  • Thank you very much, no more error. I'm really going to give you the reward because you replied to the main topic (I'll give you the bounty in 5 hours since I can't give it to you yet because 24 hours haven't passed). But with my actual code what I do is create the `Response::builder()` and lines later I add the headers, but I add them individually, and that gives me this error: `expected struct hyper::Response, found struct hyper ::http::response::Builder`. Just as extra help (obviously optional, since you already answered the main topic of the question) do you know how I could solve it? – DFG Oct 28 '22 at 16:49
  • @New1 Hi. If you would like more help We can talk here: https://chat.stackoverflow.com/rooms/249155/rusts-hyper-library – Aleksander Krauze Oct 29 '22 at 18:34