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?

1 Answer 1

4
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"))

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks, if I wanted to implement this trait on my type, say a single &str "'X-Hdr':'sample'", how would I do this?
You would create a wrapper type and implement the try_into_header_pair method by splitting on a colon.
I don't see why you would want to do this though.
While it does not really serve a purpose, I need to get a better understanding of how traits work. I had reviewed the source code and saw the implementation, but was unable to interpret it correctly. So TLDR; simple as an exercise ;-) Thanks again for the help.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.