-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproxy.js
More file actions
60 lines (52 loc) · 1.55 KB
/
proxy.js
File metadata and controls
60 lines (52 loc) · 1.55 KB
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
const http = require('http');
const httpProxy = require('http-proxy');
const express = require('express');
const cookieParser = require('cookie-parser');
module.exports = function proxySwitcher({
port = 5050,
primary,
secondary,
onRequest = () => {},
switcher = (req) => true,
logging = false,
}) {
// create a server
const app = express();
const primaryProxy = httpProxy.createProxyServer(primary);
const secondaryProxy = httpProxy.createProxyServer(secondary);
const httpServer = http.createServer(app);
function log(...args) {
if (logging) console.log(...args);
}
app.use(cookieParser());
// proxy http
app.use(function(req, res) {
const isPrimaryRequest = switcher(req);
log('proxying', req.method, req.url, isPrimaryRequest);
if (isPrimaryRequest) {
primaryProxy.web(req, res, {});
} else {
secondaryProxy.web(req, res, {});
}
});
primaryProxy.on('proxyReq', onRequest);
primaryProxy.on('proxyReqWs', onRequest);
primaryProxy.on('error', function(err) {
console.log('error primary proxy', err);
});
secondaryProxy.on('error', function(err) {
console.log('error secondary proxy', err);
})
// proxy ws
httpServer.on('upgrade', function (req, socket, head) {
const isPrimaryRequest = switcher(req);
log('proxying websocket', req.method, req.url, isPrimaryRequest);
if (isPrimaryRequest) {
primaryProxy.ws(req, socket, head);
} else {
secondaryProxy.ws(req, socket, head);
}
});
httpServer.listen(port);
console.log(`listening localhost:${port}`);
}