0

I can't seem to find how to set a header for the response.

I have looked for how to do this but haven't found a straightforward way to do this.

With specific emphasis on the content-type header, How to set both a standard & custom headers from a response handler bearing in mind that I can already do thing.into_response().

Thermatix
  • 2,757
  • 21
  • 51
  • 1
    Are [the docs](https://docs.rs/axum/latest/axum/response/index.html) not clear enough? – Chayim Friedman Jun 26 '23 at 15:46
  • They are if you're handler returns `impl IntoResponse`, my handler returns a `Response` directly otherwise the doc's would have been fine. I did mention `bearing in mind that I can already do thing.into_response()` – Thermatix Jun 26 '23 at 16:07
  • Then why want you return `impl IntoResponse`? Or just call `into_response()`, what is bad with that? – Chayim Friedman Jun 26 '23 at 16:42
  • I can't return `impl IntoResponse` (so I don't) and I do call `into_response()`, I'm not sure what you're trying to say. – Thermatix Jun 27 '23 at 08:17
  • Why can't you return `impl IntoResponse`? And I meant that I don't understand why you seek alternatives if you already know that you can call `into_response()`. – Chayim Friedman Jun 27 '23 at 08:18

1 Answers1

2

Here is an example how you can set a custom response header in your handler:

use axum::http::HeaderMap;
use axum::response::IntoResponse;

async fn my_handler() -> impl IntoResponse {
    let mut headers = HeaderMap::new();
    headers.insert("x-my-hdr", "abc".parse().unwrap());
    (headers, "It works!")
}

I've tested the above with both custom and standard headers (such as Content-Type) and it seems to work in both cases.

at54321
  • 8,726
  • 26
  • 46