Usable, fast, simple HTTP 1.1 for Ruby
Usable, fast, simple Ruby HTTP 1.1
Excon was designed to be simple, fast and performant. It works great as a general HTTP(s) client and is particularly well suited to usage in API clients.
Install the gem.
$ sudo gem install exconRequire with rubygems.
require 'rubygems'
require 'excon'The easiest way to get started is by using one-off requests. Supported one-off request methods are connect, delete, get, head, options, post, put, and trace. Requests return a response object which has body, headers, remote_ip and status attributes.
response = Excon.get('http://geemus.com')
response.body # => "..."
response.headers # => {...}
response.remote_ip # => "..."
response.status # => 200For API clients or other ongoing usage, reuse a connection across multiple requests to share options and improve performance.
connection = Excon.new('http://geemus.com')
get_response = connection.get
post_response = connection.post(:path => '/foo')
delete_response = connection.delete(:path => '/bar')By default, each connection is non-persistent. This means that each request made against a connection behaves like a one-off request. Each request will establish a socket connection to the server, then close the socket once the request is complete.
To use a persistent connection, use the :persistent option:
connection = Excon.new('http://geemus.com', :persistent => true)The initial request will establish a socket connection to the server and leave the socket open. Subsequent requests
will reuse that socket. You may call Connection#reset at any time to close the underlying socket, and the next request
will establish a new socket connection.
You may also control persistence on a per-request basis by setting the :persistent option for each request.
…Note that sending a request with :persistent => false to close the socket will also send Connection: close to inform
the server the connection is no longer needed. Connection#reset will simply close our end of the socket.
Both one-off and persistent connections support many other options. The final options for a request are built up by starting with Excon.defaults, then merging in options from the connection and finally merging in any request options. In this way you have plenty of options on where and how to set options and can easily setup connections or defaults to match common options for a particular endpoint.
Here are a few common examples:
…Compared to web browsers and other http client libraries, e.g. curl, Excon is a bit more low-level and doesn't assume much by default. If you are seeing different results compared to other clients, the following options might help:
# opt-in to omitting port from http:80 and https:443
connection = Excon.new('http://geemus.com/', :omit_default_port => true)
# accept gzip encoding
connection = Excon.new('http://geemus.com/', :headers => { "Accept-Encoding" => "gzip" })
# turn off peer verification (less secure)
Excon.defaults[:ssl_verify_peer] = false
connection = Excon.new('https://...')You can modify timeouts and define whether and how many (blocking) retries Excon should attempt if errors occur.
…You can make Transfer-Encoding: chunked requests by passing a block that will deliver chunks, delivering an empty chunk to signal completion.
file = File.open('data')
chunker = lambda do
# Excon.defaults[:chunk_size] defaults to 1048576, ie 1MB
# to_s will convert the nil received after everything is read to the final empty chunk
file.read(Excon.defaults[:chunk_size]).to_s
end
Excon.post('http://geemus.com', :request_block => chunker)
file.closeIterating in this way allows you to have more granular control over writes and to write things where you can not calculate the overall length up front.
You can make use of HTTP pipelining to improve performance. Instead of the normal request/response cycle, pipelining sends a series of requests and then receives a series of responses. You can take advantage of this using the requests method, which takes an array of params where each is a hash like request would receive and returns an array of responses.
connection = Excon.new('http://geemus.com/')
connection.requests([{:method => :get}, {:method => :get}])By default, each call to requests will use a separate persistent socket connection. To make multiple requests calls
using a single persistent connection, set :persistent => true when establishing the connection.
For large numbers of simultaneous requests please consider using the batch_requests method. This will automatically slice up the requests into batches based on the file descriptor limit of your operating system. The results are the same as the requests method, but using this method can help prevent timeout errors.
large_array_of_requests = [{:method => :get, :path => 'some_path'}, { ... }] # Hundreds of items
connection.batch_requests(large_array_of_requests)You can stream responses by passing a block that will receive each chunk.
streamer = lambda do |chunk, remaining_bytes, total_bytes|
puts chunk
puts "Remaining: #{remaining_bytes.to_f / total_bytes}%"
end
Excon.get('http://geemus.com', :response_block => streamer)Iterating over each chunk will allow you to do work on the response incrementally without buffering the entire response first. For very large responses this can lead to significant memory savings.
You can specify a proxy URL that Excon will use with both HTTP and HTTPS connections:
connection = Excon.new('http://geemus.com', :proxy => 'http://my.proxy:3128')
connection.request(:method => 'GET')
Excon.get('http://geemus.com', :proxy => 'http://my.proxy:3128')The proxy URL must be fully specified, including scheme (e.g. "http://") and port.
Proxy support must be set when establishing a connection object and cannot be overridden in individual requests.
NOTE: Excon will use HTTP_PROXY and HTTPS_PROXY environment variables. If set they will take precedence over any :proxy option specified in code. If "HTTPS_PROXY" is not set, "HTTP_PROXY" will be used for both HTTP and HTTPS connections. To disable this behavior, set the NO_PROXY environment variable and other environment variable proxy settings will be disregarded.
For advanced cases where you'd like to reuse the local port assigned to the excon socket in another socket, use the :reuseaddr option.
connection = Excon.new('http://geemus.com', :reuseaddr => true)
connection.get
s = Socket.new(Socket::AF_INET, Socket::SOCK_STREAM, 0)
s.setsockopt(Socket::SOL_SOCKET, Socket::SO_REUSEADDR, true)
if defined?(Socket::SO_REUSEPORT)
s.setsockopt(Socket::SOL_SOCKET, Socket::SO_REUSEPORT, true)
end
s.bind(Socket.pack_sockaddr_in(connection.local_port, connection.local_address))
s.connect(Socket.pack_sockaddr_in(80, '1.2.3.4'))
puts s.read
s.closeThe Unix socket will work for one-off requests and multiuse connections. A Unix socket path must be provided separate from the resource path.
connection = Excon.new('unix:///', :socket => '/tmp/puma.sock')
connection.request(:method => :get, :path => '/ping')
Excon.get('unix:///ping', :socket => '/tmp/puma.sock')NOTE: Proxies will be ignored when using a Unix socket, since a Unix socket has to be local.
You can stub out requests for testing purposes by enabling mock mode on a connection.
connection = Excon.new('http://example.com', :mock => true)Or by enabling mock mode for a request.
connection.request(:method => :get, :path => 'example', :mock => true)Add stubs by providing the request attributes to match and response attributes to return. Response params can be specified as either a hash or block which will yield with the request params.
Excon.stub({}, {:body => 'body', :status => 200})
Excon.stub({}, lambda {|request_params| {:body => request_params[:body], :status => 200}})Omitted attributes are assumed to match, so this stub will match any request and return an Excon::Response with a body of 'body' and status of 200.
Excon.stub({ :scheme => 'https', :host => 'example.com', :path => /\/examples\/\d+/, :port => 443 }, { body: 'body', status: 200 })The above code will stub this:
Excon.get('https://example.com/examples/123', mock: true)You can add whatever stubs you might like this way and they will be checked against in the order they were added, if none of them match then excon will raise an Excon::Errors::StubNotFound error to let you know.
If you want to allow unstubbed requests without raising StubNotFound, set the allow_unstubbed_requests option either globally or per request.
connection = Excon.new('http://example.com', :mock => true, :allow_unstubbed_requests => true)To remove a previously defined stub, or all stubs:
Excon.unstub({}) # remove first/oldest stub matching {}
Excon.stubs.clear # remove all stubsFor example, if using RSpec for your test suite you can clear stubs after running each example:
config.after(:each) do
Excon.stubs.clear
endYou can also modify Excon.defaults to set a stub for all requests, so for a test suite you might do this:
# Mock by default and stub any request as success
config.before(:all) do
Excon.defaults[:mock] = true
Excon.stub({}, {:body => 'Fallback', :status => 200})
# Add your own stubs here or in specific tests...
endBy default stubs are shared globally, to make stubs unique to each thread, use Excon.defaults[:stubs] = :local.
Excon calls can be timed using the ActiveSupport::Notifications API.
connection = Excon.new(
'http://geemus.com',
:instrumentor => ActiveSupport::Notifications
)Excon will then instrument each request, retry, and error. The corresponding events are named excon.request, excon.retry, and excon.error respectively.
ActiveSupport::Notifications.subscribe(/excon/) do |*args|
puts "Excon did stuff!"
endIf you prefer to label each event with a namespace other than "excon", you may specify an alternate name in the constructor:
connection = Excon.new(
'http://geemus.com',
:instrumentor => ActiveSupport::Notifications,
:instrumentor_name => 'my_app'
)Note: Excon's ActiveSupport::Notifications implementation has the following event format: . which is the opposite of the Rails' implementation.
ActiveSupport provides a subscriber interface which lets you attach a subscriber to a namespace. Due to the incompability above, you won't be able to attach a subscriber to the "excon" namespace out of the box.
If you want this functionality, you can use a simple adapter such as this one:
class ExconToRailsInstrumentor
def self.instrument(name, datum, &block)
namespace, *event = name.split(".")
rails_name = [event, namespace].flattNo open issues yet, or sync has not completed.