proxy.js 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. var http = require('http'),
  2. https = require('https'),
  3. url = require('url');
  4. var port = 1234,
  5. log = true,
  6. request_auth = false;
  7. http.createServer(function(request, response) {
  8. console.log(request.headers);
  9. console.log("Got request: " + request.url);
  10. console.log("Forwarding request to " + request.headers['host']);
  11. if (request_auth) {
  12. if (!request.headers['proxy-authorization']) {
  13. response.writeHead(407, {'Proxy-Authenticate': 'Basic realm="proxy.com"'})
  14. return response.end('Hello.');
  15. }
  16. }
  17. var remote = url.parse(request.url);
  18. var protocol = remote.protocol == 'https:' ? https : http;
  19. var opts = {
  20. host: request.headers['host'],
  21. port: remote.port || (remote.protocol == 'https:' ? 443 : 80),
  22. method: request.method,
  23. path: remote.pathname,
  24. headers: request.headers
  25. }
  26. var proxy_request = protocol.request(opts, function(proxy_response){
  27. proxy_response.on('data', function(chunk) {
  28. if (log) console.log(chunk.toString());
  29. response.write(chunk, 'binary');
  30. });
  31. proxy_response.on('end', function() {
  32. response.end();
  33. });
  34. response.writeHead(proxy_response.statusCode, proxy_response.headers);
  35. });
  36. request.on('data', function(chunk) {
  37. if (log) console.log(chunk.toString());
  38. proxy_request.write(chunk, 'binary');
  39. });
  40. request.on('end', function() {
  41. proxy_request.end();
  42. });
  43. }).listen(port);
  44. process.on('uncaughtException', function(err){
  45. console.log('Uncaught exception!');
  46. console.log(err);
  47. });
  48. console.log("Proxy server listening on port " + port);