Class: ThreadedProxy::Client
- Inherits:
-
Object
- Object
- ThreadedProxy::Client
- Defined in:
- lib/threaded_proxy/client.rb
Constant Summary collapse
- DISALLOWED_RESPONSE_HEADERS =
%w[keep-alive]- METHODS =
{ 'get' => Net::HTTP::Get, 'post' => Net::HTTP::Post, 'put' => Net::HTTP::Put, 'delete' => Net::HTTP::Delete, 'head' => Net::HTTP::Head, 'options' => Net::HTTP::Options, 'trace' => Net::HTTP::Trace }
- DEFAULT_OPTIONS =
{ headers: {}, debug: false }
Instance Method Summary collapse
- #default_port(uri) ⇒ Object
-
#initialize(origin_url, options = {}) ⇒ Client
constructor
A new instance of Client.
- #log(message) ⇒ Object
- #start(socket) ⇒ Object
Constructor Details
#initialize(origin_url, options = {}) ⇒ Client
Returns a new instance of Client.
24 25 26 27 |
# File 'lib/threaded_proxy/client.rb', line 24 def initialize(origin_url, ={}) @origin_url = Addressable::URI.parse(origin_url) = DEFAULT_OPTIONS.merge() end |
Instance Method Details
#default_port(uri) ⇒ Object
77 78 79 80 81 82 83 84 85 86 |
# File 'lib/threaded_proxy/client.rb', line 77 def default_port(uri) case uri.scheme when 'http' 80 when 'https' 443 else nil end end |
#log(message) ⇒ Object
29 30 31 |
# File 'lib/threaded_proxy/client.rb', line 29 def log() $stderr.puts if [:debug] end |
#start(socket) ⇒ Object
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 75 |
# File 'lib/threaded_proxy/client.rb', line 33 def start(socket) request_method = METHODS[([:method] || 'GET').to_s.downcase] http_request = request_method.new(@origin_url, [:headers].merge('Connection' => 'close')) if [:body].respond_to?(:read) http_request.body_stream = [:body] elsif String === [:body] http_request.body = [:body] end http = HTTP.new(@origin_url.host, @origin_url.port || default_port(@origin_url)) http.use_ssl = (@origin_url.scheme == 'https') http.set_debug_output($stderr) if [:debug] http.verify_mode = OpenSSL::SSL::VERIFY_NONE if [:ignore_ssl_errors] http.start do http.request(http_request) do |client_response| # We don't support reusing connections once we have disconnected them from rack client_response['connection'] = 'close' yield client_response if block_given? # start writing response log("Writing response status and headers") socket.write "HTTP/1.1 #{client_response.code} #{client_response.message}\r\n" client_response.each_header do |key, value| socket.write "#{key}: #{value}\r\n" unless DISALLOWED_RESPONSE_HEADERS.include?(key.downcase) end # Done with headers socket.write "\r\n" # There may have been some existing data in client_response's read buffer, flush it out # before we manually connect the raw sockets log("Flushing existing response buffer to client") http.flush_existing_buffer_to(socket) # Copy the rest of the client response to the socket log("Copying response body to client") http.copy_to(socket) end end end |