rusthttp-headersresponse-headersrust-axum

How to set a response header in an axum handler?


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.

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


Solution

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