I'm making an http proxy that tunnels data at the transport layer. Here is the complete code:
var http = require('http');
var net = require('net');
var url = require('url');
var proxy = http.createServer();
// proxy an HTTP request
proxy.on('request', function(req, res){
var uri = url.parse(req.url);
var httpMessage = req.method + ' ' + uri.path + ' HTTP/'+ req.httpVersion + '\r\n';
for(var header in req.headers){
httpMessage += header + ': ' + req.headers[header] + '\r\n';
}
httpMessage += '\r\n';
req.on('data', function(data){
httpMessage += data;
});
req.on('end', function(data){
httpMessage += data;
var client = net.connect(uri.port || 80, uri.hostname, function(){
client.write(httpMessage);
client.pipe(req.connection);
req.connection.pipe(client);
});
});
});
// proxy an HTTPS request
proxy.on('connect', function(req, socket, head) {
var uri = req.url.split(':')
var tunnel = net.connect({
port: uri[1],
host: uri[0]
}, function() {
socket.write('HTTP/1.1 200 Connection Established\r\n\r\n');
tunnel.write(head);
tunnel.pipe(socket);
socket.pipe(tunnel);
});
});
proxy.listen(8080);
My question has to do with http proxy section: I haven't run into this problem yet, but I can see that for potentially large HTTP bodies (such as file transfers), httpMessage may dramatically increase in size. What is the best way to pipe this data over the client tcp socket as it comes in, instead of caching the whole thing and sending all at once? Would be even better if I could just pipe all the parts of the HTTP message (request line, headers, body, ...) as they come into the server.
Thank for any help in advance.