Skip to content

Instantly share code, notes, and snippets.

@jrockway
Created December 16, 2010 01:38
Show Gist options
  • Save jrockway/742896 to your computer and use it in GitHub Desktop.
Save jrockway/742896 to your computer and use it in GitHub Desktop.
node.js proxy (with AnyEvent::HTTP test case)
#!/usr/bin/env perl
use strict;
use warnings;
use feature ':5.10';
use AnyEvent::HTTP;
my $cv = AE::cv;
http_get 'http://www.google.com/', $cv;
my ($body, $headers) = $cv->recv;
say "got $body";
var http = require('http');
var url = require('url');
// not really necessary, but i think it looks nice
function fixupHeaders(i) {
var fixup = function(k) {
var parts = k.split('-');
for(p in parts){
parts[p] = parts[p].substring(0,1).toUpperCase() +
parts[p].substring(1).toLowerCase();
}
return parts.join('-');
};
var o = {};
for(k in i){ o[fixup(k)] = i[k] }
return o;
}
http.createServer(function (req, res) {
var u = url.parse(req.url);
var c = http.createClient(u.port ? u.port : 80, u.hostname);
var crq = c.request(req.method, u.pathname, req.headers);
req.on( 'data', function (c) { crq.write(c) } );
req.on( 'end', function ( ) { crq.end() } );
crq.on( 'response', function (crs) {
res.writeHead(crs.statusCode, fixupHeaders(crs.headers));
crs.on( 'data', function (c) { res.write(c) } );
crs.on( 'end', function ( ) { res.end() } );
});
}).listen(8080);
console.log('listening on 8080');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment