From 5d94ae27bc2d56d1f817b0cf1dfdb01dcc376393 Mon Sep 17 00:00:00 2001 From: indexzero Date: Sun, 1 Aug 2010 21:58:01 -0400 Subject: [PATCH] [api] More changes for createServer api --- README.md | 59 +++++++++++------- demo.js | 12 +--- lib/node-http-proxy.js | 114 +++++++++++++++++++++++------------ package.json | 2 +- test/node-http-proxy-test.js | 35 ++++------- 5 files changed, 129 insertions(+), 93 deletions(-) diff --git a/README.md b/README.md index 5eadca1b8..f98a21756 100644 --- a/README.md +++ b/README.md @@ -21,39 +21,56 @@ Let's suppose you were running multiple http application servers, but you only w ### Installing npm (node package manager) - - curl http://npmjs.org/install.sh | sh +
+  curl http://npmjs.org/install.sh | sh
+
### Installing node-http-proxy - - npm install http-proxy - +
+  npm install http-proxy
+
### How to use node-http-proxy +
+  var http = require('http'),
+      httpProxy = require('http-proxy');
 
-      var sys = require('sys'),
-          colors = require('colors'),
-          http = require('http'),
-          httpProxy = require('http-proxy').httpProxy;
-
-      http.createServer(function (req, res){
-        var proxy = new httpProxy;
-        proxy.init(req, res);
-        proxy.proxyRequest('localhost', '9000', req, res);
-      }).listen(8000);
+  httpProxy.createServer('localhost', '9000').listen(8000);
 
-      http.createServer(function (req, res){
-        res.writeHead(200, {'Content-Type': 'text/plain'});
-        res.write('request successfully proxied!' + '\n' + JSON.stringify(req.headers, true, 2));
-        res.end();
-      }).listen(9000);
+  http.createServer(function (req, res){
+    res.writeHead(200, {'Content-Type': 'text/plain'});
+    res.write('request successfully proxied!' + '\n' + JSON.stringify(req.headers, true, 2));
+    res.end();
+  }).listen(9000);
+
see the [demo](http://github.com/nodejitsu/node-http-proxy/blob/master/demo.js) for further examples. + +### How to use node-http-proxy with custom server logic +
+  var http = require('http'),
+      httpProxy = require('http-proxy');
+
+  httpProxy.createServer(function (req, res, proxy) {
+    //
+    // Put your custom server logic here
+    //
+    proxy.proxyRequest('localhost', '9000', req, res);
+  }).listen(8000);
+
+  http.createServer(function (req, res){
+    res.writeHead(200, {'Content-Type': 'text/plain'});
+    res.write('request successfully proxied!' + '\n' + JSON.stringify(req.headers, true, 2));
+    res.end();
+  }).listen(9000);
+
+ ### Why doesn't node-http-proxy have more advanced features like x, y, or z? -if you have a suggestion for a feature currently not supported, feel free to open a [support issue](http://github.com/nodejitsu/node-http-proxy/issues). node-http-proxy is designed to just proxy http requests from one server to another, but we will be soon releasing many other complimentary projects that can be used in conjunction with node-http-proxy +If you have a suggestion for a feature currently not supported, feel free to open a [support issue](http://github.com/nodejitsu/node-http-proxy/issues). node-http-proxy is designed to just proxy http requests from one server to another, but we will be soon releasing many other complimentary projects that can be used in conjunction with node-http-proxy.




+ ### License (The MIT License) diff --git a/demo.js b/demo.js index 3bc5d49fd..8b5297e76 100644 --- a/demo.js +++ b/demo.js @@ -27,7 +27,7 @@ var sys = require('sys'), colors = require('colors') http = require('http'), - httpProxy = require('http-proxy').httpProxy; + httpProxy = require('http-proxy').HttpProxy; // ascii art from http://github.com/marak/asciimo var welcome = '\ @@ -40,17 +40,11 @@ var welcome = '\ sys.puts(welcome.rainbow.bold); // create regular http proxy server -http.createServer(function (req, res){ - var proxy = new httpProxy; - proxy.init(req, res); - proxy.proxyRequest('localhost', '9000', req, res); -}).listen(8000); +httpProxy.createServer('localhost', '9000').listen(8000); sys.puts('http proxy server'.blue + ' started '.green.bold + 'on port '.blue + '8000'.yellow); // http proxy server with latency -http.createServer(function (req, res){ - var proxy = new (httpProxy); - proxy.init(req, res); +httpProxy.createServer(function (req, res, proxy){ setTimeout(function(){ proxy.proxyRequest('localhost', '9000', req, res); }, 200) diff --git a/lib/node-http-proxy.js b/lib/node-http-proxy.js index 444aadc85..640fee0d8 100644 --- a/lib/node-http-proxy.js +++ b/lib/node-http-proxy.js @@ -28,38 +28,90 @@ var sys = require('sys'), http = require('http'), events = require('events'); -exports.httpProxy = function () { +exports.HttpProxy = function () { this.emitter = new(events.EventEmitter); - // If we were passed more than two arguments, - // assume the first two are request and response. - if(arguments.length >= 2) { - this.init(arguments[0], arguments[1]); - } + this.events = {}; + this.listeners = {}; }; -exports.createServer = function(callback){ - sys.puts('httpProxy.createServer'); - this.listen = function(host, port){ - sys.puts(host + port); - }; - return this; +exports.createServer = function () { + // Initialize the nodeProxy to start proxying requests + var proxy = new (exports.HttpProxy); + return proxy.createServer(arguments); }; - -exports.httpProxy.prototype = { - init: function (req, res) { - this.events = []; +exports.HttpProxy.prototype = { + toArray: function (obj){ + var len = obj.length, + arr = new Array(len); + for (var i = 0; i < len; ++i) { + arr[i] = obj[i]; + } + return arr; + }, + + createServer: function () { + var args = Array.prototype.slice.call(arguments), + self = this, + server, + port, + callback; + + if (typeof(args[0]) === "function") { + callback = args[0]; + } + else { + server = args[0]; + port = args[1]; + } + + var proxyServer = http.createServer(function (req, res){ + self.watch(req, res); + + // If we were passed a callback to process the request + // or response in some way, then call it. + if(callback) { + callback(req, res, self); + } + else { + self.proxyRequest(server, port, req, res); + } + }); + + return proxyServer; + }, + + watch: function (req, res) { var self = this; - this.onData = function () { - self.events.push(['data'].concat(self.toArray(arguments))); - }; - this.onEnd = function () { - self.events.push(['end'].concat(self.toArray(arguments))); + this.events[req] = []; + + this.listeners[req] = { + onData: function () { + self.events[req].push(['data'].concat(self.toArray(arguments))); + }, + onEnd: function () { + self.events[req].push(['end'].concat(self.toArray(arguments))); + } }; - req.addListener('data', this.onData); - req.addListener('end', this.onEnd); + req.addListener('data', this.listeners[req].onData); + req.addListener('end', this.listeners[req].onEnd); + }, + + unwatch: function (req, res) { + req.removeListener('data', this.listeners[req].onData); + req.removeListener('end', this.listeners[req].onEnd); + + // Rebroadcast any events that have been buffered + while(this.events[req].length > 0) { + var args = this.events[req].shift(); + req.emit.apply(req, args); + } + + // Remove the data from the event and listeners hashes + delete this.listeners[req]; + delete this.events[req]; }, proxyRequest: function (server, port, req, res) { @@ -116,20 +168,6 @@ exports.httpProxy.prototype = { reverse_proxy.end(); }); - req.removeListener('data', this.onData); - req.removeListener('end', this.onEnd); - - // Rebroadcast any events that have been buffered - for (var i = 0, len = this.events.length; i < len; ++i) { - req.emit.apply(req, this.events[i]); - } - }, - toArray: function (obj){ - var len = obj.length, - arr = new Array(len); - for (var i = 0; i < len; ++i) { - arr[i] = obj[i]; - } - return arr; + this.unwatch(req, res); } }; diff --git a/package.json b/package.json index 892581a64..46c83d42a 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "http-proxy", "description": "A full-featured http reverse proxy for node.js", - "version": "0.1.3", + "version": "0.1.4", "author": "Charlie Robbins ", "contributors": [ { "name": "Marak Squires", "email": "marak.squires@gmail.com" } diff --git a/test/node-http-proxy-test.js b/test/node-http-proxy-test.js index 7c8ffb837..a7b0ff837 100644 --- a/test/node-http-proxy-test.js +++ b/test/node-http-proxy-test.js @@ -1,5 +1,5 @@ /* - node-http-proxy.js: http proxy for node.js + node-http-proxy-test.js: http proxy for node.js Copyright (c) 2010 Charlie Robbins & Marak Squires http://github.com/nodejitsu/node-http-proxy @@ -31,28 +31,14 @@ var vows = require('vows'), require.paths.unshift(require('path').join(__dirname, '../lib/')); -var httpProxy = require('node-http-proxy').httpProxy; +var HttpProxy = require('node-http-proxy').HttpProxy; var testServers = {}; -// -// Simple 'hello world' response for test purposes -// -var helloWorld = function(req, res) { - res.writeHead(200, {'Content-Type': 'text/plain'}); - res.write('hello world') - res.end(); -}; - // // Creates the reverse proxy server // var startProxyServer = function (server, port, proxy) { - var proxyServer = http.createServer(function (req, res){ - // Initialize the nodeProxy and start proxying the request - proxy.init(req, res); - proxy.proxyRequest(server, port, req, res); - }); - + var proxyServer = proxy.createServer(server, port); proxyServer.listen(8080); return proxyServer; }; @@ -61,9 +47,8 @@ var startProxyServer = function (server, port, proxy) { // Creates the reverse proxy server with a specified latency // var startLatentProxyServer = function (server, port, proxy, latency) { - var proxyServer = http.createServer(function (req, res){ - // Initialize the nodeProxy and start proxying the request - proxy.init(req, res); + // Initialize the nodeProxy and start proxying the request + var proxyServer = proxy.createServer(function (req, res, proxy) { setTimeout(function () { proxy.proxyRequest(server, port, req, res); }, latency); @@ -78,8 +63,10 @@ var startLatentProxyServer = function (server, port, proxy, latency) { // var startTargetServer = function (port) { var targetServer = http.createServer(function (req, res) { - helloWorld(req, res); - }) + res.writeHead(200, {'Content-Type': 'text/plain'}); + res.write('hello world') + res.end(); + }); targetServer.listen(port); return targetServer; @@ -107,7 +94,7 @@ vows.describe('node-proxy').addBatch({ "When an incoming request is proxied to the helloNode server" : { "with no latency" : { topic: function () { - var proxy = new httpProxy; + var proxy = new (HttpProxy); startTest(proxy, 8082); proxy.emitter.addListener('end', this.callback); @@ -124,7 +111,7 @@ vows.describe('node-proxy').addBatch({ }, "with latency": { topic: function () { - var proxy = new httpProxy; + var proxy = new (HttpProxy); startTestWithLatency(proxy, 8083); proxy.emitter.addListener('end', this.callback);