Class: WeatherSage::HTTP::Fetcher

Inherits:
Object
  • Object
show all
Defined in:
lib/weather-sage/http/fetcher.rb

Overview

HTTP fetcher.

Constant Summary collapse

HEADERS =

Request headers.

{
  'Accept'      => 'application/json',
  'User-Agent'  => "weather-sage/#{WeatherSage::VERSION}"
}.freeze

Instance Method Summary collapse

Constructor Details

#initialize(log) ⇒ Fetcher

Create an HTTP Fetcher.



18
19
20
# File 'lib/weather-sage/http/fetcher.rb', line 18

def initialize(log)
  @log = log
end

Instance Method Details

#fetch(uri, limit = 5) ⇒ Object

Fetch URI, and return response.

Raises an WeatherSage::HTTP::Error on error.



27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
# File 'lib/weather-sage/http/fetcher.rb', line 27

def fetch(uri, limit = 5)
  # log uri
  @log.info('Fetcher#fetch') { '%p' % [uri] }

  # create request, set headers
  req = Net::HTTP::Get.new(uri)
  HEADERS.each { |k, v| req[k] = v }
  use_ssl = (uri.scheme == 'https')

  # connect, fetch response
  resp = Net::HTTP.start(uri.host, uri.port, use_ssl: use_ssl) do |http|
    http.request(req)
  end

  # log response
  @log.debug('Fetcher#fetch') { 'response: %p' % [resp] }

  # check for error
  case resp
  when Net::HTTPSuccess
    resp
  when Net::HTTPRedirection
    # have we hit the redirect limit?
    unless limit > 0
      # redirect limit hit, raise error
      raise ::WeatherSage::HTTP::Error.new(uri.to_s, resp.code, resp)
    end

    # get new uri
    new_uri = uri.merge(resp['location'])

    # log redirect
    @log.debug('Fetcher#fetch') do
      'redirect: %s' % [JSON.unparse({
        location: resp['location'],
        old_uri: uri,
        new_uri: new_uri,
      })]
    end

    # decriment limit, redirect
    fetch(new_uri, limit - 1)
  else
    # log error
    @log.debug('Fetcher#fetch') do
      'HTTP request failed: url = %s, response = %p' % [uri, resp]
    end

    # raise error
    raise ::WeatherSage::HTTP::Error.new(uri.to_s, resp.code, resp)
  end
end