Module: ConsulApi::Common::ClassMethods

Defined in:
lib/consul_api/common.rb

Instance Method Summary collapse

Instance Method Details

#consul_api_portObject



32
33
34
# File 'lib/consul_api/common.rb', line 32

def consul_api_port
  @@consul_api_port ||= ENV['CONSUL_API_PORT'] ? ENV['CONSUL_API_PORT'] : 8500
end

#consul_api_urlObject



40
41
42
# File 'lib/consul_api/common.rb', line 40

def consul_api_url
  "http://#{consul_ip}:#{consul_api_port}"
end

#consul_dns_portObject



36
37
38
# File 'lib/consul_api/common.rb', line 36

def consul_dns_port
  @@consul_dns_port ||= ENV['CONSUL_DNS_PORT'] ? ENV['CONSUL_DNS_PORT'] : 8600
end

#consul_ipObject



27
28
29
30
# File 'lib/consul_api/common.rb', line 27

def consul_ip
  # override with an environment variable, or read from the gateway of docker0 interface
  @@consul_ip ||= ENV['CONSUL_IP'] ? ENV['CONSUL_IP'] : `route -n | grep 'UG[ \t]' | awk '{print $2}'`.strip
end

#issue_request(method: :get, path: '', query: nil) ⇒ Object



4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# File 'lib/consul_api/common.rb', line 4

def issue_request(method: :get, path: '', query: nil)
  conn = Faraday.new(:url => "#{base_url}#{path}")
  response = conn.send(method) do |req|
    req.headers['Content-Type'] = 'application/json'
    req.body = query.to_json
  end

  # gets and puts will fail with an http status code in the 4xx and 5xx range
  fail "http status #{response.status} returned from consul" if response.status >= 400

  # return a nil of the response is 'null'
  return nil if response.body == nil || response.body == 'null'
  begin
    # if the response is empty, return an empty hash
    body = response.body == '' ? '{}' : response.body
    parsed_response = JSON.parse(body)
  rescue => e
    fail "unable to parse the json returned by Consul.  Returned data: #{response.body}"
  end

  parsed_response
end