Module: RCL::HTTP

Defined in:
lib/rcl/http.rb

Class Method Summary collapse

Class Method Details

.fetch_uri(uri, max_redirects = 10) ⇒ Object

Raises:

  • (ArgumentError)


10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/rcl/http.rb', line 10

def self.fetch_uri(uri, max_redirects=10)
  raise ArgumentError, 'nil uri' if uri.nil?
  raise ArgumentError, 'invalid uri class' if uri.class != String
  raise ArgumentError, 'empty uri' if uri.empty?
  raise ArgumentError, 'nil max_redirects' if max_redirects.nil?
  raise ArgumentError, 'max_redirects too deep' if max_redirects == 0

  url = URI.parse(uri)
  count = -1
  found = false

  until found
    host, port = url.host, url.port if url.host && url.port
    req = Net::HTTP::Get.new(url.path)
    res = Net::HTTP.start(host, port) { |http| http.request(req) }
    res.header['location'] \
      ? url = URI.parse(res.header['location']) : found = true
    count += 1
    raise 'too many redirects' if count >= max_redirects
  end

  return res, count
end

.status_message(res, count = 0) ⇒ Object

Raises:

  • (ArgumentError)


34
35
36
37
38
39
40
41
42
43
# File 'lib/rcl/http.rb', line 34

def self.status_message(res, count=0)
  raise ArgumentError, 'nil res' if res.nil?

  status = []

  status << "HTTP/#{res.http_version} #{res.code} #{res.message}"
  status << " [#{count} redirec#{count!= 1 ? "ts" : "t"}]" if count > 0

  status.join
end