forked from coyove/leancloud-test
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
executable file
·202 lines (163 loc) · 6.1 KB
/
server.js
File metadata and controls
executable file
·202 lines (163 loc) · 6.1 KB
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
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
'use strict';
// 端口一定要从环境变量 `LEANCLOUD_APP_PORT` 中获取。
// LeanEngine 运行时会分配端口并赋值到该变量。
var PORT = parseInt(process.env.LEANCLOUD_APP_PORT || process.env.PORT || 3000);
// This file is modified based on node-http-proxy.
//
// node-http-proxy
//
// Copyright (c) 2010-2016 Charlie Robbins, Jarrett Cruger & the Contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
var extend = require('util')._extend;
var http = require('http');
var url = require('url');
const urlHeader = "x-forwarded-url";
function forward(req) {
var outgoing = {};
outgoing.method = req.method;
outgoing.headers = extend({}, req.headers);
delete outgoing.headers[urlHeader];
outgoing.agent = false;
outgoing.headers = outgoing.headers || {};
if (typeof outgoing.headers.connection !== 'string' || !/(^|,)\s*upgrade\s*($|,)/i.test(outgoing.headers.connection))
outgoing.headers.connection = 'close';
var outgoingPath = req.headers[urlHeader];
if (outgoingPath) {
outgoing.path = outgoingPath;
var u = url.parse(outgoingPath);
if (u) {
outgoing.headers.host = u.hostname + ":" + (u.port ? u.port : "80");
outgoing.host = u.hostname;
outgoing.port = parseInt(u.port);
} else {
console.log("can't parse url:", outgoingPath);
}
}
return outgoing;
};
var server = http.createServer(function (req, res) {
if (req.url === '/1.1/functions/_ops/metadatas') {
res.writeHead(404, {"Content-Type": "text/plain"});
return res.end();
}
if ((req.method === 'DELETE' || req.method === 'OPTIONS') && !req.headers['content-length']) {
req.headers['content-length'] = '0';
delete req.headers['transfer-encoding'];
}
var options = forward(req);
if (!(urlHeader in req.headers)) {
res.write('Hello World');
return res.end();
}
var proxyReq = http.request(options);
req.pipe(proxyReq);
proxyReq.on('response', function(proxyRes) {
if (req.httpVersion === '1.0') {
delete proxyRes.headers['transfer-encoding'];
}
if (!proxyRes.headers.connection) {
proxyRes.headers.connection = req.headers.connection || 'keep-alive';
}
var rawHeaderKeyMap = {};
if (proxyRes.rawHeaders != undefined) {
for (var i = 0; i < proxyRes.rawHeaders.length; i += 2) {
var key = proxyRes.rawHeaders[i];
rawHeaderKeyMap[key.toLowerCase()] = key;
}
}
Object.keys(proxyRes.headers).forEach(function(key) {
var header = proxyRes.headers[key];
if (header == undefined) return;
key = rawHeaderKeyMap[key] || key;
res.setHeader(String(key).trim(), header);
});
if (proxyRes.statusMessage) {
res.writeHead(proxyRes.statusCode, proxyRes.statusMessage);
} else {
res.writeHead(proxyRes.statusCode);
}
proxyRes.pipe(res);
});
//proxyReq.end();
});
server.on('upgrade', function (req, socket, head) {
function setsockopt(socket) {
socket.setTimeout(0);
socket.setNoDelay(true);
socket.setKeepAlive(true, 0);
return socket;
};
function onOutgoingError(err) {
console.log(err);
socket.end();
};
if (req.method !== 'GET' || !req.headers.upgrade) {
console.log("invalid method for WebSocket");
socket.destroy();
return;
}
if (req.headers.upgrade.toLowerCase() !== 'websocket') {
console.log("invalid upgrade for WebSocket");
socket.destroy();
return;
}
setsockopt(socket);
if (head && head.length) socket.unshift(head);
var proxyReq = http.request(forward(req));
// Error Handler
proxyReq.on('error', onOutgoingError);
proxyReq.on('response', function (res) {
// if upgrade event isn't going to happen, close the socket
if (!res.upgrade) socket.end();
});
proxyReq.on('upgrade', function(proxyRes, proxySocket, proxyHead) {
proxySocket.on('error', onOutgoingError);
// The pipe below will end proxySocket if socket closes cleanly, but not
// if it errors (eg, vanishes from the net and starts returning
// EHOSTUNREACH). We need to do that explicitly.
socket.on('error', function () {
proxySocket.end();
});
setsockopt(proxySocket);
if (proxyHead && proxyHead.length) proxySocket.unshift(proxyHead);
//
// Remark: Handle writing the headers to the socket when switching protocols
// Also handles when a header is an array
//
socket.write(
Object.keys(proxyRes.headers).reduce(function (head, key) {
var value = proxyRes.headers[key];
if (!Array.isArray(value)) {
head.push(key + ': ' + value);
return head;
}
for (var i = 0; i < value.length; i++) {
head.push(key + ': ' + value[i]);
}
return head;
}, ['HTTP/1.1 101 Switching Protocols'])
.join('\r\n') + '\r\n\r\n'
);
proxySocket.pipe(socket).pipe(proxySocket);
});
return proxyReq.end(); // XXX: CHECK IF THIS IS THIS CORRECT
});
server.listen(PORT);