Module: DIDKit::Requests
- Included in:
- DID, PLCImporter, Resolver
- Defined in:
- lib/didkit/requests.rb
Instance Method Summary collapse
- #content_type_matches(response, expected_type) ⇒ Object
- #get_data(url, options = {}) ⇒ Object
- #get_json(url, options = {}) ⇒ Object
- #get_response(url, options = {}) ⇒ Object
-
#uri_origin(uri) ⇒ Object
backported from github.com/ruby/uri/pull/30/files for older Rubies.
Instance Method Details
#content_type_matches(response, expected_type) ⇒ Object
61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 |
# File 'lib/didkit/requests.rb', line 61 def content_type_matches(response, expected_type) content_type = response['Content-Type'] case expected_type when String content_type == expected_type when Regexp content_type =~ expected_type when :json content_type =~ /^application\/json(;.*)?$/ when nil true else raise ArgumentError, "Invalid expected_type: #{expected_type.inspect}" end end |
#get_data(url, options = {}) ⇒ Object
46 47 48 49 50 51 52 53 54 55 |
# File 'lib/didkit/requests.rb', line 46 def get_data(url, = {}) content_type = .delete(:content_type) response = get_response(url, ) if response.is_a?(Net::HTTPSuccess) && content_type_matches(response, content_type) && (data = response.body) data else raise APIError.new(response) end end |
#get_json(url, options = {}) ⇒ Object
57 58 59 |
# File 'lib/didkit/requests.rb', line 57 def get_json(url, = {}) JSON.parse(get_data(url, )) end |
#get_response(url, options = {}) ⇒ Object
9 10 11 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 44 |
# File 'lib/didkit/requests.rb', line 9 def get_response(url, = {}) url = URI(url) unless url.is_a?(URI) timeout = [:timeout] || 15 = { use_ssl: true, open_timeout: timeout, read_timeout: timeout } redirects = 0 visited_urls = [] max_redirects = [:max_redirects] || 5 loop do visited_urls << url response = Net::HTTP.start(url.host, url.port, ) do |http| request = Net::HTTP::Get.new(url) http.request(request) end if response.is_a?(Net::HTTPRedirection) && redirects < max_redirects && (location = response['Location']) url = URI(location.include?('://') ? location : (uri_origin(url) + location)) if visited_urls.include?(url) return response else redirects += 1 end else return response end end end |
#uri_origin(uri) ⇒ Object
backported from github.com/ruby/uri/pull/30/files for older Rubies
79 80 81 82 83 84 |
# File 'lib/didkit/requests.rb', line 79 def uri_origin(uri) uri = uri.is_a?(URI) ? uri : URI(uri) = (uri.port == uri.default_port) ? uri.host : "#{uri.host}:#{uri.port}" "#{uri.scheme}://#{}" end |