Class: Rack::ReverseProxy

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

Instance Method Summary collapse

Constructor Details

#initialize(app = nil, &b) ⇒ ReverseProxy

Returns a new instance of ReverseProxy.



6
7
8
9
10
11
# File 'lib/rack/reverse_proxy.rb', line 6

def initialize(app = nil, &b)
  @app = app || lambda {|env| [404, [], []] }
  @matchers = []
  @global_options = {:preserve_host => true, :x_forwarded_host => true, :matching => :all, :verify_ssl => true}
  instance_eval &b if block_given?
end

Instance Method Details

#call(env) ⇒ Object



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
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
# File 'lib/rack/reverse_proxy.rb', line 13

def call(env)
  rackreq = Rack::Request.new(env)
  matcher = get_matcher rackreq.fullpath
  return @app.call(env) if matcher.nil?

  uri = matcher.get_uri(rackreq.fullpath,env)
  all_opts = @global_options.dup.merge(matcher.options)
  headers = Rack::Utils::HeaderHash.new
  env.each { |key, value|
    if key =~ /HTTP_(.*)/
      headers[$1] = value
    end
  }
  headers['HOST'] = uri.host if all_opts[:preserve_host]
  headers['X-Forwarded-Host'] = rackreq.host if all_opts[:x_forwarded_host]

  session = Net::HTTP.new(uri.host, uri.port)
  session.read_timeout=all_opts[:timeout] if all_opts[:timeout]

  session.use_ssl = (uri.scheme == 'https')
  if uri.scheme == 'https' && all_opts[:verify_ssl]
    session.verify_mode = OpenSSL::SSL::VERIFY_PEER
  else
    # DO NOT DO THIS IN PRODUCTION !!!
    session.verify_mode = OpenSSL::SSL::VERIFY_NONE
  end
  session.start { |http|
    m = rackreq.request_method
    case m
    when "GET", "HEAD", "DELETE", "OPTIONS", "TRACE"
      req = Net::HTTP.const_get(m.capitalize).new(uri.request_uri, headers)
      req.basic_auth all_opts[:username], all_opts[:password] if all_opts[:username] and all_opts[:password]
    when "PUT", "POST"
      req = Net::HTTP.const_get(m.capitalize).new(uri.request_uri, headers)
      req.basic_auth all_opts[:username], all_opts[:password] if all_opts[:username] and all_opts[:password]

      if rackreq.body.respond_to?(:read) && rackreq.body.respond_to?(:rewind)
        body = rackreq.body.read
        req.content_length = body.size
        rackreq.body.rewind
      else
        req.content_length = rackreq.body.size
      end

      req.content_type = rackreq.content_type unless rackreq.content_type.nil?
      req.body_stream = rackreq.body
    else
      raise "method not supported: #{m}"
    end

    body = ''
    res = http.request(req) do |res|
      res.read_body do |segment|
        body << segment
        # ensure content length header is correct
        res.content_length = body.bytesize
      end
    end

    [res.code, create_response_headers(res), [body]]
  }
end