forked from robjperez/simple_reverse_proxy
-
Notifications
You must be signed in to change notification settings - Fork 2
/
app.js
60 lines (53 loc) · 1.65 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
const express = require('express');
const proxy = require('http-proxy-middleware');
const cors = require('cors');
const fs = require('fs');
const path = require('path');
const http = require('http');
const https = require('https');
const processUrl = (originalUrl) => {
const urlRegExp = new RegExp(`^/([a-zA-Z0-9:.-]+.(?:opentok.com|tokbox.com)[:0-9]*)/(.*)$`);
const matches = originalUrl.match(urlRegExp);
if (!matches || matches.length < 3) {
return 'https://tokbox.com';
}
const returnUrl = `https://${matches[1]}/${matches[2]}`;
console.log(`${originalUrl} -> ${returnUrl}`)
return returnUrl;
};
const proxyRouter = (req) => {
if (!req.originalUrl && !req.url) {
return '';
}
return processUrl(req.originalUrl || req.url);
};
const otProxy = proxy({
target: 'https://tokbox.com', // Not really used since we are changing the target with router function
router: proxyRouter,
changeOrigin: true,
ignorePath: true,
ws: true,
});
const app = express()
const PORT = process.env.PORT || 3000;
const USE_SSL = process.env.USE_SSL
|| process.argv.indexOf('-use-ssl') > -1;
app.use('/', cors(), otProxy);
app.use('/proxy', cors(), otProxy);
let server;
if (!USE_SSL) {
console.log("Starting over HTTP");
server = http.createServer(app);
}
else {
console.log("Starting over HTTPS");
const key = fs.readFileSync(path.join(__dirname, 'selfsigned.key'));
const cert = fs.readFileSync(path.join(__dirname, 'selfsigned.crt'));
const options = {
key: key,
cert: cert
};
server = https.createServer(options, app);
}
server.listen(PORT, () => console.log(`Reverse proxy started.`))
process.once('SIGINT', () => { server.close(); });