Skip to content

Commit 52c35e7

Browse files
committed
cleanup attempts for uri building
1 parent d163606 commit 52c35e7

File tree

2 files changed

+32
-10
lines changed

2 files changed

+32
-10
lines changed

lib/webmachine/request.rb

Lines changed: 29 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
require 'cgi'
22
require 'forwardable'
33
require 'webmachine/constants'
4+
require 'ipaddr'
45

56
module Webmachine
67
# Request represents a single HTTP request sent from a client. It
@@ -165,19 +166,40 @@ def options?
165166

166167
private
167168

169+
IPV6_MATCH = /\A\[(?<address> .* )\]:(?<port> \d+ )\z/x.freeze # string like "[::1]:80"
170+
IPV4_MATCH = /\A(?<address> [^:]+ ):(?<port> \d+ )\z/x.freeze # string like "127.0.0.1:80"
171+
172+
def parse_addr(string)
173+
# Split host and port number from string.
174+
case string
175+
when IPV6_MATCH
176+
address = $~[:address]
177+
port = $~[:port]
178+
when IPV4_MATCH
179+
address = $~[:address]
180+
port = $~[:port]
181+
else # string with no port number
182+
address = string
183+
port = nil
184+
end
185+
186+
# Pass address, port to Addrinfo.tcp. It will raise SocketError if address or port is not valid.
187+
Addrinfo.tcp(address, port)
188+
end
189+
168190
def build_uri(uri, headers)
169191
uri = URI(uri)
192+
if uri.host
193+
return uri
194+
end
170195

171-
host, _, port = headers.fetch(HOST, "").rpartition(COLON)
172-
return uri if host.empty?
173-
174-
host = "[#{host}]" if host.include?(COLON)
175-
port = 80 if port.empty?
196+
addr = parse_addr(headers.fetch(HOST))
176197

177198
uri.scheme = HTTP
178-
uri.host, uri.port = host, port.to_i
199+
uri.host = addr.ip_address
200+
uri.port = addr.ip_port == 0 ? 80 : addr.ip_port
179201

180-
URI.parse(uri.to_s)
202+
uri
181203
end
182204

183205
end # class Request

lib/webmachine/spec/adapter_lint.rb

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
require "webmachine/spec/test_resource"
1+
require "webmachine/spec/test_resource"
22
require "net/http"
33

44
shared_examples_for :adapter_lint do
@@ -57,8 +57,8 @@
5757
let(:address) { "::1" }
5858

5959
it "provides the IPv6 request URI" do
60-
if RUBY_VERSION =~ /^2\.(0|1)\./
61-
skip "Net::HTTP regression in Ruby 2.(0|1)"
60+
if RUBY_VERSION =~ /^2\.(0|1\2)\./
61+
skip "Net::HTTP regression in Ruby 2.(0|1|2)"
6262
end
6363

6464
request = Net::HTTP::Get.new("/test")

0 commit comments

Comments
 (0)