-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathapp.js
61 lines (53 loc) · 1.55 KB
/
app.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
var fs = require('fs'),
nconf = require('nconf');
var http = require('http'),
https = require('https'),
httpProxy = require('http-proxy');
var debugging = true;
var routing = require('./redis_routing_table');
var routingTable = {};
function log(message) {
if (debugging) console.log(message);
}
nconf.file({ file: 'config.json' }).load(function(err) {
if (!err) {
start();
} else {
console.log("Couldn't load config.json");
}
});
function internalServerError(res) {
res.writeHead(500, {
'Content-Type': 'text/plain'
});
res.end('Something went wrong!');
}
function start() {
debugging = nconf.get('debugging');
routing.loadRoutingTable(nconf, routingTable);
server = httpProxy.createServer(function (req, res, proxy) {
var buffer = httpProxy.buffer(req);
var destinationHosts = routingTable[req.headers.host];
if (destinationHosts != null && destinationHosts.length > 0) {
var destinationHost = destinationHosts[Math.floor(Math.random() * destinationHosts.length)];
log(req.url + " => " + destinationHost);
req.headers.host = destinationHost;
if (destinationHost != null) {
proxy.proxyRequest(req, res, {
host: destinationHost,
port: 80,
buffer: buffer
});
} else {
log("Host not found!");
internalServerError(res)
}
} else {
log("No destination hosts!");
internalServerError(res)
}
}).listen(80);
server.proxy.on('proxyError', function (err, req, res) {
internalServerError(res);
});
}