-
Notifications
You must be signed in to change notification settings - Fork 0
/
localhosts.js
72 lines (63 loc) · 1.95 KB
/
localhosts.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
var http = require('http');
var httpProxy = require('http-proxy');
var fs = require('fs');
var LineByLineReader = require('line-by-line');
var serveStatic = require('serve-static');
var proxy = httpProxy.createProxyServer({});
var targets = {};
var server = http.createServer(function (req, res) {
var target = targets[req.headers.host];
if (target) {
target(req, res);
} else {
res.writeHead(404);
res.end('Host not found: ' + req.headers.host);
}
});
function loadHosts() {
console.log('Loading /etc/hosts');
var linePattern = /^\s*\S+\s+(\S+)\s*#\s*(proxy|static)\s+([^\s#]+)/i;
var lr = new LineByLineReader('/etc/hosts');
var newTargets = {};
lr.on('error', function (err) {
console.log('Error reading /etc/hosts: ' + err);
});
lr.on('line', function (line) {
var match = line.match(linePattern);
if (match) {
var host = match[1];
var type = match[2];
var target = match[3];
if (type.toLowerCase() == 'static') {
console.log('Static ' + host + ' => ' + target);
var static = serveStatic(target);
newTargets[host] = function (req, res) {
static(req, res, function () {
res.writeHead(404);
res.end('Not found: ' + req.url + ' in ' + target);
});
}
}
else if (type.toLowerCase() == 'proxy') {
if (target.match(/^\d+$/)) {
target = 'http://localhost:' + target;
} else if (!target.match(/^https?\:\/\//)) {
target = 'http://' + target;
}
console.log('Proxy ' + host + ' => ' + target);
newTargets[host] = function (req, res) {
proxy.web(req, res, { target: target }, function (e) {
res.writeHead(504);
res.end('Unable to connect to ' + target + ': ' + e);
});
}
}
}
});
lr.on('end', function () {
targets = newTargets;
});
}
fs.watch('/etc/hosts', loadHosts);
loadHosts();
server.listen(80);