Class: Nonnative::HTTPProxy

Inherits:
Sinatra::Application
  • Object
show all
Defined in:
lib/nonnative/http_proxy_server.rb

Overview

Sinatra application implementing a simple forward proxy.

The upstream host is configured via Sinatra settings (see HTTPProxyServer).

Supported HTTP verbs: GET, POST, PUT, PATCH, DELETE.

Instance Method Summary collapse

Instance Method Details

#api_response(verb, uri, opts) ⇒ RestClient::Response

Executes the upstream request and returns the response.

Parameters:

  • verb (String)

    HTTP verb name (e.g. ‘“get”`)

  • uri (String)

    upstream URI

  • opts (Hash)

    RestClient options (e.g. headers)

Returns:

  • (RestClient::Response)

    response for error statuses, otherwise RestClient return value



56
57
58
59
60
61
62
# File 'lib/nonnative/http_proxy_server.rb', line 56

def api_response(verb, uri, opts)
  client = RestClient::Resource.new(uri, opts)

  client.send(verb)
rescue RestClient::Exception => e
  e.response
end

#build_url(request, settings) ⇒ String

Builds the upstream URL for the given request.

Parameters:

  • request (Sinatra::Request)

    the incoming request

  • settings (Sinatra::Base)

    Sinatra settings, expected to include host

Returns:

  • (String)

    HTTPS URL for the upstream request



46
47
48
# File 'lib/nonnative/http_proxy_server.rb', line 46

def build_url(request, settings)
  URI::HTTPS.build(host: settings.host, path: request.path_info, query: request.query_string).to_s
end

#retrieve_headers(request) ⇒ Hash{String=>String}

Extracts request headers from the Rack environment and normalizes them to standard HTTP names.

Certain hop-by-hop or proxy-specific headers are removed.

Parameters:

  • request (Sinatra::Request)

    the incoming request

Returns:

  • (Hash{String=>String})

    headers to forward to the upstream



32
33
34
35
36
37
38
39
# File 'lib/nonnative/http_proxy_server.rb', line 32

def retrieve_headers(request)
  headers = request.env.map do |header, value|
    [header[5..].split('_').map(&:capitalize).join('-'), value] if header.start_with?('HTTP_')
  end
  headers = headers.compact.to_h

  headers.except('Host', 'Accept-Encoding', 'Version')
end