Skip to content

Instantly share code, notes, and snippets.

@matths
Created February 6, 2019 22:21
Show Gist options
  • Save matths/a0f746abb44c16cebcba9672e18f2fee to your computer and use it in GitHub Desktop.
Save matths/a0f746abb44c16cebcba9672e18f2fee to your computer and use it in GitHub Desktop.
basic reverse proxy middleware in comparison to the node-http-proxy module
var http = require('http');
var createProxyMiddleware = require('./proxy_middleware');
/*
/etc/hosts
127.0.0.1 hostA
127.0.0.1 hostB
*/
function getSocketPathForHostname (hostName) {
return __dirname+'/sockets/' + hostName;
}
var hostAproxyMiddleware = createProxyMiddleware(getSocketPathForHostname('hostA'))
var hostBproxyMiddleware = createProxyMiddleware(getSocketPathForHostname('hostB'))
var proxyServer = http.createServer().listen(80);
proxyServer.on('request', function (req, res) {
var hostName = req.headers.host.split(':')[0];
if (hostName == 'hostA') {
hostAproxyMiddleware(req, res);
}
if (hostName == 'hostB') {
hostBproxyMiddleware(req, res);
}
});
var http = require('http');
var httpProxy = require('http-proxy');
/*
/etc/hosts
127.0.0.1 hostA
127.0.0.1 hostB
*/
function getSocketPathForHostname (hostName) {
return __dirname+'/sockets/' + hostName;
}
function createProxyWithSocketPathAsTargetForHostName (hostName) {
var options = {
target: {
socketPath: getSocketPathForHostname(hostName)
},
ws: true,
xfwd: true,
secure: false
};
var proxy = httpProxy.createProxyServer(options);
proxy.on('error', function (err, req, res) {
// implement!
});
return proxy;
}
var hostAproxy = createProxyWithSocketPathAsTargetForHostName('hostA')
var hostBproxy = createProxyWithSocketPathAsTargetForHostName('hostB')
var proxyServer = http.createServer().listen(80);
proxyServer.on('request', function(req, res) {
var hostName = req.headers.host.split(':')[0];
if (hostName == 'hostA') {
hostAproxy.web(req, res);
}
if (hostName == 'hostB') {
hostBproxy.web(req, res);
}
});
var url = require('url');
var http = require('http');
module.exports = function createMiddleware (socketPath) {
return function proxyMiddleware (req, res) {
console.log('request ' + req.url);
req.pause();
var options = url.parse(req.url);
options.socketPath = socketPath;
options.headers = req.headers;
options.headers['x-forwarded-for'] = req.connection.remoteAddress;
options.method = req.method;
options.agent = false;
var proxy = http.request(options, function(appRes) {
appRes.pause();
res.writeHeader(appRes.statusCode, appRes.headers);
appRes.pipe(res);
appRes.resume();
});
proxy.on('error', function (e) {
console.error('problem with request:', e.message);
res.end('500 Internal server error');
});
req.pipe(proxy);
req.resume();
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment