-
Notifications
You must be signed in to change notification settings - Fork 119
/
proxy.js
74 lines (58 loc) · 1.82 KB
/
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
62
63
64
65
66
67
68
69
70
71
72
73
74
// 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 fs = require('fs');
var http = require('http');
var https = require('https');
var htproxy = require('http-proxy');
var port = parseInt(process.env.PORT);
var upstream_host = process.env.UPSTREAM_HOST;
var upstream_port = parseInt(process.env.UPSTREAM_PORT);
var upstream_size = parseInt(process.env.UPSTREAM_SIZE);
var sslCert = process.env.SSL_CERT;
var sslKey = process.env.SSL_KEY;
var sslPort = parseInt(process.env.SSL_PORT);
var addresses = [];
for(var i = 0; i < upstream_size; i++) {
addresses.push({
host: upstream_host,
port: upstream_port + i,
protocol: 'http',
});
}
// Proxy
var proxy = htproxy.createProxyServer({
// Set the x-forwarded- headers, because apps often need them to make
// decisions (such as about redirecting to SSL or a canonical host),
// and proxies often do this for you in the real world.
xfwd: true
});
// Hanle Error
proxy.on('error',function(err,req,res){
console.error("Proxy Error: ",err);
res.writeHead(500);
res.write("Upstream Proxy Error");
res.end();
});
// Main HTTP Server
http.createServer(function (req, res) {
var target = addresses.shift();
proxy.web(req, res, {target: target});
addresses.push(target);
}).listen(port, function() {
process.send({http: this.address().port});
});
if (sslCert && sslKey) {
https.createServer({
key: fs.readFileSync(sslKey),
cert: fs.readFileSync(sslCert)
},
function (req, res) {
var target = addresses.shift();
proxy.web(req, res, {target: target});
addresses.push(target);
}).listen(sslPort, function() {
process.send({https: this.address().port});
});
}