Class: Rack::Rekon::Proxy

Inherits:
Object
  • Object
show all
Defined in:
lib/rack/rekon/proxy.rb

Direct Known Subclasses

App

Instance Method Summary collapse

Instance Method Details

#call(env) ⇒ 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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/rack/rekon/proxy.rb', line 7

def call(env)
  req = Rack::Request.new(env)
  method = req.request_method.downcase
  method[0..0] = method[0..0].upcase

  uri = URI(uri_for(req))

  sub_request = Net::HTTP.const_get(method).new("#{uri.path}#{"?" if uri.query}#{uri.query}")

  if sub_request.request_body_permitted? and req.body
    sub_request.body_stream = req.body
    sub_request.content_length = req.content_length
    sub_request.content_type = req.content_type
  end

  sub_request["X-Forwarded-For"] = (req.env["X-Forwarded-For"].to_s.split(/, +/) + [req.env['REMOTE_ADDR']]).join(", ")
  sub_request["X-Requested-With"] = req.env['HTTP_X_REQUESTED_WITH'] if req.env['HTTP_X_REQUESTED_WITH']
  sub_request["Accept-Encoding"] = req.accept_encoding
  sub_request["Referer"] = req.referer
  sub_request.basic_auth *uri.userinfo.split(':') if (uri.userinfo && uri.userinfo.index(':'))

  sub_response = Net::HTTP.start(uri.host, uri.port) do |http|
    http.request(sub_request)
  end

  headers = {}
  sub_response.each_header do |k,v|
    headers[k] = v unless k.to_s =~ /cookie|content-length|transfer-encoding/i
  end

  response_triplet = [sub_response.code.to_i, headers, [sub_response.read_body]]

  if respond_to?(:rewrite_response)
    rewrite_response(req, *response_triplet)
  else
    response_triplet
  end
end