-
-
Save Marak/566873 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var http = require('http'), | |
sys = require('sys'); | |
exports.createServer = function createServer (port, host) { | |
return new HttpProxy({ | |
port: +port, | |
host: host || '0.0.0.0' | |
}); | |
}; | |
var ClientPool = function ClientPool (port, host) { | |
this.port = +port; | |
this.host = host; | |
this.clients = []; | |
return this; | |
}; | |
ClientPool.prototype.request = function allocRequest (method, path, headers) { | |
var client, request, $ = this; | |
if (!(client = this.clients.pop())) { | |
client = http.createClient(this.port, this.host); | |
request = client.request(method, path, headers); | |
request.connection.on('close', function () { | |
request | |
$.clients.push(client); | |
}); | |
} else { | |
request = client.request(method, path, headers); | |
} | |
return request; | |
}; | |
var HttpProxy = exports.HttpProxy = function HttpProxy (options) { | |
this.client_pool = new ClientPool(options.port, options.host); | |
http.Server.call(this); | |
this.on('request', this.onRequest); | |
return this; | |
}; | |
HttpProxy.prototype = Object.create(http.Server.prototype); | |
HttpProxy.prototype.onRequest = function onRequest (e_request, e_response) { | |
var i_request = this.client_pool.request(e_request.method, | |
e_request.url, e_request.rawHeaders); | |
i_request.connection.on('error', function (error) { | |
error = 'An error occurred: ' + sys.inspect(error); | |
e_response.writeHead(200, { | |
'Content-Type': 'text/plain', | |
'Content-Length': error.length | |
}); | |
if (e_request.method === 'HEAD') error = null; | |
e_response.end(error); | |
}); | |
i_request.on('response', function (i_response) { | |
// Pump response | |
e_response.writeHead(i_response.statusCode, i_response.rawHeaders); | |
sys.pump(i_response, e_response); | |
i_response.on('end', function () { | |
e_response.end(); | |
}); | |
}); | |
sys.pump(e_request, i_request); | |
e_request.on('end', function () { | |
i_request.end(); | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment