Created
December 9, 2012 10:06
-
-
Save shuhei/4244102 to your computer and use it in GitHub Desktop.
Super simple HTTP proxy with Node.js
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
var http = require('http'); | |
var red = '\u001b[31m'; | |
var reset = '\u001b[0m'; | |
var proxyServer = function (request, response) { | |
var components = request.headers['host'].split(':'); | |
var options = { | |
hostname: components[0], | |
port: parseInt(components[1] || 80), | |
path: request.url, | |
method: request.method, | |
headers: request.headers | |
}; | |
console.log(request.url); | |
var proxyRequest = http.request(options, function (proxyResponse) { | |
proxyResponse.on('data', function (chunk) { | |
response.write(chunk, 'binary'); | |
}); | |
proxyResponse.on('end', function () { | |
response.end(); | |
}); | |
response.writeHead(proxyResponse.statusCode, proxyResponse.headers); | |
}); | |
proxyRequest.on('error', function (e) { | |
console.log(red + '[error]', options.hostname, request.url, e.message, reset); | |
}); | |
request.on('data', function (chunk) { | |
proxyRequest.write(chunk, 'binary'); | |
}); | |
request.on('end', function () { | |
proxyRequest.end(); | |
}) | |
}; | |
http.createServer(proxyServer).listen(8080); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment