-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathserver.js
121 lines (97 loc) · 2.95 KB
/
server.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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
"use strict";
var utils = require("./utils");
var respMod = require("resp-modifier");
var connect = require("connect");
var httpProxy = require("http-proxy");
var merge = require("lodash.merge");
function Foxy (config) {
var foxy = this;
foxy.config = config;
foxy.app = (function () {
/**
* Connect app for middleware stacking.
*/
var app = connect();
foxy.config.middleware.forEach(function (mw) {
app.use(mw);
});
/**
* Proxy server for final requests
*/
var proxy = httpProxy.createProxyServer(merge(foxy.config.proxyOptions, {
target: foxy.config.target,
headers: foxy.config.reqHeaders(foxy.config)
}));
/**
* Proxy errors out to user errHandler
*/
proxy.on("error", foxy.config.errHandler);
/**
* Modify the proxy response
*/
proxy.on("proxyRes", utils.proxyRes(foxy.config));
/**
* Handle `upgrade` event to proxy WebSockets
* https://github.com/nodejitsu/node-http-proxy#proxying-websockets
*/
app.handleUpgrade = function (req, socket, head) {
proxy.ws(req, socket, head);
};
/**
* Push the final handler onto the mw stack
*/
app.stack.push({route: "", id: "foxy-resp-mod", handle: finalhandler});
/**
* Intercept regular .use() calls to
* ensure final handler is always called
* @param path
* @param fn
* @param opts
*/
var mwCount = 0;
app.use = function (path, fn, opts) {
opts = opts || {};
if (typeof path !== "string") {
fn = path;
path = "";
}
if (path === "*") {
path = "";
}
if (!opts.id) {
opts.id = "foxy-mw-" + (mwCount += 1);
}
// Never override final handler
app.stack.splice(app.stack.length - 1, 0, {
route: path,
handle: fn,
id: opts.id
});
};
/**
* Final handler - give the request to the proxy
* and cope with link re-writing
* @param req
* @param res
*/
function finalhandler(req, res) {
/**
* Rewrite the links
*/
respMod({
rules: utils.getRules(foxy.config, req.headers.host),
blacklist: foxy.config.blacklist,
whitelist: foxy.config.whitelist
})(req, res, function () {
/**
* Pass the request off to http-proxy now that
* all middlewares are done.
*/
proxy.web(req, res);
});
}
return app;
})();
return foxy;
}
module.exports = Foxy;