Class: ProxES::Forwarder

Inherits:
Object
  • Object
show all
Defined in:
lib/proxes/forwarder.rb

Overview

A lot of code in this comes from Rack::Proxy

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(opts = {}) ⇒ Forwarder

Returns a new instance of Forwarder.



9
10
11
# File 'lib/proxes/forwarder.rb', line 9

def initialize(opts= {})
  @backend = URI(opts[:backend]) if opts[:backend]
end

Instance Attribute Details

#backendObject (readonly)

Returns the value of attribute backend.



7
8
9
# File 'lib/proxes/forwarder.rb', line 7

def backend
  @backend
end

#streamingObject (readonly)

Returns the value of attribute streaming.



7
8
9
# File 'lib/proxes/forwarder.rb', line 7

def streaming
  @streaming
end

Class Method Details

.normalize_headers(headers) ⇒ Object



32
33
34
35
36
37
# File 'lib/proxes/forwarder.rb', line 32

def normalize_headers(headers)
  mapped = headers.map do |k, v|
    [k, if v.is_a? Array then v.join("\n") else v end]
  end
  Rack::Utils::HeaderHash.new Hash[mapped]
end

Instance Method Details

#call(env) ⇒ Object



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/proxes/forwarder.rb', line 13

def call(env)
  source_request = Rack::Request.new(env)
  full_path = source_request.fullpath == "" ? URI.parse(env['REQUEST_URI']).request_uri : source_request.fullpath
  target_request = Net::HTTP.const_get(source_request.request_method.capitalize).new(full_path)

  http = Net::HTTP.new(backend.host, backend.port)
  target_response = http.request(target_request)

  headers = (target_response.respond_to?(:headers) && target_response.headers) || self.class.normalize_headers(target_response.to_hash)
  body    = target_response.body || [""]
  body    = [body] unless body.respond_to?(:each)

  # Not sure where this is coming from, but it causes timeouts on the client
  headers.delete('transfer-encoding')

  [target_response.code, headers, body]
end