Skip to content

Commit

Permalink
HTTP::Client: set connection: close header on one-shot requests (#6410
Browse files Browse the repository at this point in the history
)
  • Loading branch information
asterite authored and Serdar Dogruyol committed Jul 20, 2018
1 parent 6ab9c60 commit 1b83706
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 0 deletions.
28 changes: 28 additions & 0 deletions spec/std/http/client/client_spec.cr
Expand Up @@ -129,6 +129,34 @@ module HTTP
spawn { server.listen }

HTTP::Client.get("http://[::1]:#{address.port}/").body.should eq("[::1]:#{address.port}")

server.close
end

it "sends a 'connection: close' header on one-shot request" do
server = HTTP::Server.new do |context|
context.response.print context.request.headers["connection"]
end
address = server.bind_unused_port "::1"
spawn { server.listen }

HTTP::Client.get("http://[::1]:#{address.port}/").body.should eq("close")

server.close
end

it "sends a 'connection: close' header on one-shot request with block" do
server = HTTP::Server.new do |context|
context.response.print context.request.headers["connection"]
end
address = server.bind_unused_port "::1"
spawn { server.listen }

HTTP::Client.get("http://[::1]:#{address.port}/") do |response|
response.body_io.gets_to_end
end.should eq("close")

server.close
end

it "doesn't read the body if request was HEAD" do
Expand Down
9 changes: 9 additions & 0 deletions src/http/client.cr
Expand Up @@ -575,6 +575,13 @@ class HTTP::Client
{% end %}
end

# For one-shot headers we don't want keep-alive (might delay closing the response)
private def self.default_one_shot_headers(headers)
headers ||= HTTP::Headers.new
headers["Connection"] ||= "close"
headers
end

private def run_before_request_callbacks(request)
@before_request.try &.each &.call(request)
end
Expand Down Expand Up @@ -614,6 +621,7 @@ class HTTP::Client
# response.body # => "..."
# ```
def self.exec(method, url : String | URI, headers : HTTP::Headers? = nil, body : BodyType = nil, tls = nil) : HTTP::Client::Response
headers = default_one_shot_headers(headers)
exec(url, tls) do |client, path|
client.exec method, path, headers, body
end
Expand All @@ -628,6 +636,7 @@ class HTTP::Client
# end
# ```
def self.exec(method, url : String | URI, headers : HTTP::Headers? = nil, body : BodyType = nil, tls = nil)
headers = default_one_shot_headers(headers)
exec(url, tls) do |client, path|
client.exec(method, path, headers, body) do |response|
yield response
Expand Down

0 comments on commit 1b83706

Please sign in to comment.