Created
January 11, 2013 16:38
-
-
Save kaizhu256/4512114 to your computer and use it in GitHub Desktop.
nodejs - efficient http proxy that directly pipes data from website to browser in under 50 lines of code
This file contains 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
/*jslint bitwise: true, indent: 2, nomen: true, regexp: true, stupid: true*/ | |
(function () { | |
'use strict'; | |
exports.requireHttp = require('http'); | |
exports.requireUrl = require('url'); | |
exports.handlerHttpProxy = function (request, response, next) { | |
var kk, | |
proxy = exports.requireUrl.parse(/http.*/.exec(request.url)[0]); | |
//// OPTIMIZATION - disable socket pooling | |
proxy.agent = false; | |
proxy.headers = {}; | |
proxy.method = request.method; | |
//// modify proxy request headers | |
for (kk in request.headers) { | |
if (request.headers.hasOwnProperty(kk)) { | |
proxy.headers[kk] = request.headers[kk]; | |
} | |
} | |
proxy.headers.host = proxy.host; | |
proxy = require(proxy.protocol.slice(0, -1)).request(proxy, function (proxyResponse) { | |
response.writeHead(proxyResponse.statusCode, proxyResponse.headers); | |
//// OPTIMIZATION - stream data | |
proxyResponse.pipe(response); | |
}); | |
proxy.once('error', function (err) { | |
next(err); | |
}); | |
//// OPTIMIZATION - stream data | |
request.pipe(proxy); | |
}; | |
//// test | |
exports.requireHttp.createServer(function (request, response) { | |
if (/^http:\/\/|^https:\/\//.test(request.url)) { | |
exports.handlerHttpProxy(request, response, function (err) { | |
console.error(err.stack); | |
response.end(err.stack); | |
}); | |
} else { | |
response.writeHead(404); | |
response.end('404 Not Found'); | |
} | |
}).listen(8888); | |
//// from command line shell, try: | |
//// curl --proxy http://localhost:8888 'http://www.yahoo.com' | |
}()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment