-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
76 lines (63 loc) · 1.88 KB
/
index.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
75
76
var http = require('http'),
url = require('url'),
httpProxy = require('http-proxy'),
config,
server,
proxy;
// did the user pass the config path via command line arg?
if (process.argv[2] && process.argv[2].indexOf('.json') > -1) {
// yes, load the config the user specified
config = require('./' + process.argv[2]);
} else {
// no config file passed, use default configuration
config = require('./default-config.json');
}
if (typeof config !== 'object') {
console.log('config is invalid, see default-config.json for an example');
process.exit();
}
function validArray (arr) {
return arr && Array.isArray(arr) && arr.length > 0;
}
// validate bind config
if (!validArray(config.bind)) {
console.log('config bind is invalid, see default-config.json for an example');
process.exit();
}
// create proxy
proxy = httpProxy.createProxyServer();
proxy.on('error', function (err, req, res) {
var op = 'cjdns-proxy error:\n' + JSON.stringify(err, null, '\t');
res.writeHead(500, { 'Content-Type': 'text/plain' });
res.end(op);
console.log(op);
});
// handle the requests to be proxied
function serverRequestHandler (req, res) {
var options,
host = req.headers.host;
// see ./default-config.json for the `admin` section
// should redirect cjdns-admin to 127.0.0.1:8
if (config.admin && config.admin.alias &&host.indexOf(config.admin.alias) === 0) {
host = config.admin.host;
}
// setup the proxy's config
options = {
target: 'http://' + host,
ws: true,
xfwd: true
};
// attempt to proxy the request
console.log('%s %s', req.method, req.url);
proxy.web(req, res, options);
}
// create server
server = http.createServer(serverRequestHandler);
// bind to each of the hosts in the config
config.bind.forEach(function (item) {
var hostParts = item.split(':'),
host = hostParts[0],
port = hostParts[1];
server.listen(port, host);
console.log('cjdns-proxy listening %s', item);
});