forked from shakyShane/foxy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
103 lines (84 loc) · 2.52 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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
var respMod = require("resp-modifier");
var httpProxy = require("http-proxy");
var http = require("http");
var utils = require("./lib/utils");
/**
* @param opts
* @param [additionalRules]
* @param [additionalMiddleware]
* @returns {*}
* @param errHandler
*/
function init(opts, additionalRules, additionalMiddleware, errHandler) {
var proxyServer = httpProxy.createProxyServer();
var hostHeader = utils.getProxyHost(opts);
var host = false;
if (!errHandler) {
errHandler = function (err) {
console.log(err.message);
}
}
var server = http.createServer(function(req, res) {
if (!host) {
host = req.headers.host;
}
var middleware = respMod({
rules: getRules(req.headers.host)
});
var next = function () {
proxyServer.web(req, res, {
target: opts.target,
headers: {
host: hostHeader,
"accept-encoding": "identity",
agent: false
}
});
};
if (additionalMiddleware) {
additionalMiddleware(req, res, function (success) {
if (success) {
return;
}
utils.handleIe(req);
middleware(req, res, next);
});
} else {
utils.handleIe(req);
middleware(req, res, next);
}
}).on("error", errHandler);
// Handle proxy errors
proxyServer.on("error", errHandler);
// Remove headers
proxyServer.on("proxyRes", function (res) {
if (res.statusCode === 302 || res.statusCode === 301) {
if (opts.port == 80 || opts.port == 443) {
var match = opts.host;
}
else {
var match = opts.host + ':' + opts.port;
}
res.headers.location = res.headers.location.replace(match, host);
}
utils.removeHeaders(res.headers, ["content-length", "content-encoding"]);
host = false;
});
function getRules(host) {
var rules = [utils.rewriteLinks(opts, host)];
if (additionalRules) {
if (Array.isArray(additionalRules)) {
additionalRules.forEach(function (rule) {
rules.push(rule);
})
} else {
rules.push(additionalRules);
}
}
return rules;
}
return server;
}
module.exports = {
init: init
};