Module: ThreadedProxy::Controller

Defined in:
lib/threaded_proxy/controller.rb

Instance Method Summary collapse

Instance Method Details

#proxy_fetch(origin_url, options = {}) {|Client| ... } ⇒ void

This method returns an undefined value.

Proxies a fetch request to the specified origin URL, allowing for hijacking the controller response outside of the Rack request/response cycle.

Examples:

proxy_fetch('http://example.com', body: :rack, headers: { 'Custom-Header' => 'value' }) do |client|
  client.on_headers { |client_response| client_response['x-foo'] = 'bar' }
  client.on_error { |e| Rails.logger.error(e) }
end

Options Hash (options):

  • :body (Symbol)

    The body of the request. If set to :rack, the request body stream will be used.

  • :headers (Hash)

    Additional headers to include in the request.

Yields:

  • (Client)

    Optional block to configure the client.

Raises:

  • (RuntimeError)

    If a non-chunked POST request is made without a content-length header.



25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/threaded_proxy/controller.rb', line 25

def proxy_fetch(origin_url, options = {}, &block)
  # hijack the response so we can take it outside of the rack request/response cycle
  request.env['rack.hijack'].call
  socket = request.env['rack.hijack_io']

  options.deep_merge!(proxy_options_from_request) if options[:body] == :rack

  Thread.new do
    client = Client.new(origin_url, options, &block)
    client.start(socket)
  ensure
    socket.close unless socket.closed?
  end

  head :ok
end