Skip to content

Commit

Permalink
Return true for Body::is_empty for HEAD responses (#343)
Browse files Browse the repository at this point in the history
Fixes #341.
  • Loading branch information
sagebind committed Sep 5, 2021
1 parent 422d4b0 commit ca24e04
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 10 deletions.
26 changes: 16 additions & 10 deletions src/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1166,6 +1166,8 @@ impl crate::interceptor::Invoke for &HttpClient {
mut request: Request<AsyncBody>,
) -> crate::interceptor::InterceptorFuture<'_, Error> {
Box::pin(async move {
let is_head_request = request.method() == http::Method::HEAD;

// Set default user agent if not specified.
request
.headers_mut()
Expand Down Expand Up @@ -1212,17 +1214,21 @@ impl crate::interceptor::Invoke for &HttpClient {

// Convert the reader into an opaque Body.
Ok(response.map(|reader| {
let body = ResponseBody {
inner: reader,
// Extend the lifetime of the agent by including a reference
// to its handle in the response body.
_client: (*self).clone(),
};

if let Some(len) = body_len {
AsyncBody::from_reader_sized(body, len)
if is_head_request {
AsyncBody::empty()
} else {
AsyncBody::from_reader(body)
let body = ResponseBody {
inner: reader,
// Extend the lifetime of the agent by including a reference
// to its handle in the response body.
_client: (*self).clone(),
};

if let Some(len) = body_len {
AsyncBody::from_reader_sized(body, len)
} else {
AsyncBody::from_reader(body)
}
}
}))
})
Expand Down
26 changes: 26 additions & 0 deletions tests/response_body.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,18 @@ fn simple_response_body() {
assert_eq!(response_text, "hello world");
}

#[test]
fn zero_length_response_body() {
let m = mock! {
body: "",
};

let response = isahc::get(m.url()).unwrap();

assert_eq!(response.body().len(), Some(0));
assert!(!response.body().is_empty());
}

#[test]
fn large_response_body() {
let body = "wow so large ".repeat(1000);
Expand Down Expand Up @@ -58,6 +70,20 @@ fn response_body_with_chunked_encoding_has_unknown_size() {
assert_eq!(response.body().len(), None);
}

// See issue #341.
#[test]
fn head_request_with_content_length_response_returns_empty_body() {
let m = mock! {
headers {
"content-length": 767,
}
};

let response = isahc::head(m.url()).unwrap();

assert!(response.body().is_empty());
}

// See issue #64.
#[test]
fn dropping_client_does_not_abort_response_transfer() {
Expand Down

0 comments on commit ca24e04

Please sign in to comment.