lib/hako/scripts/switch_hitter.rb in hako-switch-hitter-0.1.2 vs lib/hako/scripts/switch_hitter.rb in hako-switch-hitter-0.1.3

- old
+ new

@@ -1,9 +1,10 @@ require 'hako' require 'hako/error' require 'hako/script' require 'net/http' +require 'uri' module Hako module Scripts class SwitchHitter < Script @@ -26,67 +27,59 @@ def endpoint raise Error.new("Switch hitter endpoint is not configured") unless @options['endpoint'] @options['endpoint'] end + # @return [URI] + def endpoint_uri + @uri ||= URI.parse(endpoint) + end + # @return [String] - def endpoint_proto - proto = endpoint.fetch('proto') - raise Error.new("Switch hitter proto must be http or https") unless %w/http https/.include?(proto) - proto + def endpoint_scheme + raise Error.new("Switch hitter endpoint scheme must be http or https") unless %w/http https/.include?(endpoint_uri.scheme) + endpoint_uri.scheme end # @return [String] def endpoint_host - endpoint.fetch('host') + endpoint_uri.host end # @return [Fixnum] - def wellknown_port - endpoint_proto == 'https' ? 443 : 80 - end - - # @return [Fixnum] def endpoint_port - endpoint.fetch('port', wellknown_port) + endpoint_uri.port end # @return [String] def endpoint_path - endpoint.fetch('path') + endpoint_uri.path end # @return [Net::HTTP] def http(host, port) Net::HTTP.new(host, port) end - # @return [String] - def url - "#{endpoint_proto}://#{endpoint_host}:#{endpoint_port}#{endpoint_path}" - end - # @return [nil] def hit_switch + Hako.logger.info("Switch endpoint #{endpoint}") + net_http = http(endpoint_host, endpoint_port) + net_http.use_ssl = endpoint_scheme == 'https' - Hako.logger.info("Switch endpoint #{url}") - if endpoint_proto == 'HTTPS' - net_http.use_ssl = true - end - if @dry_run - Hako.logger.info("Switch hitter will request #{url} [dry-run]") + Hako.logger.info("Switch hitter will request #{endpoint} [dry-run]") return end net_http.start do - req = Net::HTTP::Get.new(endpoint_path) + req = Net::HTTP::Get.new(endpoint_uri.request_uri) res = net_http.request(req) unless res.code == '200' raise Error.new("Switch hitter HTTP Error: #{res.code}: #{res.body}") end - Hako.logger.info("Enabled #{endpoint_path} at #{res.body}") + Hako.logger.info("Enabled #{endpoint} at #{res.body}") end end end end end