lib/async/http/client.rb in async-http-0.6.0 vs lib/async/http/client.rb in async-http-0.8.0
- old
+ new
@@ -23,55 +23,59 @@
require_relative 'protocol'
module Async
module HTTP
class Client
- def initialize(endpoints, protocol_class = Protocol::HTTP11)
- @endpoints = endpoints
+ def initialize(endpoint, protocol = Protocol::HTTPS, **options)
+ @endpoint = endpoint
- @protocol_class = protocol_class
+ @protocol = protocol
+
+ @connections = connect(**options)
end
- GET = 'GET'.freeze
- HEAD = 'HEAD'.freeze
- POST = 'POST'.freeze
-
- def get(path, *args)
- connect do |protocol|
- protocol.send_request(GET, path, *args)
+ def self.open(*args, &block)
+ client = self.new(*args)
+
+ return client unless block_given?
+
+ begin
+ yield client
+ ensure
+ client.close
end
end
- def head(path, *args)
- connect do |protocol|
- protocol.send_request(HEAD, path, *args)
- end
+ def close
+ @connections.close
end
- def post(path, *args)
- connect do |protocol|
- protocol.send_request(POST, path, *args)
+ VERBS = ['GET', 'HEAD', 'POST', 'PUT', 'PATCH', 'DELETE']
+
+ VERBS.each do |verb|
+ define_method(verb.downcase) do |*args|
+ self.request(verb, *args)
end
end
- def send_request(*args)
- connect do |protocol|
- protocol.send_request(*args)
+ def request(*args)
+ @connections.acquire do |connection|
+ connection.send_request(*args)
end
end
- private
+ protected
- def connect
- Async::IO::Endpoint.each(@endpoints) do |endpoint|
- # puts "Connecting to #{address} on process #{Process.pid}"
+ def connect(connection_limit: nil)
+ Pool.new(connection_limit) do
+ Async.logger.debug(self) {"Making connection to #{@endpoint.inspect}"}
- endpoint.connect do |peer|
- stream = Async::IO::Stream.new(peer)
+ @endpoint.each do |endpoint|
+ peer = endpoint.connect
- # We only yield for first successful connection.
+ stream = IO::Stream.new(peer)
- return yield @protocol_class.new(stream)
+ break @protocol.client(stream)
end
end
end
end
end