Commit 933b902a authored by Cédric de Saint Martin's avatar Cédric de Saint Martin Committed by Cédric de Saint Martin

Add support for web socket middle wares

parent 30dac898
......@@ -177,6 +177,16 @@ exports.createServer = function () {
? https.createServer(options.https, handler)
: http.createServer(handler);
//
// process websocket as well if middleware(s) use(s) it
//
websocketHandler = exports.stackWebSocket(handlers, proxy);
if (websocketHandler != undefined) {
server.on('upgrade', function (req, socket, head) {
websocketHandler(req, socket, head);
});
}
server.on('close', function () {
proxy.close();
});
......@@ -326,6 +336,53 @@ exports.stack = function stack (middlewares, proxy) {
return handle;
};
//
// ### function stackWebSocket (middlewares, proxy)
// #### @middlewares {Array} Array of functions to stack.
// #### @proxy {HttpProxy|RoutingProxy} Proxy instance to
// Iteratively build up a single handler to the `http.Server`
// `request` event (i.e. `function (req, res)`) by wrapping
// each middleware `layer` into a `child` middleware which
// is in invoked by the parent (i.e. predecessor in the Array).
//
// adapted from https://github.com/creationix/stack
//
exports.stackWebSocket = function stackWebSocket (middlewares, proxy) {
var handle;
middlewares.reverse().forEach(function (layer) {
//
// Check if middleware as websocket strategy. If so, add it
//
if (!layer.proxyWebSocketRequest) return;
var child = handle;
handle = function (req, socket, head) {
var next = function (err) {
if (err) {
socket.end();
console.error('Error in websocket middleware(s): %s', err.stack);
return;
}
if (child) {
child(req, res);
}
};
//
// Set the prototype of the `next` function to the instance
// of the `proxy` so that in can be used interchangably from
// a `connect` style callback and a true `HttpProxy` object.
//
// e.g. `function (req, res, next)` vs. `function (req, res, proxy)`
//
next.__proto__ = proxy;
layer.proxyWebSocketRequest(req, socket, head, next);
};
});
return handle;
};
//
// ### function _getAgent (host, port, secure)
// #### @options {Object} Options to use when creating the agent.
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment