Skip to content

Instantly share code, notes, and snippets.

@highwaycoder
Last active December 14, 2015 09:19
Show Gist options
  • Save highwaycoder/5063980 to your computer and use it in GitHub Desktop.
Save highwaycoder/5063980 to your computer and use it in GitHub Desktop.
Simple, http-based node.js proxy server, connects clients to node.js applications based on the domain name used in the request. Not currently working.
{"apps" :
[
{
"name": "fieldlord",
"domains": ["fieldlord.chaos-kitten.com","fieldlord"],
"port": "1337"
}
]
}
var http = require('http'),
fs = require('fs');
var apps = require('./apps').apps;
fs.watchFile('./apps.json',function(c,p) {
apps = require('./apps').apps;
});
var app = http.createServer(function(request,response) {
var found = false;
for(i in apps) {
for(j in apps[i].domains) {
if(apps[i].domains[j] === request.headers.host) {
found = true;
var options = {
hostname: request.headers.host,
port: apps[i].port,
path: request.url,
method: request.method
};
var proxy_request = http.request(options,function(proxy_response) {
response.writeHead(proxy_response.statusCode,proxy_response.headers);
proxy_response.on('data',function(chunk) {
response.write(chunk,'binary');
});
proxy_response.on('end',function() {
response.end();
});
});
proxy_request.on('error',function() {
response.writeHead(500);
response.end('500 Error: application ' + request.headers.host + ' not available (not running?).');
});
request.on('data',function(chunk) {
proxy_request.write(chunk,'binary');
});
request.on('end',function() {
proxy_request.end();
});
}
}
}
if(!found) {
response.writeHead(404);
response.end('Application information could not be retrieved for: ' + request.headers.host);
}
});
app.on('error',function(err) {
console.log("Warning: could not bind to port 80, attempting rebind on port 8080 (are you root?): " + err.message);
app.listen(8080);
});
app.listen(80);
@highwaycoder
Copy link
Author

Changlog:
r1: initial
r2: stopped the infinite wait bug, but responses are empty (not connecting correctly to underlying app?)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment