-
Notifications
You must be signed in to change notification settings - Fork 0
/
reverse_proxy.js
executable file
·61 lines (53 loc) · 1.83 KB
/
reverse_proxy.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
#!/usr/bin/env node
const argparse = require('argparse');
const http = require('http');
const https = require('https');
const url = require('url');
function main() {
const parser = argparse.ArgumentParser({
description: 'Simple reverse proxy (to quickly test switching)',
});
parser.addArgument(['-p', '--port'], {
type: Number,
defaultValue: 3006,
help: 'Port to run on (default: %(defaultValue)s)',
});
parser.addArgument('BACKEND_URL', {
help: 'Backend website',
});
const args = parser.parseArgs();
const backend = url.parse(args.BACKEND_URL);
const backendPort = backend.port || (backend.protocol === 'https:' ? 443 : 80);
const srv = http.createServer((req, res) => {
const request = url.parse(req.url);
const options = {
host: backend.hostname,
port: backendPort,
path: request.path,
method: req.method,
headers: req.headers,
rejectUnauthorized: false,
};
options.headers['host'] = backend.host;
console.log(
`${options.method} ${backend.protocol}//${options.host}:${options.port}${options.path}`);
const requestFunc = backend.protocol === 'https:' ? https.request : http.request;
const backendRequest = requestFunc(options, backendResponse => {
res.writeHead(backendResponse.statusCode, backendResponse.headers);
backendResponse.on('data', chunk => {
res.write(chunk);
});
backendResponse.on('end', () => {
res.end();
});
});
req.on('data', chunk => {
backendRequest.write(chunk);
});
req.on('end', () => {
backendRequest.end();
});
});
srv.listen(args.port);
}
main();