forked from strongloop/node-foreman
-
Notifications
You must be signed in to change notification settings - Fork 0
/
forward.js
63 lines (46 loc) · 1.35 KB
/
forward.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
// Copyright IBM Corp. 2012,2016. All Rights Reserved.
// Node module: foreman
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT
var http = require('http');
var url = require('url');
var httpProxy = require('http-proxy');
function startForward(proxy_port, proxy_host) {
var proxy = httpProxy.createProxyServer({});
var httpServer = http.createServer(function(req, res) {
var _url = url.parse(req.url);
var dest = _url.hostname;
var port = _url.port || 80;
var host = '127.0.0.1';
var target;
if(proxy_host === '<ANY>' || proxy_host === dest) {
target = {
host: host,
port: port
};
var urlmatch = req.url.match(/http:\/\/[^/]*:?[0-9]*(\/.*)$/);
if(urlmatch) {
req.url = urlmatch[1];
} else {
req.url = '/';
}
} else {
target = {
host: dest,
port: port
};
}
proxy.web(req, res, {target: target});
});
proxy.on('upgrade', function (req, socket, head) {
proxy.ws(req, socket, head);
});
proxy.on('error', function(err, req, res){
console.error('Proxy Error: ', err);
res.writeHead(500);
res.write('Upstream Proxy Error');
res.end();
});
httpServer.listen(proxy_port);
}
startForward(process.env.PROXY_PORT, process.env.PROXY_HOST);