Class: Ip2Geo::Helpers::Http

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

Class Method Summary collapse

Class Method Details

.request(endpoint, body = nil) ⇒ Object



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/ip2geo/helpers/http.rb', line 12

def request(endpoint, body = nil)
  uri = URI.parse(endpoint)
  http = Net::HTTP.new(uri.host, uri.port)
  http.use_ssl = uri.scheme == 'https'
  http.verify_mode = OpenSSL::SSL::VERIFY_PEER
  http.ssl_version = :TLSv1_2
  http.open_timeout = 30
  http.read_timeout = 30

  # Fix for macOS certificate CRL verification issues
  cert_store = OpenSSL::X509::Store.new
  cert_store.set_default_paths
  http.cert_store = cert_store

  headers = {
    Data::HEADER_TYPES[:CONTENT_TYPE] => Data::FILE_FORMATS[:APPLICATION_JSON],
    Data::HEADER_KEYS[:X_API_KEY] => Data::State.auth_key
  }

  if body && !body.empty?
    request = Net::HTTP::Post.new(uri.request_uri, headers)
    request.body = body.to_json
  else
    request = Net::HTTP::Get.new(uri.request_uri, headers)
  end

  response = http.request(request)
  JSON.parse(response.body, symbolize_names: false)
rescue StandardError => e
  warn "[Ip2Geo::Http] Error: #{e.message}"
  nil
end