-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
61 lines (53 loc) · 1.66 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
var http = require('http');
// Add `upgradeEx` and `connectEx` events to a server.
exports.addEvents = function(server) {
server.on('upgrade', exports.wrap(function(req, res) {
server.emit('upgradeEx', req, res);
}));
server.on('connect', exports.wrap(function(req, res) {
server.emit('connectEx', req, res);
}));
};
// Wrap a new-style upgrade/connect callback with an old-style signature.
exports.wrap = function(callback) {
return function(req, sock, head) {
var res;
// Check if we need to wrap at all.
if (sock.switchProtocols) {
res = sock;
}
else {
// 'shouldKeepAlive == false' ensures we send 'Connection: close' for
// responses that don't successfully switch protocols.
res = new http.ServerResponse(req);
res.shouldKeepAlive = false;
res.useChunkedEncodingByDefault = false;
// The alternate exit for a handler that accepts the upgrade.
var switchCb = null;
res.switchProtocols = function(fn) {
switchCb = fn;
this.end();
};
res.assignSocket(sock);
res.on('finish', function() {
res.detachSocket(sock);
// When finished, either upgrade, or close the socket.
if (!switchCb) {
sock.destroySoon();
return;
}
// Push the body part already received back in the socket buffer.
if (sock.push && head.length) {
sock.push(head);
}
switchCb(sock);
// Old-style streams compatibility.
if (!sock.push && head.length) {
sock.emit('data', head);
}
});
}
// Now run the new-style callback.
callback(req, res);
};
};