Skip to content

Optimized table based routing and changed its behavior to a more consistent one. #133

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
63 changes: 38 additions & 25 deletions lib/node-http-proxy/proxy-table.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,8 @@

var util = require('util'),
events = require('events'),
fs = require('fs');
fs = require('fs'),
url = require('url');

//
// ### function ProxyTable (router, silent)
Expand Down Expand Up @@ -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
});
});
}
Expand Down Expand Up @@ -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<max; i++){
var route = routes[i];
if (target.match(route.route)) {
var replaceStr = route.targetPath ? route.targetPath : '/';
req.url = req.url.replace(route.url, replaceStr);

return {
port: port,
host: host
port: route.port,
host: route.host
};
}
}
}

return null;
};

Expand Down