Class: Rack::Client::HTTP

Inherits:
Object
  • Object
show all
Defined in:
lib/rack/client/http.rb

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(env) ⇒ HTTP

Returns a new instance of HTTP.



8
9
10
# File 'lib/rack/client/http.rb', line 8

def initialize(env)
  @env = env
end

Class Method Details

.call(env) ⇒ Object



4
5
6
# File 'lib/rack/client/http.rb', line 4

def self.call(env)
  new(env).run
end

Instance Method Details

#httpObject



41
42
43
44
45
46
47
48
# File 'lib/rack/client/http.rb', line 41

def http
  http = Net::HTTP.new(request.host, request.port)
  if https?
    http.use_ssl = true
    http.verify_mode = OpenSSL::SSL::VERIFY_NONE
  end
  http
end

#https?Boolean

Returns:

  • (Boolean)


37
38
39
# File 'lib/rack/client/http.rb', line 37

def https?
  request.scheme == 'https'
end

#parse(response) ⇒ Object



50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/rack/client/http.rb', line 50

def parse(response)
  status = response.code.to_i
  headers = {}
  response.each do |key,value|
    key = key.gsub(/(\w+)/) do |matches|
      matches.sub(/^./) do |char|
        char.upcase
      end
    end
    headers[key] = value
  end
  [status, headers, response.body.to_s]
end

#requestObject



64
65
66
# File 'lib/rack/client/http.rb', line 64

def request
  @request ||= Rack::Request.new(@env)
end

#request_headersObject



68
69
70
71
72
73
74
75
76
# File 'lib/rack/client/http.rb', line 68

def request_headers
  headers = {}
  @env.each do |k,v|
    if k =~ /^HTTP_(.*)$/
      headers[$1] = v
    end
  end
  headers
end

#runObject



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/rack/client/http.rb', line 12

def run
  request_klass = case request.request_method
  when "HEAD"
    Net::HTTP::Head
  when "GET"
    Net::HTTP::Get
  when "POST"
    Net::HTTP::Post
  when "PUT"
    Net::HTTP::Put
  when "DELETE"
    Net::HTTP::Delete
  else
    raise "Unsupported method: #{request.request_method.inspect}"
  end

  request_object = request_klass.new(request.path, request_headers)

  if %w( POST PUT ).include?(request.request_method)
    request_object.body = @env["rack.input"].read
  end

  parse(http.request(request_object))
end