Created
October 19, 2018 18:11
-
-
Save joshlarsen/cee0fc5c1e6c49a5ac9bd0a094a35645 to your computer and use it in GitHub Desktop.
Simple node.js proxy with dynamic route lookups via Redis
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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