From b4e08d72199fcc649bbc1b48ea715341879e067d Mon Sep 17 00:00:00 2001 From: Manuel Astudillo Date: Tue, 18 Oct 2011 21:10:40 +0200 Subject: [PATCH] Optimized table based routing and changed the forwarding behavior: "pizza.com/taco/muffins": "127.0.0.1:8099' -> 127.0.0.1:8099 "pizza.com/taco/muffins": "127.0.0.1:8099/pasta/tomato' -> 127.0.0.1:8099/pasta/tomato --- lib/node-http-proxy/proxy-table.js | 63 ++++++++++++++++++------------ 1 file changed, 38 insertions(+), 25 deletions(-) diff --git a/lib/node-http-proxy/proxy-table.js b/lib/node-http-proxy/proxy-table.js index 4ab6690ee..70834c2ff 100644 --- a/lib/node-http-proxy/proxy-table.js +++ b/lib/node-http-proxy/proxy-table.js @@ -26,7 +26,8 @@ var util = require('util'), events = require('events'), - fs = require('fs'); + fs = require('fs'), + url = require('url'); // // ### function ProxyTable (router, silent) @@ -97,12 +98,36 @@ ProxyTable.prototype.setRoutes = function (router) { this.routes = []; Object.keys(router).forEach(function (path) { - var route = new RegExp(path, 'i'); + var route = new RegExp(path, 'i'), + target, + targetPath = null, + url = null, + match = router[path].match('/'); + + if(match){ + target = router[path].slice(0,match.index); + targetPath = router[path].slice(match.index); + }else{ + target = router[path]; + } + + match = path.match('/'); + if(match){ + url = path.slice(match.index); + } + + var location = target.split(':'), + host = location[0], + port = location.length === 1 ? 80 : location[1]; self.routes.push({ route: route, - target: router[path], - path: path + target: target, + targetPath: targetPath, + path: path, + url: url, + host:host, + port:port }); }); } @@ -134,32 +159,20 @@ ProxyTable.prototype.getProxyLocation = function (req) { } else { target += req.url; - for (var i in this.routes) { - var route = this.routes[i]; - if (target.match(route.route)) { - - var segments = route.path.split('/'); - - if (segments.length > 0) { - var lastSegment = new RegExp("/" + segments[segments.length - 1] + "$"); - - if(req.url.match(lastSegment)) { - req.url = req.url.replace(lastSegment, '/'); - } - } - - var location = route.target.split(':'), - host = location[0], - port = location.length === 1 ? 80 : location[1]; - + var routes = this.routes; + for(var i=0, max = routes.length; i