Question

How do I set response headers in Axum?

Answer and Explanation

Setting response headers in Axum, a web framework for Rust, is straightforward. You can achieve this by using the Response type and its associated methods. Here's a comprehensive guide:

1. Using `Response::builder()`:

- The most common way to set headers is by using the Response::builder() method. This allows you to construct a response step-by-step, including setting headers, status codes, and the body.

2. Setting Headers with `header()`:

- The header() method is used to add or modify headers. It takes the header name and value as arguments. You can chain multiple header() calls to set multiple headers.

3. Example Code:

use axum::{ response::{IntoResponse, Response}, routing::get, Router, }; use http::header; async fn handler() -> impl IntoResponse { let body = "Hello, Headers!"; Response::builder() .status(200) .header(header::CONTENT_TYPE, "text/plain") .header("X-Custom-Header", "Custom Value") .body(body.into()) .unwrap() } #[tokio::main] async fn main() { let app = Router::new().route("/", get(handler)); let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap(); axum::serve(listener, app).await.unwrap(); }

4. Explanation:

- The handler function constructs a Response using Response::builder().

- It sets the HTTP status code to 200 (OK) using status(200).

- It sets the Content-Type header to text/plain using header(header::CONTENT_TYPE, "text/plain").

- It sets a custom header X-Custom-Header to Custom Value using header("X-Custom-Header", "Custom Value").

- Finally, it sets the response body using body(body.into()).

5. Using `IntoResponse` Trait:

- Axum also allows you to return types that implement the IntoResponse trait. This can simplify the process for common cases. For example, you can return a tuple of (StatusCode, HeaderMap, String), which will be converted into a Response.

6. Example with `IntoResponse`:

use axum::{ http::StatusCode, response::IntoResponse, routing::get, Router, }; use http::HeaderMap; async fn handler() -> impl IntoResponse { let mut headers = HeaderMap::new(); headers.insert("X-Custom-Header", "Custom Value".parse().unwrap()); (StatusCode::OK, headers, "Hello, Headers!".to_string()) } #[tokio::main] async fn main() { let app = Router::new().route("/", get(handler)); let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap(); axum::serve(listener, app).await.unwrap(); }

7. Explanation:

- The handler function returns a tuple of (StatusCode, HeaderMap, String).

- A HeaderMap is created and populated with the custom header.

- Axum automatically converts this tuple into a Response.

By using these methods, you can effectively set response headers in your Axum applications, allowing you to control various aspects of the HTTP response.

More questions