commit b0d0e77f14bf94c6c3fac41a5273968548779353
parent 9c93d9b4f14020b55dae512c508fa829ecbbd3f4
Author: Robin Bron <robin@finwo.nl>
Date: Tue, 4 Oct 2016 16:20:15 +0200
Working version
Diffstat:
4 files changed, 94 insertions(+), 0 deletions(-)
diff --git a/.gitignore b/.gitignore
@@ -35,3 +35,6 @@ jspm_packages
# Optional REPL history
.node_repl_history
+
+# Editor files
+.idea
diff --git a/Procfile b/Procfile
@@ -0,0 +1 @@
+web: forever index.js
diff --git a/index.js b/index.js
@@ -0,0 +1,63 @@
+var http = require('http'),
+ httpProxy = require('http-proxy');
+
+var port = process.env.PORT || 3000,
+ proxies = {},
+ commonRegex = {
+ targetHost: new RegExp('(.*)(localhost|'+(process.env.DOMAIN)+')', 'i'),
+ dotProtocol: /^(https?)\./i,
+ trimDots: /(^\.|\.$)/g,
+ protocol: /^https?:\/\//i
+ };
+
+function error_500(res) {
+ res.writeHead(500, {
+ 'Content-Type': 'text/plain'
+ });
+ res.end('Internal server error');
+}
+
+var server = http.createServer(function(req, res) {
+ // HTTP
+
+ // Let's get the target host
+ var targetHost = commonRegex.targetHost.exec(req.headers.host)[1] || null,
+ proto = commonRegex.dotProtocol.test(targetHost);
+
+ // Fix the protocol
+ if (proto) {
+ targetHost = targetHost.replace(commonRegex.dotProtocol, function() {
+ return arguments[1]+'://';
+ });
+ } else {
+ targetHost = 'http://' + targetHost;
+ }
+
+ // Strip surrounding dots
+ targetHost = targetHost.replace(commonRegex.trimDots, '');
+
+ // Check if we have a proxy for this yet
+ if (!proxies[targetHost]) {
+ try {
+ proxies[targetHost] = new httpProxy.createProxyServer({
+ target:targetHost,
+ autoRewrite: true,
+ cookieDomainRewrite: req.headers.host
+ });
+ } catch(e) {
+ console.log(e);
+ proxies[targetHost] = null;
+ }
+ }
+
+ // And proxy the request
+ req.headers.host = targetHost.replace(commonRegex.protocol, '');
+ proxies[targetHost].web(req, res);
+});
+
+server.on('upgrade', function(req, socket, head) {
+ // Websockets
+});
+
+server.listen(port);
+console.log("Server now listening on port", port);
diff --git a/package.json b/package.json
@@ -0,0 +1,27 @@
+{
+ "name": "node-proxy-dokku",
+ "version": "1.0.0",
+ "description": "Nodejs HTTP(S) proxy based on node-proxy & environment variables",
+ "main": "index.js",
+ "scripts": {
+ "test": "echo \"Error: no test specified\" && exit 1"
+ },
+ "repository": {
+ "type": "git",
+ "url": "git+https://github.com/finwo/node-proxy-dokku.git"
+ },
+ "keywords": [
+ "proxy"
+ ],
+ "author": "Robin Bron",
+ "license": "MIT",
+ "bugs": {
+ "url": "https://github.com/finwo/node-proxy-dokku/issues"
+ },
+ "homepage": "https://github.com/finwo/node-proxy-dokku#readme",
+ "dependencies": {
+ "forever": "^0.15.2",
+ "http": "0.0.0",
+ "http-proxy": "^1.15.1"
+ }
+}