Skip to content

Instantly share code, notes, and snippets.

@jameswomack
Created August 15, 2017 22:04
Show Gist options
  • Select an option

  • Save jameswomack/0fb76f93200b88727d42428d03edca72 to your computer and use it in GitHub Desktop.

Select an option

Save jameswomack/0fb76f93200b88727d42428d03edca72 to your computer and use it in GitHub Desktop.
Dynamically Updated Node.js HTTP Proxy Server (UI Edge Server)
const http = require('http'),
httpProxy = require('http-proxy'),
HttpProxyRules = require('http-proxy-rules');
let proxyConfiguration = {
rules: {
'.*/test': 'http://localhost:8080/cool', // Rule (1)
'.*/test2/': 'http://localhost:8080/cool2/' // Rule (2)
},
default: 'http://localhost:8080' // default target
}
// Set up proxy rules instance
let proxyRules = new HttpProxyRules(proxyConfiguration);
// A registry server alongside this module can call this function to
// update the rules as microapps appear, disappear or change
module.exports.updateProxyConfiguration = function (newProxyConfiguration) {
proxyConfiguration = newProxyConfiguration;
proxyRules = new HttpProxyRules(proxyConfiguration);
};
// Create reverse proxy instance
const proxy = httpProxy.createProxy();
// Create http server that leverages reverse proxy instance
// and proxy rules to proxy requests to different targets
http.createServer(function(req, res) {
// a match method is exposed on the proxy rules instance
// to test a request to see if it matches against one of the specified rules
let target = proxyRules.match(req);
if (target) {
return proxy.web(req, res, {
target: target
});
}
res.writeHead(500, { 'Content-Type': 'text/plain' });
res.end('The request url and path did not match any of the listed rules!');
}).listen(6010, () => console.info('Listening'));
const http = require('http'),
ProxyServer = require('./proxy-server');
// Create http server that microapps talk to register themselves
// for routes in the edge server
http.createServer(function(req, res) {
ProxyServer.updateProxyConfiguration(req.body.proxyConfiguration)
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ ok : true }));
}).listen(6020, () => console.info('Listening'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment