collin (owner)

Revisions

gist: 148228 Download_button fork
public
Public Clone URL: git://gist.github.com/148228.git
Embed All Files: show embed
Rack::ProxyPass.rb #
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
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
# This is really boring. Only shown for completeness.
# This loads up the application layout for the staticmatic app
# And renders it's layout.
# It is expected that "content" is an html string.
def wrap_with_layout content
  engine = Haml::Engine.new File.read("src/layouts/application.haml")
  @staticmatic = StaticMatic::Base.new(File.dirname(__FILE__))
  engine.render { Hpricot(content)/"#content").to_s }
end
 
class Rack::Builder
  def proxy_pass target, source, &block=lambda{|echo| echo }
    use Rack::ProxyPass.new(target, source, &block)
  end
end
 
# This is the mused-of API
# It uses rack to proxy urls starting with '/blog'
proxy_pass '/blog/', 'http://whattech_wp/index.php/' do |env|
  request = Rack::request.new(env)
  [200, {}, wrap_with_layout(request.body)] # oh yeah
end
 
# Forwarding for the Rack::Request class
class Rack::Request
  def forward target, &block
    curl = Curl::Easy.new(target)
    curl.headers.merge headers
    
    case
      when get?
        curl.http_get
      when post?
        curl.http_post body
      when put?
        curl.http_put body
      when delete?
        curl.http_delete
      else
        raise "Unimplemented HTTP methof for Rack::Request#forward"
    end
    
    [curl.response_code, curl.header_str, yield(curl.body_str)]
  end
end
 
# And the ProxyPass Middleware
class Rack::ProxyPass
  def initialize src, target
    @src, @target = src, target
  end
  
  def call env, &block=nil
    block||= lambda{ |body_str| body_str }
    forward_to = env.path_info.sub(@src, @target)
    Rack::Request.new(env.merge).forward(forward_to, &block)
  end
end