require 'net/http' module Adminix module Helpers class NetHTTP def self.get(path) uri = URI.parse("#{Adminix.config.api_host}/v1/#{path}") request = Net::HTTP::Get.new(uri) default_headers.each { |h| request[h[0]] = h[1] } opts = { use_ssl: uri.scheme == 'https' } response = Net::HTTP.start(uri.hostname, uri.port, opts) do |http| http.request(request) end read_response_body(response) rescue SocketError, Net::OpenTimeout, Net::ReadTimeout Adminix.logger.error("Can't connect to API") [false, nil] end def self.post(path, payload) uri = URI.parse("#{Adminix.config.api_host}/v1/#{path}") request = Net::HTTP::Post.new(uri) request.content_type = 'application/json' request.body = payload.to_json default_headers.each { |h| request[h[0]] = h[1] } opts = { use_ssl: uri.scheme == 'https' } response = Net::HTTP.start(uri.hostname, uri.port, opts) do |http| http.request(request) end read_response_body(response) rescue SocketError, Net::OpenTimeout, Net::ReadTimeout Adminix.logger.error("Can't connect to API") [false, nil] end def self.read_response_body(response) unless response.is_a? Net::HTTPSuccess Adminix.logger.error("Received code #{response.code} from API") return [false, response.code] end data = JSON.parse(response.body) success = data['success'] || false result = data['result'] [success, result] end def self.default_headers [ ['Authorization', "Bearer #{Adminix.config.secret_key}"], ['X-Watcher-Version', Adminix::VERSION], ['Accept', 'application/json'] ] end end end end