Advertisement
bogdanbiv

SelectiveProxy

Feb 2nd, 2014
1,319
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /*
  2. Install Dependencies:
  3. npm install http-proxy colors connect util --save
  4. */
  5.  
  6. var util = require('util'),
  7.     colors = require('colors'),
  8.     http = require('http'),
  9.     connect = require('connect'),
  10.     httpProxy = require('http-proxy');
  11.  
  12. //
  13. // Basic Connect App
  14. //
  15. connect.createServer(
  16.   function (req, res, next) {
  17.     var _write = res.write;
  18.  
  19.     res.write = function (data) {
  20.       _write.call(res, data.toString().replace("Ruby", "nodejitsu2"));
  21.     }
  22.     next();
  23.   },
  24.   function (req, res) {
  25.     console.log('host: ' + req.headers['host'] + '; url ' + req.url);
  26.     if (req.headers['host'] === "stackoverflow.com") {
  27.         proxy.web(req, res, { target: 'http://localhost:9013' });
  28.     } else {
  29.         proxy.web(req, res, { target: req.url });
  30.     }
  31.     proxy.on('error', function (err, req, res) {
  32.       if (!res.headerSent) {
  33.         res.writeHead(500, {
  34.           'Content-Type': 'text/plain'
  35.         });
  36.       }
  37.       console.log(err);
  38.       res.end('Something went wrong. And we are reporting a custom error message.');
  39.     });
  40.   }
  41. ).listen(8013);
  42.  
  43. //
  44. // Basic Http Proxy Server
  45. //
  46. var proxy = httpProxy.createProxyServer({
  47.   // target: 'http://localhost:9013'
  48. });
  49.  
  50. //
  51. // Target Http Server
  52. //
  53. http.createServer(function (req, res) {
  54.   res.writeHead(200, { 'Content-Type': 'text/plain' });
  55.   res.end('Hello, I know Ruby\n');
  56. }).listen(9013);
  57.  
  58. util.puts('http proxy server'.blue + ' started '.green.bold + 'on port '.blue + '8013'.yellow);
  59. util.puts('http server '.blue + 'started '.green.bold + 'on port '.blue + '9013 '.yellow);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement