-
Notifications
You must be signed in to change notification settings - Fork 4
/
dispatcher.js
40 lines (36 loc) · 1.02 KB
/
dispatcher.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
var httpProxy = require('http-proxy'),
proxy = httpProxy.createProxyServer();
var PROXY_MAX_TRY = 50,
PROXY_RETRY_TIME = 1000;
function proxyTo(req, res, ipaddr, port, attempt) {
if (!attempt) {
attempt = 0;
}
proxy.web(req, res, { target: 'http://' + ipaddr + ':' + port }, function(e) {
if (attempt > PROXY_MAX_TRY) {
res.writeHead(500);
res.end('Could not proxy request: ' + req.headers.host);
} else {
setTimeout(function() {
proxyTo(req, res, ipaddr, port, attempt + 1);
}, PROXY_RETRY_TIME);
}
});
}
function proxyWsTo(req, socket, head, ipaddr, attempt) {
if (!attempt) {
attempt = 0;
}
proxy.ws(req, socket, head, { target: 'http://' + ipaddr }, function(e) {
if (attempt > PROXY_MAX_TRY) {
socket.close();
} else if (e) {
alarm.raise(e);
setTimeout(function() {
proxyWsTo(req, socket, head, ipaddr, attempt + 1);
}, PROXY_RETRY_TIME);
}
});
}
module.exports.proxyTo = proxyTo;
module.exports.proxyWsTo = proxyWsTo;