Last active
          December 31, 2015 00:19 
        
      - 
      
- 
        Save ngyuki/7906962 to your computer and use it in GitHub Desktop. 
    node.js forward proxy example
  
        
  
    
      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 httpProxy = require('http-proxy'); | |
| var url = require('url'); | |
| var net = require('net'); | |
| var http = require('http'); | |
| process.on('uncaughtException', function (err) { | |
| console.error('! uncaughtException: ' + err.stack); | |
| }); | |
| function truncate(str) | |
| { | |
| var maxLength = 100; | |
| return (str.length >= maxLength ? str.substring(0,maxLength) + '...' : str); | |
| } | |
| function logRequest(req) | |
| { | |
| console.log(req.method + ' ' + truncate(req.url)); | |
| } | |
| function logRewrite(uri) | |
| { | |
| console.log(" + Rewrite: " + uri); | |
| } | |
| var regularProxy = new httpProxy.RoutingProxy(); | |
| function rewriteUrl(uri) | |
| { | |
| if (uri === "http://stackoverflow.com/questions/18569733/running-a-forward-proxy-server-in-nodejitsu-using-node-js") | |
| { | |
| uri = "http://ngyuki.hatenablog.com/entry/2013/12/11/003959"; | |
| logRewrite(uri); | |
| } | |
| return uri; | |
| } | |
| function rewriteHttps(host) | |
| { | |
| if (host === "github.com") | |
| { | |
| host = "bitbucket.org"; | |
| logRewrite(host); | |
| } | |
| return host; | |
| } | |
| var server = http.createServer(); | |
| server.on('request', function(req, res) { | |
| logRequest(req); | |
| req.url = rewriteUrl(req.url); | |
| var uri = url.parse(req.url); | |
| regularProxy.proxyRequest(req, res, { | |
| host: uri.hostname, | |
| port: uri.port || 80 | |
| }); | |
| }); | |
| server.on('connect', function(req, socket, head) { | |
| logRequest(req); | |
| var parts = req.url.split(':', 2); | |
| var host = rewriteHttps(parts[0]); | |
| var port = parts[1]; | |
| var conn = net.connect(port, host, function() { | |
| socket.write("HTTP/1.1 200 OK\r\n\r\n"); | |
| socket.pipe(conn); | |
| conn.pipe(socket); | |
| }); | |
| }); | |
| server.listen(8888); | 
  
    
      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
    
  
  
    
  | { | |
| "dependencies": { | |
| "http-proxy": "~0.10.3" | |
| } | |
| } | 
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment