Sha256: e32e449ddfcd0a2a9dfdf59159fb185b2171cb2af4175b3f8ca3f444c96df52f

Contents?: true

Size: 1.79 KB

Versions: 3

Compression:

Stored size: 1.79 KB

Contents

require 'net/http'
require 'rack'

module ProxES
  # A lot of code in this comes from Rack::Proxy
  class Forwarder
    attr_reader :backend, :streaming

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

    def body(request)
      return nil unless request.body
      return nil if request.body.is_a? Puma::NullIO
      return request.body.string if request.body.is_a? StringIO
      return request.body.read if request.body.is_a? Tempfile
      request.body
    end

    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)

      request_body = body(source_request)
      if request_body
        target_request.body = request_body
        target_request.content_length = request_body.length
        target_request.content_type   = source_request.content_type if source_request.content_type
      end

      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

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

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
proxes-0.8.0 lib/proxes/forwarder.rb
proxes-0.7.1 lib/proxes/forwarder.rb
proxes-0.7.0 lib/proxes/forwarder.rb