-
Notifications
You must be signed in to change notification settings - Fork 1
/
server.js
80 lines (71 loc) · 1.84 KB
/
server.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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
var Connect = require('connect');
var http = require('http');
process.on('uncaughtException', function(e) {
console.log(e.stack);
});
function proxyMiddleware(req, res, next) {
req.proxyTo = function(host, port) {
var cl = http.createClient(port, host);
var clReq = cl.request(req.method, req.url, req.headers);
var clRes_ = null;
// Forward body
req.on('data', function(data) {
clReq.write(data);
});
req.on('end', function(data) {
clReq.end(data);
if (clRes_)
clRes_.end();
});
// Forward response
clReq.on('response', function(clRes) {
res.writeHead(clRes.statusCode, clRes.headers);
clRes.on('data', function(data) {
res.write(data);
});
clRes.on('end', function(data) {
res.end(data);
});
clRes_ = clRes;
});
cl.on('error', function(error) {
res.writeHead(500, {});
res.end(error.toString());
});
};
next();
};
var BACKEND_HOST = "127.0.0.1";
var BACKEND_PORTS = [8001, 8002, 8003, 8004];
var rrIdx = 0;
var toAny = {
"/": true,
"/up": true,
"/main.css": true,
"/favicon.ico": true
};
function routingMiddleware(req, res, next) {
if (toAny.hasOwnProperty(req.url) ||
/^\/js\//.test(req.url) ||
/^\/img\//.test(req.url)) {
req.proxyTo(BACKEND_HOST, BACKEND_PORTS[rrIdx]);
rrIdx = (rrIdx + 1) % BACKEND_PORTS.length;
} else {
var idx = 0;
for(var i = 1; i < req.url.length; i++) {
var c = req.url.charCodeAt(i);
if (c == 47 || // 2nd '/'
c == 46) // 1st '.'
break;
idx += c;
}
idx = idx % BACKEND_PORTS.length;
req.proxyTo(BACKEND_HOST, BACKEND_PORTS[idx]);
}
};
Connect.createServer(
Connect.logger(),
proxyMiddleware,
routingMiddleware,
Connect.errorHandler({ dumpExceptions: true, showStack: true })
).listen(parseInt(process.env.PORT || "8000", 10));