3

I am trying to create a response inside a handler with actix-web v4.

The header method has changed to append_header which now instead of a key value pair takes a header object.

The original documentation here gives the following example:

use actix_web::HttpResponse;

async fn index() -> HttpResponse {
    HttpResponse::Ok()
        .content_type("plain/text")
        .header("X-Hdr", "sample")
        .body("data")
}

I can create a header with append_header(ContentType::plaintext()) with a predefined mime name, but I haven't found any way to create a custom type.

I would have expected something like Header::from("'X-Hdr': 'sample'") to work but haven't found any way to create this header.

What would be the right way to create the 'X-Hdr':'sample' header in actix-web v4?

Johannes Maria Frank
  • 2,747
  • 1
  • 29
  • 38

1 Answers1

3
pub fn append_header<H>(&mut self, header: H) -> &mut Self where
    H: IntoHeaderPair, 

The append_header method takes any type implementing IntoHeaderPair. If you look at the documentation for the trait you will see that it is implemented for:

(&'_ HeaderName, V)
(&'_ str, V)
(HeaderName, V)
(&'_ [u8], V)
(String, V)

V is any type implementing IntoHeaderValue, which includes String, &str, Vec, and integer types.

Therefore you can simply write .append_header(("X-Hdr", "sample"))

Ibraheem Ahmed
  • 11,652
  • 2
  • 48
  • 54