-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
109 lines (80 loc) · 2.15 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
103
104
105
106
107
'use strict';
const url = require('url');
var http = require('http'),
httpProxy = require('http-proxy'),
Router = require('./router');
function RoutingProxy (options) {
this.proxy = httpProxy.createProxyServer(options);
this.router = new Router();
this.server = undefined;
this.dispatch = RoutingProxy.prototype.dispatch.bind(this);
}
RoutingProxy.prototype.dispatch = function () {
this.router.dispatch.apply(this.router, arguments);
};
RoutingProxy.prototype.listen = function () {
this.server = this.server || http.createServer(this.dispatch);
this.server.listen.apply(this.server, arguments);
return this;
};
RoutingProxy.prototype.when = function () {
this.router.when.apply(this.router, arguments);
return this;
};
RoutingProxy.prototype.upstream = function (route, _upstreams) {
var upstreams = _upstreams;
if (typeof upstreams === 'string') {
upstreams = [upstreams];
}
this.router.when(route, upstreamer.bind(undefined, {
proxy: this.proxy,
upstreams: upstreams.slice(),
destination: upstreams[0],
route: route,
i: 0
}));
return this;
};
function upstreamer (ctx, req, res) {
var upstreams = ctx.upstreams;
if (upstreams.length === 0) {
send502();
return;
}
var destination = url.parse(ctx.destination);
ctx.i = (ctx.i + 1) % upstreams.length;
var upstream = upstreams[ctx.i];
var requested_url = url.parse(req.url).pathname;
// http://xxxx/{ctx.route}
// must substract ctx.route from req.url
req.url = req.url.slice( ctx.route.length )
if (req.url[0] !== '/') req.url = '/' + req.url;
// must pass host header from the destination
req.headers.host = destination.host;
//console.log(req.headers)
ctx.proxy.web(req, res, {
target: upstream
}, function (err) {
if (err.code === 'ECONNREFUSED' || err.code === 'EHOSTUNREACH') {
var index = upstreams.indexOf(upstream);
if (index !== -1) {
upstreams.splice(index, 1);
setTimeout(function () {
upstreams.push(upstream);
}, 5000);
}
send502();
return;
}
if (err.code === 'ECONNRESET') {
send502();
return;
}
throw(err);
});
function send502 () {
res.statusCode = 502;
res.end();
}
}
module.exports = RoutingProxy;