Skip to content

Instantly share code, notes, and snippets.

@joshlarsen
Created October 19, 2018 18:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joshlarsen/cee0fc5c1e6c49a5ac9bd0a094a35645 to your computer and use it in GitHub Desktop.
Save joshlarsen/cee0fc5c1e6c49a5ac9bd0a094a35645 to your computer and use it in GitHub Desktop.
Simple node.js proxy with dynamic route lookups via Redis
const http = require('http');
const httpProxy = require('http-proxy');
const redis = require('redis');
// listen port
const port = 5050;
// redis client
const client = redis.createClient();
// create proxy server
const proxy = httpProxy.createProxyServer({});
// create the server
const server = http.createServer((req, res) => {
const fqdn = req.headers.host.split(':')[0];
const hostname = fqdn.split('.')[0];
// redis lookup
client.hget('routes', fqdn, (err, data) => {
if (data) {
const route = data.split(':');
const target = { host: route[0], port: route[1] };
// proxy the request upstream
proxy.web(req, res, {
target: target
});
console.log(`DEBUG: routing ${hostname} to ${target.host}:${target.port}`);
} else {
// send a 404 and close the connection if no route was found
res.writeHead(404);
res.end();
console.log(`DEBUG: no route found for ${hostname}`);
}
});
});
server.listen(port);
console.log(`DEBUG: listening on port ${port}`);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment