我想通过 restify 服务器将上游 http.IncomingMessage 转发给客户端。这就是我到现在为止的想法。它提供转发能力。但是我认为这可能会导致内存泄漏:
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()
})
- 我假设在上游的情况下,
404
此代码会泄漏upstreamRes
主体(1),因为它从未被消耗(否pipe(somewhere)
)? - 一个不应该泄漏
upstreamRes
身体的明显解决方案(2)是将其通过管道输送到/dev/null
. 这个问题有替代/更好的解决方案吗?