Skip to content

Instantly share code, notes, and snippets.

@stellaraccident
Created February 15, 2011 20:31
Show Gist options
  • Save stellaraccident/828184 to your computer and use it in GitHub Desktop.
Save stellaraccident/828184 to your computer and use it in GitHub Desktop.
connect style middleware to proxy requests to another server
/**
* Simple proxy intended to be used as middleware to direct parts
* of an HTTP namespace to other servers.
*
* Copyright (c) 2011, Stella Laurenzo
*/
var util=require('util'),
url=require('url'),
http=require('http'),
armor=require('./armor');
function makeAppendDestination(baseUrl) {
return function(request) {
//console.log('Request: ' + util.inspect(request));
return baseUrl + request.url;
};
}
module.exports=function(destination) {
if (typeof destination==='string')
destination=makeAppendDestination(destination);
return function(req, res, next) {
var newUrl=destination(req),
parsed=url.parse(newUrl),
port=parsed.port;
//console.log('url: ' + util.inspect(parsed));
if (!port) {
if (parsed.protocol==='http:') port=80;
else if (parsed.protocol==='https:') port=443;
else port=80;
}
var client=http.createClient(port, parsed.hostname),
clientRequest=client.request(req.method,
parsed.pathname + (parsed.search||''),
req.headers);
// Error handling
var a=armor(next)
.enlist(client)
.enlist(clientRequest, clientRequest.end.bind(clientRequest));
// Patch through the response
clientRequest.on('response', function(pxres) {
pxres.on('data', function(chunk) {
res.write(chunk, 'binary');
}.armor(a));
pxres.on('end', function() {
res.end();
}.armor(a));
res.writeHead(pxres.statusCode, pxres.headers);
}.armor(a));
// Patch through the request
req.on('data', function(chunk) {
clientRequest.write(chunk, 'binary');
}.armor(a));
req.on('end', function() {
clientRequest.end();
}.armor(a));
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment