Skip to content

Commit

Permalink
fix: Ignore Content-Length for methods without payload semantics (#429)
Browse files Browse the repository at this point in the history
  • Loading branch information
0x676e67 authored Feb 14, 2025
1 parent 05a1adb commit bd5420c
Showing 1 changed file with 24 additions and 7 deletions.
31 changes: 24 additions & 7 deletions src/util/client/request.rs
Original file line number Diff line number Diff line change
Expand Up @@ -123,9 +123,14 @@ where
/// Set the body for the request.
#[inline]
pub fn body(mut self, body: B) -> Result<InnerRequest<B>, Error> {
if let Some((order, headers)) = self.headers_order.zip(self.builder.headers_mut()) {
add_content_length_header(headers, &body);
sort_headers(headers, order);
if let Some((method, (headers_order, headers))) = self
.builder
.method_ref()
.cloned()
.zip(self.headers_order.zip(self.builder.headers_mut()))
{
add_content_length_header(method, headers, &body);
sort_headers(headers, headers_order);
}

self.builder.body(body).map(|request| InnerRequest {
Expand All @@ -136,6 +141,7 @@ where
}
}

/// Map the HTTP version to the ALPN protocols.
fn map_alpn_protos(version: Version) -> Option<AlpnProtos> {
match version {
Version::HTTP_11 | Version::HTTP_10 | Version::HTTP_09 => Some(AlpnProtos::HTTP1),
Expand All @@ -146,17 +152,28 @@ fn map_alpn_protos(version: Version) -> Option<AlpnProtos> {

/// Add the `Content-Length` header to the request.
#[inline]
fn add_content_length_header<B>(headers: &mut HeaderMap, body: &B)
fn add_content_length_header<B>(method: Method, headers: &mut HeaderMap, body: &B)
where
B: Body,
{
if let Some(len) = Body::size_hint(body).exact() {
headers
.entry(CONTENT_LENGTH)
.or_insert_with(|| HeaderValue::from(len));
if len != 0 || method_has_defined_payload_semantics(method) {
headers
.entry(CONTENT_LENGTH)
.or_insert_with(|| HeaderValue::from(len));
}
}
}

/// Check if the method has defined payload semantics.
#[inline]
pub(super) fn method_has_defined_payload_semantics(method: Method) -> bool {
!matches!(
method,
Method::GET | Method::HEAD | Method::DELETE | Method::CONNECT
)
}

/// Sort the headers in the specified order.
///
/// Headers in `headers_order` are sorted to the front, preserving their order.
Expand Down

0 comments on commit bd5420c

Please sign in to comment.