From 253849c2ce9dfbcc8641928021df674eac8facba Mon Sep 17 00:00:00 2001 From: Matt Bearman Date: Thu, 27 Jun 2024 20:52:06 +0100 Subject: [PATCH] Ensure consistent Connection header value Depending on how you start a connection, the `Connection` header may be unexpectedly set to `close` Creating a new instance of `Net::HTTP` and then calling its `request` method (or any of its methods that call `request`, eg: `get`) will first set the `Connection` header to `close` (if it's not already set), then start the connection, and re-call itself Where as initiating a request with class methods, or by manually starting a connection before calling `request` will _not_ set the `Connection` header As the default connection in HTTP 1.1 is `keep-alive`, having the `Connection` header silently set to `close` is unexpected Examples: ```rb uri = URI('https://example.com/test') http = Net::HTTP.new(uri.host, uri.port) http.use_ssl = true req = Net::HTTP::Get.new(uri.path) req['connection'] # => nil res = http.request(req) req['connection'] # => 'close' http = Net::HTTP.new(uri.host, uri.port) http.use_ssl = true http.start req = Net::HTTP::Get.new(uri.path) req['connection'] # => nil res = http.request(req) req['connection'] # => nil ``` From what I can see this functionality was added 24 years ago when implicit starts to GET and HEAD requests were introduced. Not long later the shortcut class methods (eg: `Net::HTTP.get`) were added, which called `start` as part of the method body, bypassing the implicit start therefore not setting the `Connection: close` header, creating inconsistent behaviour This PR stops the `Connection` header from being set to `close` when calling `request` without an open connection, as that matches the behaviour of the more commonly used class methods, as well as allowing the HTTP 1.1 default of `keep-alive` to be used unless the `Connection` header is explicitly set --- lib/net/http.rb | 1 - 1 file changed, 1 deletion(-) diff --git a/lib/net/http.rb b/lib/net/http.rb index 41b8357a..27b46237 100644 --- a/lib/net/http.rb +++ b/lib/net/http.rb @@ -2341,7 +2341,6 @@ def send_request(name, path, data = nil, header = nil) def request(req, body = nil, &block) # :yield: +response+ unless started? start { - req['connection'] ||= 'close' return request(req, body, &block) } end