-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
64 lines (53 loc) · 1.62 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
"use strict";
const http = require('http');
// From RFC 2616 section 13.5.1
const hopByHopHeaders = [
"connection",
"keep-alive",
"proxy-authenticate",
"proxy-authorization",
"te",
"trailers",
"transfer-encoding",
"upgrade"
];
module.exports = opts => {
const agent = new http.Agent({ keepAlive: opts.keepAlive });
return (req, res) => {
const proxyReq = http.request({
method: req.method,
path: req.url,
hostname: opts.upstreamHost,
port: opts.upstreamPort,
agent
}, proxyRes => {
res.statusCode = proxyRes.statusCode;
for (let i = 0; i < proxyRes.rawHeaders.length; i += 2) {
const name = proxyRes.rawHeaders[i];
if (hopByHopHeaders.indexOf(name.toLowerCase()) >= 0) continue;
const value = proxyRes.rawHeaders[i + 1];
res.setHeader(name, value);
}
proxyRes.pipe(res);
});
for (let i = 0; i < req.rawHeaders.length; i += 2) {
const name = req.rawHeaders[i];
if (hopByHopHeaders.indexOf(name.toLowerCase()) >= 0) continue;
const value = req.rawHeaders[i + 1];
proxyReq.setHeader(name, value);
}
req.pipe(proxyReq);
proxyReq.on("error", e => {
res.write(e.message);
res.end();
});
req.on("error", e => {
proxyReq.abort();
res.write(e.message);
res.end();
});
req.on('aborted', () => {
proxyReq.abort();
});
};
};