Class: WebProxy

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

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(host) ⇒ WebProxy

Returns a new instance of WebProxy.



25
26
27
# File 'lib/webproxy.rb', line 25

def initialize host
  @host = host
end

Class Method Details

.run!(host, port = 8080) ⇒ Object



8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# File 'lib/webproxy.rb', line 8

def self.run!(host, port = 8080)
  handler = Rack::Handler::WEBrick

  begin
    require 'thin'
    handler = Rack::Handler::Thin
  rescue LoadError
    begin
      require 'mongrel'
      handler = Rack::Handler::Mongrel
    rescue LoadError
    end
  end

  handler.run WebProxy.new(host), :Port => port.to_i
end

Instance Method Details

#_get_request_body(env) ⇒ Object

env returns an IO object that you must #each over to get the full body



43
44
45
46
47
# File 'lib/webproxy.rb', line 43

def _get_request_body env
  body = ''
  env['rack.input'].each {|string| body << string }
  body
end

#_get_request_headers(env) ⇒ Object

we should pass along all HTTP_* headers and we need to CHANGE the HTTP_HOST header to reflect the new host we’re making the request to



57
58
59
60
61
62
# File 'lib/webproxy.rb', line 57

def _get_request_headers env
  headers = {}
  env.each {|k,v| if k =~ /HTTP_(\w+)/ then headers[$1] = v end }
  headers.delete 'HOST' # simply delete it and let HTTP do the rest
  headers
end

#_get_response_headers(response) ⇒ Object

response.headers returns an object that wraps the actual Hash of headers … this gets the actual Hash



50
51
52
53
54
# File 'lib/webproxy.rb', line 50

def _get_response_headers response
  response_headers = response.headers.instance_variable_get('@header')
  response_headers.each {|k, v| response_headers[k] = response_headers[k][0] } # values are all in arrays
  response_headers
end

#call(env) ⇒ Object



29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/webproxy.rb', line 29

def call env
  url    = File.join @host, env['PATH_INFO']
  method = env['REQUEST_METHOD'].downcase

  puts "#{env['REQUEST_METHOD']} #{url}"

  # make request
  response = HTTParty.send method, url, :body => _get_request_body(env), :headers => _get_request_headers(env), :format => 'text'

  # return response
  [ response.code, _get_response_headers(response), [response.body] ]
end