hyperium / hyper

An HTTP library for Rust
https://hyper.rs
MIT License
14.34k stars 1.58k forks source link

Could we have automatic content type header ? #2460

Closed Stargateur closed 3 years ago

Stargateur commented 3 years ago

I do not deal with HTTP often so as a newbie, I get confused that the API (use foalts) don't understand my request if I don't set CONTENT_TYPE (foalts body is empty if I don't put content_type very confusing IMO). So, I now do:

let response = client.request(
        Request::builder()
            .method(Method::POST)
            .uri(uri)
            .header(CONTENT_TYPE, "application/json")
            .body(Body::from(body))

Is this the recommended way ? I didn't deal with headers so far so I expected hyper would do it for me. Could we have a BodyJson type that handle that for us, should I code it myself implementing HttpBody trait ? Or it's a bad idea ? Any recommendation ?

seanmonstar commented 3 years ago

hyper has no way of knowing what the content-type of the body is, so it doesn't add a header automatically. Additionally, it's not uncommon for a specific format of a body to be specified with a different content-type (JSON could be sent as application/vnd.github.v3+json in the GitHub API, for example).

hyper is designed to not have an opinion on this, as adding a header is the simple and correct option from hyper's point of view. If you're just looking for an HTTP client to handle many of the things you'd normally expect, you may want to look at reqwest.