Permalink
Browse files

initial thing, seems to work

  • Loading branch information...
substack committed Oct 10, 2011
0 parents commit 0a8d54e5894955f212332c0b5892503c6838fb44
Showing with 113 additions and 0 deletions.
  1. +37 −0 README.markdown
  2. +9 −0 example/bounce.js
  3. +67 −0 index.js
@@ -0,0 +1,37 @@
+bouncy
+======
+
+Bouncy uses node's http parser innards to bounce http requests around to where
+they need to go.
+
+Use bouncy as a load balancer or http host router.
+
+example
+=======
+
+bounce.js
+---------
+
+Bounce requests to :8001 along to :8000...
+
+````javascript
+var bouncy = require('../');
+var net = require('net');
+
+bouncy(function (req, proxy) {
+ var stream = net.createConnection(8000);
+ proxy(stream);
+}).listen(8001);
+````
+
+install
+=======
+
+With [npm](http://npmjs.org), do:
+
+ npm install bouncy
+
+license
+=======
+
+MIT/X11
@@ -0,0 +1,9 @@
+// bounce requests to :8001 along to :8000
+
+var bouncy = require('../');
+var net = require('net');
+
+bouncy(function (req, proxy) {
+ var stream = net.createConnection(8000);
+ proxy(stream);
+}).listen(8001);
@@ -0,0 +1,67 @@
+var http = require('http');
+var parsers = http.parsers;
+
+var net = require('net');
+
+var bouncy = module.exports = function (cb) {
+ return net.createServer(handler.bind(null, cb));
+};
+
+var handler = bouncy.handler = function (cb, c) {
+ var parser = parsers.alloc();
+ parser.reinitialize('request');
+ parser.socket = c;
+ parser.incoming = null;
+
+ var request = null;
+ parser.onIncoming = function (req, shouldKeepAlive) {
+ request = req;
+ };
+
+ var buffers = [];
+ function respond (req, bytesInHeader) {
+ var bufs = buffers;
+ buffers = [];
+
+ req.pause();
+ cb(req, function (stream) {
+ var written = 0;
+ for (var i = 0; i < bufs.length; i++) {
+ var buf = bufs[i];
+ if (written + buf.length > bytesInHeader) {
+ stream.write(buf.slice(0, bytesInHeader - written));
+ break;
+ }
+ else {
+ stream.write(buf);
+ written += buf.length;
+ }
+ }
+ req.pipe(stream);
+ stream.pipe(c);
+ req.resume();
+ });
+ };
+
+ c.on('data', function (buf) {
+ buffers.push(buf);
+
+ var ret = parser.execute(buf, 0, buf.length);
+ if (ret instanceof Error) {
+ c.destroy();
+ }
+ else if (request) {
+ respond(request, ret);
+ request = null;
+ }
+ });
+
+ c.on('close', function () {
+ parsers.free(parser);
+ });
+
+ c.on('end', function () {
+ parser.finish();
+ c.destroy();
+ });
+};

0 comments on commit 0a8d54e

Please sign in to comment.