Class: AppMonit::Http

Inherits:
Object
  • Object
show all
Defined in:
lib/app_monit/http.rb

Constant Summary collapse

Error =
Class.new(StandardError)
SUCCESS_CODES =
%w(200 201).freeze

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeHttp

Returns a new instance of Http.



9
10
11
12
13
14
15
16
17
18
# File 'lib/app_monit/http.rb', line 9

def initialize
  uri     = URI.parse(AppMonit::Config.end_point)
  @client = Net::HTTP.new(uri.host, uri.port)
  if uri.scheme == 'https'
    @client.use_ssl = true
    @client.verify_mode  = OpenSSL::SSL::VERIFY_PEER
  end

  @client.read_timeout = AppMonit::Config.timeout if AppMonit::Config.timeout > 0
end

Instance Attribute Details

#clientObject

Returns the value of attribute client.



7
8
9
# File 'lib/app_monit/http.rb', line 7

def client
  @client
end

Class Method Details

.get(path) ⇒ Object



24
25
26
# File 'lib/app_monit/http.rb', line 24

def self.get(path)
  request :get, path
end

.post(path, data_hash) ⇒ Object



20
21
22
# File 'lib/app_monit/http.rb', line 20

def self.post(path, data_hash)
  request :post, path, data_hash
end

.request(*args) ⇒ Object



28
29
30
# File 'lib/app_monit/http.rb', line 28

def self.request(*args)
  new.request(*args)
end

Instance Method Details

#request(method, path, body = nil) ⇒ Object

Raises:



32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/app_monit/http.rb', line 32

def request(method, path, body = nil)
  if method == :get
    request = Net::HTTP::Get.new(path)
  else
    request              = Net::HTTP::Post.new(path)
    request.body         = body.to_json if body
    request.content_type = 'application/json'
  end

  # set headers so event data ends up in the correct bucket on the other side
  # only add Appmonit-Api-Key header if there was no api_key configured in the params
  request.add_field('Appmonit-Api-Key', AppMonit::Config.api_key) unless api_key(path)
  request.add_field('Appmonit-Env', AppMonit::Config.env)
  response = client.request(request)

  raise Error.new("Invalid response code: #{response.code} body: #{response.body}") unless SUCCESS_CODES.include?(response.code)

  response
end