I want to forward an upstream http.IncomingMessage to a client via a restify server. This is what I came up till now. It provides the forwarding capability. However I assume that this could cause a memory leak:
var server = restify.createServer()
server.get('/test', function(req, res, next) {
var upstreamReq = createUpstreamReq() // just creates a http.ClientRequest
upstreamReq.on('response', function(upstreamRes) {
if (upstreamRes.statusCode === 404) {
// (1) I guess this leaks the upstreamRes body ?
return next(new restify.errors.NotFoundError())
}
if (upstreamRes.statusCode !== 200) {
// (2) is there a better way than pipeing the response to /dev/null?
// I guess the advantage of this approach is that we can reuse the connection (not closed) ?
upstreamRes.pipe(fs.createWriteStream('/dev/null'))
return next(new restify.errors.InternalServerError())
}
res.setHeader('Content-Type', upstreamRes.header('Content-Type'))
res.setHeader('Content-Length', upstreamRes.header('Content-Length'))
upstreamRes.pipe(res)
return next()
})
upstreamReq.end()
})
- I assume that in the case of a upstream
404
this code leaks theupstreamRes
body (1) because it is never consumed (nopipe(somewhere)
)? - One obvious solution (2) that shouldn't leak the
upstreamRes
body is to pipe it to/dev/null
. Is there an alternative/better solution for this problem?