Skip to content

Commit

Permalink
[refactor] Improved event handler cleanup
Browse files Browse the repository at this point in the history
  • Loading branch information
Marak committed Oct 25, 2011
1 parent 9e630da commit 9f92332
Showing 1 changed file with 40 additions and 18 deletions.
58 changes: 40 additions & 18 deletions lib/node-http-proxy/http-proxy.js
Expand Up @@ -236,24 +236,46 @@ HttpProxy.prototype.proxyRequest = function (req, res, buffer) {

res.on('drain', ondrain);

//
// When the `reverseProxy` `response` ends, end the
// corresponding outgoing `res` unless we have entered
// an error state. In which case, assume `res.end()` has
// already been called and the 'error' event listener
// removed.
//
response.on('end', function () {
if (!errState) {
reverseProxy.removeListener('error', proxyError);

try { res.end() }
catch (ex) { console.error("res.end error: %s", ex.message) }

// Emit the `end` event now that we have completed proxying
self.emit('end', req, res);
}
});
function onend() {
cleanup();
res.end();
}

function onclose() {
cleanup();
res.destroy();
}

response.on('close', onclose);
response.on('end', onend);

response.on('error', proxyError);
res.on('error', proxyError);


function cleanup() {
response.removeListener('data', ondata);
res.removeListener('drain', ondrain);

response.removeListener('end', onend);
response.removeListener('close', onclose);

response.removeListener('error', proxyError);
res.removeListener('error', proxyError);

response.removeListener('end', cleanup);
response.removeListener('close', cleanup);

res.removeListener('end', cleanup);
res.removeListener('close', cleanup);
}

response.on('end', cleanup);
response.on('close', cleanup);

res.on('end', cleanup);
res.on('close', cleanup);

});

//
Expand Down

0 comments on commit 9f92332

Please sign in to comment.