Module: Egalite::HTTP

Defined in:
lib/egalite/http.rb

Class Method Summary collapse

Class Method Details

.get(url, options = {}) ⇒ Object



52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
# File 'lib/egalite/http.rb', line 52

def self.get(url, options = {})
  params = options[:params]
  if params.is_a?(Hash)
    params = URI.encode_www_form(params)
  end
  if params.is_a?(String)
    if url =~ /\?/
      url << "&"
    else
      url << "?"
    end
    url << params
  end
  parse_options(options)
  (http, uri) = parse_url(url, options)
  resp = http.get(uri.request_uri, options[:header])
  parse_response(resp)
end

.parse_options(options) ⇒ Object



31
32
33
34
35
36
37
38
39
# File 'lib/egalite/http.rb', line 31

def self.parse_options(options)
  if options[:basic_auth]
    u = options[:basic_auth][0]
    pw = options[:basic_auth][1]
    b = ["#{u}:#{pw}"].pack("m")
    options[:header] ||= {}
    options[:header]["Authorization"] = "Basic #{b}".chop
  end
end

.parse_response(response) ⇒ Object



40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/egalite/http.rb', line 40

def self.parse_response(response)
  ret = {}
  ret[:body] = response.body
  ret[:headers] = response.each {}
  ret[:headers] = Hash[ret[:headers].map { |k,v|
    [k.tr("-","_").downcase.to_sym,v[0]]
  }]
  ret[:headers][:content_length] = ret[:headers][:content_length].to_i
  ret[:headers][:date] = Time.parse(ret[:headers][:date]) rescue ret[:headers][:date]
  ret[:code] = response.code.to_i
  ret
end

.parse_url(url, options) ⇒ Object



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

def self.parse_url(url, options)
  uri = URI.parse(url)
  http = Net::HTTP.new(uri.host, uri.port)
  if uri.scheme == "https"
    http.use_ssl = true
    http.verify_mode = OpenSSL::SSL::VERIFY_NONE
  end
  if options[:continue_timeout]
    http.continue_timeout = options[:continue_timeout]
  end
  if options[:keep_alive_timeout]
    http.keep_alive_timeout = options[:keep_alive_timeout]
  end
  if options[:open_timeout]
    http.open_timeout = options[:open_timeout]
  end
  if options[:read_timeout]
    http.read_timeout = options[:read_timeout]
  end
  if options[:ssl_timeout]
    http.ssl_timeout = options[:ssl_timeout]
  end
  [http, uri]
end

.post(url, body = nil, options = {}) ⇒ Object



70
71
72
73
74
75
76
77
78
79
# File 'lib/egalite/http.rb', line 70

def self.post(url, body = nil, options = {})
  uri = parse_url(url,options)
  if body.is_a?(Hash)
    body = URI.encode_www_form(body)
  end
  parse_options(options)
  (http, uri) = parse_url(url, options)
  resp = http.post(uri.request_uri, body, options[:header])
  parse_response(resp)
end