Commit 93505a42 authored by Marak Squires's avatar Marak Squires

merge

parents d0ad9317 15c18b61
...@@ -21,39 +21,77 @@ Let's suppose you were running multiple http application servers, but you only w ...@@ -21,39 +21,77 @@ Let's suppose you were running multiple http application servers, but you only w
### Installing npm (node package manager) ### Installing npm (node package manager)
<pre>
curl http://npmjs.org/install.sh | sh curl http://npmjs.org/install.sh | sh
</pre>
### Installing node-http-proxy ### Installing node-http-proxy
<pre>
npm install http-proxy
</pre>
npm install http-proxy ### How to setup a basic proxy server
<pre>
var http = require('http'),
httpProxy = require('http-proxy');
### How to use node-http-proxy httpProxy.createServer('9000', 'localhost').listen(8000);
var sys = require('sys'), http.createServer(function (req, res){
colors = require('colors'), res.writeHead(200, {'Content-Type': 'text/plain'});
http = require('http'), res.write('request successfully proxied!' + '\n' + JSON.stringify(req.headers, true, 2));
httpProxy = require('http-proxy').httpProxy; res.end();
}).listen(9000);
</pre>
http.createServer(function (req, res){ see the [demo](http://github.com/nodejitsu/node-http-proxy/blob/master/demo.js) for further examples.
var proxy = new httpProxy;
proxy.init(req, res);
proxy.proxyRequest('localhost', '9000', req, res);
}).listen(8000);
http.createServer(function (req, res){ ### How to setup a proxy server with custom server logic
res.writeHead(200, {'Content-Type': 'text/plain'}); <pre>
res.write('request successfully proxied!' + '\n' + JSON.stringify(req.headers, true, 2)); var http = require('http'),
res.end(); httpProxy = require('http-proxy');
}).listen(9000);
// create a proxy server with custom application logic
httpProxy.createServer(function (req, res, proxy) {
// Put your custom server logic here
proxy.proxyRequest('9000', 'localhost', req, res);
}).listen(8000);
http.createServer(function (req, res){
res.writeHead(200, {'Content-Type': 'text/plain'});
res.write('request successfully proxied: ' + req.url +'\n' + JSON.stringify(req.headers, true, 2));
res.end();
}).listen(9000);
</pre>
### How to proxy requests with a regular http server
<pre>
var http = require('http'),
httpProxy = require('http-proxy');
// create a regular http server and proxy its handler
http.createServer(function (req, res){
var proxy = new httpProxy.HttpProxy;
proxy.watch(req, res);
// Put your custom server logic here
proxy.proxyRequest(9000, 'localhost', req, res);
}).listen(8001);
http.createServer(function (req, res){
res.writeHead(200, {'Content-Type': 'text/plain'});
res.write('request successfully proxied: ' + req.url +'\n' + JSON.stringify(req.headers, true, 2));
res.end();
}).listen(9000);
</pre>
see the [demo](http://github.com/nodejitsu/node-http-proxy/blob/master/demo.js) for further examples.
### Why doesn't node-http-proxy have more advanced features like x, y, or z? ### 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.
<br/><br/><br/><br/><br/> <br/><br/><br/><br/><br/>
### License ### License
(The MIT License) (The MIT License)
......
...@@ -27,7 +27,7 @@ ...@@ -27,7 +27,7 @@
var sys = require('sys'), var sys = require('sys'),
colors = require('colors') colors = require('colors')
http = require('http'), http = require('http'),
httpProxy = require('http-proxy').httpProxy; httpProxy = require('./lib/node-http-proxy');
// ascii art from http://github.com/marak/asciimo // ascii art from http://github.com/marak/asciimo
var welcome = '\ var welcome = '\
...@@ -39,25 +39,31 @@ var welcome = '\ ...@@ -39,25 +39,31 @@ var welcome = '\
# # # # # # # # #### # # # \n'; # # # # # # # # #### # # # \n';
sys.puts(welcome.rainbow.bold); sys.puts(welcome.rainbow.bold);
// create regular http proxy server
http.createServer(function (req, res){ /****** basic http proxy server ******/
var proxy = new httpProxy; httpProxy.createServer(9000, 'localhost').listen(8000);
proxy.init(req, res);
proxy.proxyRequest('localhost', '9000', req, res);
}).listen(8000);
sys.puts('http proxy server'.blue + ' started '.green.bold + 'on port '.blue + '8000'.yellow); sys.puts('http proxy server'.blue + ' started '.green.bold + 'on port '.blue + '8000'.yellow);
// http proxy server with latency /****** http proxy server with latency******/
http.createServer(function (req, res){ httpProxy.createServer(function (req, res, proxy){
var proxy = new (httpProxy);
proxy.init(req, res);
setTimeout(function(){ setTimeout(function(){
proxy.proxyRequest('localhost', '9000', req, res); proxy.proxyRequest(9000, 'localhost', req, res);
}, 200) }, 200)
}).listen(8001); }).listen(8001);
sys.puts('http proxy server '.blue + 'started '.green.bold + 'on port '.blue + '8001 '.yellow + 'with latency'.magenta.underline ); sys.puts('http proxy server '.blue + 'started '.green.bold + 'on port '.blue + '8001 '.yellow + 'with latency'.magenta.underline );
// create regular http server /****** http server with proxyRequest handler and latency******/
http.createServer(function (req, res){
var proxy = new httpProxy.HttpProxy;
proxy.watch(req, res);
setTimeout(function(){
proxy.proxyRequest(9000, 'localhost', req, res);
}, 200);
}).listen(8002);
sys.puts('http server '.blue + 'started '.green.bold + 'on port '.blue + '8002 '.yellow + 'with proxyRequest handler'.cyan.underline + ' and latency'.magenta);
/****** regular http server ******/
http.createServer(function (req, res){ http.createServer(function (req, res){
res.writeHead(200, {'Content-Type': 'text/plain'}); res.writeHead(200, {'Content-Type': 'text/plain'});
res.write('request successfully proxied to: ' + req.url + '\n' + JSON.stringify(req.headers, true, 2)); res.write('request successfully proxied to: ' + req.url + '\n' + JSON.stringify(req.headers, true, 2));
......
...@@ -28,41 +28,92 @@ var sys = require('sys'), ...@@ -28,41 +28,92 @@ var sys = require('sys'),
http = require('http'), http = require('http'),
events = require('events'); events = require('events');
exports.httpProxy = function () { exports.HttpProxy = function () {
this.emitter = new(events.EventEmitter); this.emitter = new(events.EventEmitter);
// If we were passed more than two arguments, this.events = {};
// assume the first two are request and response. this.listeners = {};
if(arguments.length >= 2) {
this.init(arguments[0], arguments[1]);
}
}; };
exports.createServer = function(callback){ exports.createServer = function () {
sys.puts('httpProxy.createServer'); // Initialize the nodeProxy to start proxying requests
this.listen = function(host, port){ var proxy = new (exports.HttpProxy);
sys.puts(host + port); return proxy.createServer.apply(proxy, arguments);
};
return this;
}; };
exports.HttpProxy.prototype = {
exports.httpProxy.prototype = { toArray: function (obj){
init: function (req, res) { var len = obj.length,
this.events = []; arr = new Array(len);
for (var i = 0; i < len; ++i) {
arr[i] = obj[i];
}
return arr;
},
createServer: function () {
var self = this,
server,
port,
callback;
if (typeof(arguments[0]) === "function") {
callback = arguments[0];
}
else {
port = arguments[0];
server = arguments[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(port, server, req, res);
}
});
return proxyServer;
},
watch: function (req, res) {
var self = this; var self = this;
this.onData = function () { this.events[req] = [];
self.events.push(['data'].concat(self.toArray(arguments)));
}; this.listeners[req] = {
this.onEnd = function () { onData: function () {
self.events.push(['end'].concat(self.toArray(arguments))); 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('data', this.listeners[req].onData);
req.addListener('end', this.onEnd); 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) { proxyRequest: function (port, server, req, res) {
// Remark: nodeProxy.body exists solely for testability // Remark: nodeProxy.body exists solely for testability
this.body = ''; this.body = '';
var self = this; var self = this;
...@@ -116,20 +167,6 @@ exports.httpProxy.prototype = { ...@@ -116,20 +167,6 @@ exports.httpProxy.prototype = {
reverse_proxy.end(); reverse_proxy.end();
}); });
req.removeListener('data', this.onData); this.unwatch(req, res);
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;
} }
}; };
{ {
"name": "http-proxy", "name": "http-proxy",
"description": "A full-featured http reverse proxy for node.js", "description": "A full-featured http reverse proxy for node.js",
"version": "0.1.3", "version": "0.1.4",
"author": "Charlie Robbins <charlie.robbins@gmail.com>", "author": "Charlie Robbins <charlie.robbins@gmail.com>",
"contributors": [ "contributors": [
{ "name": "Marak Squires", "email": "marak.squires@gmail.com" } { "name": "Marak Squires", "email": "marak.squires@gmail.com" }
......
/* /*
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 Copyright (c) 2010 Charlie Robbins & Marak Squires http://github.com/nodejitsu/node-http-proxy
...@@ -31,28 +31,14 @@ var vows = require('vows'), ...@@ -31,28 +31,14 @@ var vows = require('vows'),
require.paths.unshift(require('path').join(__dirname, '../lib/')); require.paths.unshift(require('path').join(__dirname, '../lib/'));
var httpProxy = require('node-http-proxy').httpProxy; var httpProxy = require('node-http-proxy');
var testServers = {}; 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 // Creates the reverse proxy server
// //
var startProxyServer = function (server, port, proxy) { var startProxyServer = function (port, server, proxy) {
var proxyServer = http.createServer(function (req, res){ var proxyServer = proxy.createServer(port, server);
// Initialize the nodeProxy and start proxying the request
proxy.init(req, res);
proxy.proxyRequest(server, port, req, res);
});
proxyServer.listen(8080); proxyServer.listen(8080);
return proxyServer; return proxyServer;
}; };
...@@ -60,12 +46,11 @@ var startProxyServer = function (server, port, proxy) { ...@@ -60,12 +46,11 @@ var startProxyServer = function (server, port, proxy) {
// //
// Creates the reverse proxy server with a specified latency // Creates the reverse proxy server with a specified latency
// //
var startLatentProxyServer = function (server, port, proxy, latency) { var startLatentProxyServer = function (port, server, proxy, latency) {
var proxyServer = http.createServer(function (req, res){ // Initialize the nodeProxy and start proxying the request
// Initialize the nodeProxy and start proxying the request var proxyServer = proxy.createServer(function (req, res, proxy) {
proxy.init(req, res);
setTimeout(function () { setTimeout(function () {
proxy.proxyRequest(server, port, req, res); proxy.proxyRequest(port, server, req, res);
}, latency); }, latency);
}); });
...@@ -78,8 +63,10 @@ var startLatentProxyServer = function (server, port, proxy, latency) { ...@@ -78,8 +63,10 @@ var startLatentProxyServer = function (server, port, proxy, latency) {
// //
var startTargetServer = function (port) { var startTargetServer = function (port) {
var targetServer = http.createServer(function (req, res) { 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); targetServer.listen(port);
return targetServer; return targetServer;
...@@ -90,7 +77,7 @@ var startTargetServer = function (port) { ...@@ -90,7 +77,7 @@ var startTargetServer = function (port) {
// //
var startTest = function (proxy, port) { var startTest = function (proxy, port) {
testServers.noLatency = []; testServers.noLatency = [];
testServers.noLatency.push(startProxyServer('127.0.0.1', port, proxy)); testServers.noLatency.push(startProxyServer(port, 'localhost', proxy));
testServers.noLatency.push(startTargetServer(port)); testServers.noLatency.push(startTargetServer(port));
}; };
...@@ -99,44 +86,48 @@ var startTest = function (proxy, port) { ...@@ -99,44 +86,48 @@ var startTest = function (proxy, port) {
// //
var startTestWithLatency = function (proxy, port) { var startTestWithLatency = function (proxy, port) {
testServers.latency = []; testServers.latency = [];
testServers.latency.push(startLatentProxyServer('127.0.0.1', port, proxy, 2000)); testServers.latency.push(startLatentProxyServer(port, 'localhost', proxy, 2000));
testServers.latency.push(startTargetServer(port)); testServers.latency.push(startTargetServer(port));
}; };
vows.describe('node-proxy').addBatch({ vows.describe('node-http-proxy').addBatch({
"When an incoming request is proxied to the helloNode server" : { "A node-http-proxy": {
"with no latency" : { "when instantiated directly": {
topic: function () { "and an incoming request is proxied to the helloNode server" : {
var proxy = new httpProxy; "with no latency" : {
startTest(proxy, 8082); topic: function () {
proxy.emitter.addListener('end', this.callback); var proxy = new (httpProxy.HttpProxy);
startTest(proxy, 8082);
var client = http.createClient(8080, '127.0.0.1'); proxy.emitter.addListener('end', this.callback);
var request = client.request('GET', '/');
request.end(); var client = http.createClient(8080, 'localhost');
}, var request = client.request('GET', '/');
"it should received 'hello world'": function (err, body) { request.end();
assert.equal(body, 'hello world'); },
testServers.noLatency.forEach(function (server) { "it should received 'hello world'": function (err, body) {
server.close(); assert.equal(body, 'hello world');
}) testServers.noLatency.forEach(function (server) {
} server.close();
}, })
"with latency": { }
topic: function () { },
var proxy = new httpProxy; "with latency": {
startTestWithLatency(proxy, 8083); topic: function () {
proxy.emitter.addListener('end', this.callback); var proxy = new (httpProxy.HttpProxy);
startTestWithLatency(proxy, 8083);
var client = http.createClient(8081, '127.0.0.1'); proxy.emitter.addListener('end', this.callback);
var request = client.request('GET', '/');
request.end(); var client = http.createClient(8081, 'localhost');
}, var request = client.request('GET', '/');
"it should receive 'hello world'": function (err, body) { request.end();
assert.equal(body, 'hello world'); },
testServers.latency.forEach(function (server) { "it should receive 'hello world'": function (err, body) {
server.close(); assert.equal(body, 'hello world');
}) testServers.latency.forEach(function (server) {
server.close();
})
}
}
} }
} }
} }
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment