Skip to content

Commit

Permalink
Feature/change http client (#20)
Browse files Browse the repository at this point in the history
  • Loading branch information
Mateus Luiz authored and prodis committed Nov 18, 2018
1 parent e6c1572 commit 6f2b6e2
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 31 deletions.
1 change: 1 addition & 0 deletions correios-cep.gemspec
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 23,7 @@ Gem::Specification.new do |spec|

spec.add_dependency 'log-me', '~> 0.0.10'
spec.add_dependency 'ox', '~> 2.9'
spec.add_dependency 'http', '~> 4.0.0'

spec.add_development_dependency 'coveralls', '~> 0.8.21'
spec.add_development_dependency 'pry', '~> 0.11.3'
Expand Down
52 changes: 21 additions & 31 deletions lib/correios/cep/web_service.rb
Original file line number Diff line number Diff line change
@@ -1,5 1,5 @@
# frozen_string_literal: true
require 'net/https'
require 'http'
require 'uri'

module Correios
Expand All @@ -23,43 23,33 @@ def initialize
end

def request(zipcode)
http = build_http

request = build_request(zipcode)
Correios::CEP.log_request(request, uri.to_s)

response = http.request(request)
Correios::CEP.log_response(response)

http.finish if http.started?

response.body
http_setup
.post(@uri.to_s, body: request_body(zipcode), ssl_context: ssl_setup)
.body
.to_s
end

private

attr_reader :uri, :proxy_uri
def client
@proxy_uri.host ? HTTP.via(@proxy_uri.host, @proxy_uri.port) : HTTP
end

def http_setup
client
.timeout(connect: Correios::CEP.request_timeout)
.use(logging: {logger: Correios::CEP.logger})
.headers('Content-Type' => CONTENT_TYPE_HEADER)
end

def build_http
Net::HTTP.start(
uri.host,
uri.port,
proxy_uri.host,
proxy_uri.port,
nil,
nil,
use_ssl: true,
verify_mode: OpenSSL::SSL::VERIFY_NONE,
open_timeout: Correios::CEP.request_timeout,
read_timeout: Correios::CEP.request_timeout
)
def request_body(zipcode)
BODY_TEMPLATE % { zipcode: zipcode }
end

def build_request(zipcode)
request = Net::HTTP::Post.new(uri.path)
request['Content-Type'] = CONTENT_TYPE_HEADER
request.body = BODY_TEMPLATE % { zipcode: zipcode }
request
def ssl_setup
ssl = OpenSSL::SSL::SSLContext.new
ssl.verify_mode = OpenSSL::SSL::VERIFY_NONE
ssl
end
end
end
Expand Down

0 comments on commit 6f2b6e2

Please sign in to comment.