class Imperium::HTTPClient

Attributes

config[R]

Public Class Methods

new(config) click to toggle source
# File lib/imperium/http_client.rb, line 7
def initialize(config)
  @config = config
  @driver = ::HTTPClient.new
  @driver.connect_timeout = @config.connect_timeout
  @driver.send_timeout = @config.send_timeout
  @driver.receive_timeout = @config.receive_timeout
end

Public Instance Methods

delete(path, query: {}) click to toggle source
# File lib/imperium/http_client.rb, line 15
def delete(path, query: {})
  wrapping_exceptions do
    url = config.url.join(path)
    url.query_values = query
    @driver.delete(url, header: build_request_headers)
  end
end
get(path, query: {}) click to toggle source
# File lib/imperium/http_client.rb, line 23
def get(path, query: {})
  wrapping_exceptions do
    url = config.url.join(path)
    url.query_values = query
    @driver.get(url, header: build_request_headers)
  end
end
put(path, value, query: {}) click to toggle source
# File lib/imperium/http_client.rb, line 31
def put(path, value, query: {})
  wrapping_exceptions do
    url = config.url.join(path)
    url.query_values = query
    if value.is_a?(String)
      @driver.put(url, body: value, header: build_request_headers)
    else
      @driver.put(url, body: JSON.generate(value), header: build_request_headers)
    end
  end
end

Private Instance Methods

build_request_headers() click to toggle source
# File lib/imperium/http_client.rb, line 45
def build_request_headers
  if config.token?
    {'X-Consul-Token' => config.token}
  else
    {}
  end
end
wrapping_exceptions() { || ... } click to toggle source

We're doing this wrap and re-raise dance to give a more consistent set of exceptions that can come from us.

# File lib/imperium/http_client.rb, line 55
def wrapping_exceptions
  yield
rescue SocketError => ex
  if ex.message.start_with?("getaddrinfo: Name or service not known")
    raise Imperium::UnableToConnectError, ex.message
  else
    raise
  end
rescue ::HTTPClient::ConnectTimeoutError => ex
  raise Imperium::ConnectTimeout, ex.message
rescue ::HTTPClient::SendTimeoutError => ex
  raise Imperium::SendTimeout, ex.message
rescue ::HTTPClient::ReceiveTimeoutError => ex
  raise Imperium::ReceiveTimeout, ex.message
end