Module: Egalite::HTTP

Defined in:
lib/egalite/http.rb

Class Method Summary collapse

Class Method Details

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



37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/egalite/http.rb', line 37

def self.get(url, options = {})
  params = options[:params]
  if params.is_a?(Hash)
    params = params.map { |k,v|
      "#{k}=#{v}"
    }.join("&")
  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



16
17
18
19
20
21
22
23
24
# File 'lib/egalite/http.rb', line 16

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



25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/egalite/http.rb', line 25

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
# 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
  [http, uri]
end

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



57
58
59
60
61
62
63
64
65
66
67
68
# File 'lib/egalite/http.rb', line 57

def self.post(url, body = nil, options = {})
  uri = parse_url(url,options)
  if body.is_a?(Hash)
    body = body.map { |k,v|
      "#{k}=#{v}"
    }.join("&")
  end
  parse_options(options)
  (http, uri) = parse_url(url, options)
  resp = http.post(uri.request_uri, body, options[:header])
  parse_response(resp)
end