Last active
August 29, 2015 14:15
-
-
Save thedude42/c1f04be51dea7156a8aa to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"use strict"; | |
var vsm = require('lrs/virtualServerModule'), | |
FIX_HEADER = true; | |
function ResponseAppender(vsname, appendString, fixContentLength) { | |
var self = this; | |
self.virtualServer = vsname; | |
self.appendString = appendString; | |
vsm.on('exist', self.virtualServer, function(vs) { | |
vs.on('request', function (servReq, servResp, cliReq) { | |
console.log("request received for: " + servReq.url); | |
// immediately send request to back end real-server | |
servReq.bindHeaders(cliReq); | |
servReq.fastPipe(cliReq); | |
var body = false, | |
total_length = 0; | |
cliReq.on('response', function(response) { | |
console.log("**HANDLING RESPONSE " + servReq.url + "**"); | |
// send along response headers un-touched | |
response.bindHeaders(servRes); | |
if ('Content-Length' in response.headers) { | |
body = [] | |
} | |
response.on('data', function(chunk) { | |
// get a chunk, send a chunk | |
if (body === false) { | |
servResp.write(chunk); | |
} | |
else { | |
// collect the chunks | |
body.push(chunk); | |
total_length += Buffer.byteLength(chunk); | |
} | |
console.log(" " + servReq.url + " got " + chunk.length + " bytes of response data"); | |
}); | |
response.on('error', function(err) { | |
console.log("#### " + servReq.url + " errored out: "+ err); | |
servRes.end(); | |
}); | |
response.on('end', function() { | |
console.log(" ## ENDING ##"); | |
// add our additional content | |
if (! body === false) { | |
if (fixContentLength) { | |
servResp.setHeader('Content-Length', total_length + self.appendString.length); | |
} | |
body = Buffer.concat(body, total_length); | |
body += self.appendString; | |
servResp.end(body); | |
} | |
else { | |
servResp.end(self.appendString); | |
} | |
}); | |
}); | |
}); | |
}); | |
} | |
exports.ResponseAppender = ResponseAppender; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment