summaryrefslogtreecommitdiff
path: root/lib/net/hippie/connection.rb
diff options
context:
space:
mode:
authormo khan <mo.khan@gmail.com>2020-06-13 08:32:45 -0600
committermo khan <mo.khan@gmail.com>2020-06-13 08:32:45 -0600
commitecc326cdad87cf978604974ae4e04c9fc47f9ee4 (patch)
tree3c280c58b9fecab09fec89d51d1936cc96620825 /lib/net/hippie/connection.rb
parent10a9b0b05a924d46accbdf99f2266ec8465d10b9 (diff)
Extract Http Connection class
Diffstat (limited to 'lib/net/hippie/connection.rb')
-rw-r--r--lib/net/hippie/connection.rb42
1 files changed, 42 insertions, 0 deletions
diff --git a/lib/net/hippie/connection.rb b/lib/net/hippie/connection.rb
new file mode 100644
index 0000000..599d754
--- /dev/null
+++ b/lib/net/hippie/connection.rb
@@ -0,0 +1,42 @@
+# frozen_string_literal: true
+
+module Net
+ module Hippie
+ # A connection to a specific host
+ class Connection
+ def initialize(scheme, host, port, options = {})
+ http = Net::HTTP.new(host, port)
+ http.read_timeout = options.fetch(:read_timeout, 10)
+ http.open_timeout = options.fetch(:open_timeout, 10)
+ http.use_ssl = scheme == 'https'
+ http.verify_mode = options.fetch(:verify_mode, Net::Hippie.verify_mode)
+ http.set_debug_output(options.fetch(:logger, Net::Hippie.logger))
+ apply_client_tls_to(http, options)
+ @http = http
+ end
+
+ def run(request)
+ @http.request(request)
+ end
+
+ def build_url_for(path)
+ return path if path.start_with?('http')
+
+ "#{@http.use_ssl? ? 'https' : 'http'}://#{@http.address}#{path}"
+ end
+
+ private
+
+ def apply_client_tls_to(http, options)
+ return if options[:certificate].nil? || options[:key].nil?
+
+ http.cert = OpenSSL::X509::Certificate.new(options[:certificate])
+ http.key = private_key(options[:key], options[:passphrase])
+ end
+
+ def private_key(key, passphrase, type = OpenSSL::PKey::RSA)
+ passphrase ? type.new(key, passphrase) : type.new(key)
+ end
+ end
+ end
+end