Erik
Erik

Reputation: 4422

How to write content altering web proxy server in Ruby?

Can someone give a working code example of how to write a content altering web proxy server in Ruby? (for example rewriting all lowercase text to uppercase, or removing all img tags).

I had a look at mousehole and em-proxy before, with both I was unable to get a simple example working.

Upvotes: 1

Views: 894

Answers (2)

hlh
hlh

Reputation: 2072

Would Rack middlewares fit your use case? I don't know if you've heard of them or not, but the basic idea is that you can put Rack applications between the webserver and an endpoint application (like a Rails or Sinatra app) and they filter the request or response by performing some kind of operation on it (like altering the content).

I don't know what your situation is, but if you just wanted to change something about the response sent back to the client (like converting text to uppercase, as you said), maybe this is a good solution.

Upvotes: 0

nex
nex

Reputation: 685

In theory like this: http://www.ruby-doc.org/stdlib-2.0/libdoc/webrick/rdoc/WEBrick/HTTPProxyServer.html

require 'webrick'
require 'webrick/httpproxy'

handler = proc do |req, res|
  if res['content-type'] == 'text/plain'
    res.body << "\nThis content was proxied!\n"
  end
end

proxy = WEBrick::HTTPProxyServer.new Port: 8000, ProxyContentHandler: handler


trap 'INT'  do proxy.shutdown end
trap 'TERM' do proxy.shutdown end
proxy.start

But for some reason I can't get it to alter the content. Maybe it works for you tough.

Upvotes: 1

Related Questions