diff --git a/.gitignore b/.gitignore
index 468b525c9..099c4d9df 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,3 +1,7 @@
-config.json
-node_modules/
-npm-debug.log
+node_modules
+*.swp
+cov
+atest.js
+notes
+primus-proxy.js
+tes.js
diff --git a/.travis.yml b/.travis.yml
index efd470846..ba5be4174 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -1,6 +1,5 @@
language: node_js
node_js:
- - 0.8
- "0.10"
- "0.11"
@@ -8,3 +7,6 @@ notifications:
email:
- travis@nodejitsu.com
irc: "irc.freenode.org#nodejitsu"
+
+script:
+ npm test
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 2205ee874..21d6bb03c 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,97 +1,4 @@
-## ChangeLog for: node-http-proxy
+### v 1.0.0-alpha
-## Version 0.10.0 - 3/18/2013
+- Complete refactor with new API
-- Breaking change: `proxyResponse` events are emitted on the `HttpProxy` or `RoutingProxy` instances as originally was intended in `0.9.x`.
-
-## Version 0.9.1 - 3/9/2013
-
-- Ensure that `webSocketProxyError` and `proxyError` both receive the error (indexzero).
-
-## Version 0.9.0 - 3/9/2013
-- Fix #276 Ensure response.headers.location is defined (indexzero)
-- Fix #248 Make options immutable in RoutingProxy (indexzero)
-- Fix #359 Do not modify the protocol in redirect request for external sites. (indexzero)
-- Fix #373 Do not use "Transfer-Encoding: chunked" header for proxied DELETE requests with no "Content-Length" header. (indexzero)
-- Fix #338 Set "content-length" header to "0" if it is not already set on DELETE requests. (indexzero)
-- Updates to README.md and Examples (ramitos, jamie-stackhouse, oost, indexzero)
-- Fixes to ProxyTable and Routing Proxy (adjohnson916, otavoijr)
-- New API for ProxyTable (mikkel, tglines)
-- Add `options.timeout` for specifying socket timeouts (pdoran)
-- Improve bin/node-http-proxy (niallo)
-- Don't emit `proxyError` twice (erasmospunk)
-- Fix memory leaks in WebSocket proxying
-- Support UNIX Sockets (yosefd)
-- Fix truncated chunked respones (jpetazzo)
-- Allow upstream listeners to get `proxyResponse` (colinmollenhour)
-
-## Version 0.8.1 - 6/5/2012
-- Fix re-emitting of events in RoutingProxy (coderarity)
-- New load balancer and middleware examples (marak)
-- Docs updated including changelog (lot of gently people)
-
-## Version 0.8.0 - 12/23/2011
-- Improve support and tests for url segment routing (maxogden)
-- Fix aborting connections when request close (c4milo)
-- Avoid 'Transfer-Encoding' on HTTP/1.0 clients (koichik).
-- Support for Node.js 0.6.x (mmalecki)
-
-## Version 0.7.3 - 10/4/2011
-- Fix setting x-forwarded headers (jesusabdullah)
-- Updated examples (AvianFlu)
-
-## Version 0.7.0 - 9/10/2011
-- Handles to every throw-able resume() call (isaacs)
-- Updated tests, README and package.json (indexzero)
-- Added HttpProxy.close() method (indexzero)
-
-## Version 0.6.6 - 8/31/2011
-- Add more examples (dominictarr)
-- Use of 'pkginfo' (indexzero)
-- Handle cases where res.write throws (isaacs)
-- Handles to every throw-able res.end call (isaacs)
-
-## Version 0.5.11 - 6/21/2011
-- Add more examples with WebSockets (indexzero)
-- Update the documentation (indexzero)
-
-## Version 0.5.7 - 5/19/2011
-- Fix to README related to markup and fix some examples (benatkin)
-- Improve WebSockets handling (indexzero)
-- Improve WebSockets tests (indexzero)
-- Improve https tests (olauzon)
-- Add devDependencies to package.json (olauzon)
-- Add 'proxyError' event (indexzero)
-- Add 'x-forwarded-{port|proto}' headers support (indexzero)
-- Keep-Alive connection supported (indexzero)
-
-## Version 0.5.0 - 4/15/2011
-- Remove winston in favor of custom events (indexzero)
-- Add x-forwarded-for Header (indexzero)
-- Fix WebSocket support (indexzero)
-- Add tests / examples for WebSocket support (indexzero)
-- Update .proxyRequest() and .proxyWebSocketRequest() APIs (indexzero)
-- Add HTTPS support (indexzero)
-- Add tests / examples for HTTPS support (indexzero)
-
-## Version 0.4.1 - 3/20/2011
-- Include missing dependency in package.json (indexzero)
-
-## Version 0.4.0 - 3/20/2011
-- Update for node.js 0.4.0 (indexzero)
-- Remove pool dependency in favor of http.Agent (indexzero)
-- Store buffered data using `.buffer()` instead of on the HttpProxy instance (indexzero)
-- Change the ProxyTable to be a lookup table instead of actively proxying (indexzero)
-- Allow for pure host-only matching in ProxyTable (indexzero)
-- Use winston for logging (indexzero)
-- Improve tests with async setup and more coverage (indexzero)
-- Improve code documentation (indexzero)
-
-### Version 0.3.1 - 11/22/2010
-- Added node-http-proxy binary script (indexzero)
-- Added experimental WebSocket support (indutny)
-- Added forward proxy functionality (indexzero)
-- Added proxy table for multiple target lookup (indexzero)
-- Simplified tests using helpers.js (indexzero)
-- Fixed uncaughtException bug with invalid proxy target (indutny)
-- Added configurable logging for HttpProxy and ProxyTable (indexzero)
\ No newline at end of file
diff --git a/LICENSE b/LICENSE
index db9b0b1ed..2bab4b9b1 100644
--- a/LICENSE
+++ b/LICENSE
@@ -1,7 +1,7 @@
node-http-proxy
- Copyright (c) 2010 Charlie Robbins, Mikeal Rogers, Fedor Indutny, & Marak Squires
+ Copyright (c) Nodejitsu 2013
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
diff --git a/README.md b/README.md
index 594d02ad1..4d68f3d5e 100644
--- a/README.md
+++ b/README.md
@@ -1,70 +1,80 @@
-# node-http-proxy [](http://travis-ci.org/nodejitsu/node-http-proxy)
+
+
+
-
+node-http-proxy
+=======
-## Battle-hardened node.js http proxy
+`node-http-proxy` is an HTTP programmable proxying library that supports
+websockets. It is suitable for implementing components such as
+proxies and load balancers.
-### Features
+### Build Status
-* Reverse proxies incoming http.ServerRequest streams
-* Can be used as a CommonJS module in node.js
-* Reverse or Forward Proxy based on simple JSON-based configuration
-* Supports [WebSockets][1]
-* Supports [HTTPS][2]
-* Minimal request overhead and latency
-* Full suite of functional tests
-* Battled-hardened through __production usage__ @ [nodejitsu.com][0]
-* Written entirely in Javascript
-* Easy to use API
+
+### Looking to Upgrade from 0.8.x ? Click [here](UPGRADING.md)
-node-http-proxy is `<= 0.8.x` compatible, if you're looking for a `>= 0.10` compatible version please check [caronte](https://github.com/nodejitsu/node-http-proxy/tree/caronte)
+### Core Concept
-### When to use node-http-proxy
+A new proxy is created by calling `createProxyServer` and passing
+an `options` object as argument ([valid properties are available here](lib/http-proxy.js#L26-L39))
-Let's suppose you were running multiple http application servers, but you only wanted to expose one machine to the internet. You could setup node-http-proxy on that one machine and then reverse-proxy the incoming http requests to locally running services which were not exposed to the outside network.
-
-### Installing npm (node package manager)
+```javascript
+var httpProxy = require('http-proxy');
-```
-curl https://npmjs.org/install.sh | sh
+var proxy = httpProxy.createProxyServer(options);
```
-### Installing node-http-proxy
+An object will be returned with four values:
-```
-npm install http-proxy
+* web `req, res, [options]` (used for proxying regular HTTP(S) requests)
+* ws `req, socket, head, [options]` (used for proxying WS(S) requests)
+* listen `port` (a function that wraps the object in a webserver, for your convenience)
+
+Is it then possible to proxy requests by calling these functions
+
+```javascript
+require('http').createServer(function(req, res) {
+ proxy.web(req, res, { target: 'http://mytarget.com:8080' });
+});
```
-## Using node-http-proxy
+Errors can be listened on either using the Event Emitter API
-There are several ways to use node-http-proxy; the library is designed to be flexible so that it can be used by itself, or in conjunction with other node.js libraries / tools:
+```javascript
+proxy.on('error', function(e) {
+ ...
+});
+```
-1. Standalone HTTP Proxy server
-2. Inside of another HTTP server (like Connect)
-3. In conjunction with a Proxy Routing Table
-4. As a forward-proxy with a reverse proxy
-5. From the command-line as a long running process
-6. customized with 3rd party middleware.
+or using the callback API
-In each of these scenarios node-http-proxy can handle any of these types of requests:
+```javascript
+proxy.web(req, res, { target: 'http://mytarget.com:8080' }, function(e) { ... });
+```
-1. HTTP Requests (http://)
-2. HTTPS Requests (https://)
-3. WebSocket Requests (ws://)
-4. Secure WebSocket Requests (wss://)
+When a request is proxied it follows two different pipelines ([available here](lib/http-proxy/passes))
+which apply transformations to both the `req` and `res` object.
+The first pipeline (ingoing) is responsible for the creation and manipulation of the stream that connects your client to the target.
+The second pipeline (outgoing) is responsible for the creation and manipulation of the stream that, from your target, returns data
+to the client.
-See the [examples][3] for more working sample code.
-### Setup a basic stand-alone proxy server
+#### Setup a basic stand-alone proxy server
-``` js
+```js
var http = require('http'),
httpProxy = require('http-proxy');
//
-// Create your proxy server
+// Create your proxy server and set the target in the options.
//
-httpProxy.createServer(9000, 'localhost').listen(8000);
+httpProxy.createProxyServer({target:'http://localhost:9000'}).listen(8000);
//
// Create your target server
@@ -76,571 +86,237 @@ http.createServer(function (req, res) {
}).listen(9000);
```
-### Setup a stand-alone proxy server with custom server logic
+#### Setup a stand-alone proxy server with custom server logic
+This example show how you can proxy a request using your own HTTP server
+and also you can put your own logic to handle the request.
-``` js
+```js
var http = require('http'),
httpProxy = require('http-proxy');
//
// Create a proxy server with custom application logic
//
-httpProxy.createServer(function (req, res, proxy) {
- //
- // Put your custom server logic here
- //
- proxy.proxyRequest(req, res, {
- host: 'localhost',
- port: 9000
- });
-}).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);
-```
-
-### Setup a stand-alone proxy server with latency (e.g. IO, etc)
-
-``` js
-var http = require('http'),
- httpProxy = require('http-proxy');
+var proxy = httpProxy.createProxyServer({});
//
-// Create a proxy server with custom application logic
+// Create your custom server and just call `proxy.web()` to proxy
+// a web request to the target passed in the options
+// also you can use `proxy.ws()` to proxy a websockets request
//
-httpProxy.createServer(function (req, res, proxy) {
- //
- // Buffer the request so that `data` and `end` events
- // are not lost during async operation(s).
- //
- var buffer = httpProxy.buffer(req);
-
- //
- // Wait for two seconds then respond: this simulates
- // performing async actions before proxying a request
- //
- setTimeout(function () {
- proxy.proxyRequest(req, res, {
- host: 'localhost',
- port: 9000,
- buffer: buffer
- });
- }, 2000);
-}).listen(8000);
+var server = require('http').createServer(function(req, res) {
+ // You can define here your custom logic to handle the request
+ // and then proxy the request.
+ proxy.web(req, res, { target: 'http://127.0.0.1:5060' });
+});
-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);
+console.log("listening on port 5050")
+server.listen(5050);
```
-### Proxy requests within another http server
+#### Setup a stand-alone proxy server with latency
-``` js
+```js
var http = require('http'),
httpProxy = require('http-proxy');
-
+
//
-// Create a new instance of HttProxy to use in your server
+// Create a proxy server with latency
//
-var proxy = new httpProxy.RoutingProxy();
+var proxy = httpProxy.createProxyServer();
//
-// Create a regular http server and proxy its handler
+// Create your server that make an operation that take a while
+// and then proxy de request
//
http.createServer(function (req, res) {
- //
- // Put your custom server logic here, then proxy
- //
- proxy.proxyRequest(req, res, {
- host: 'localhost',
- port: 9000
- });
-}).listen(8001);
+ // This simulate an operation that take 500ms in execute
+ setTimeout(function () {
+ proxy.web(req, res, {
+ target: 'http://localhost:9008'
+ });
+ }, 500);
+}).listen(8008);
+//
+// Create your target server
+//
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.write('request successfully proxied to: ' + req.url + '\n' + JSON.stringify(req.headers, true, 2));
res.end();
-}).listen(9000);
+}).listen(9008);
```
-### Proxy requests using a ProxyTable
-A Proxy Table is a simple lookup table that maps incoming requests to proxy target locations. Take a look at an example of the options you need to pass to httpProxy.createServer:
+#### Listening for proxy events
-``` js
-var options = {
- router: {
- 'foo.com/baz': '127.0.0.1:8001',
- 'foo.com/buz': '127.0.0.1:8002',
- 'bar.com/buz': '127.0.0.1:8003'
- }
-};
-```
-
-The above route table will take incoming requests to 'foo.com/baz' and forward them to '127.0.0.1:8001'. Likewise it will take incoming requests to 'foo.com/buz' and forward them to '127.0.0.1:8002'. The routes themselves are later converted to regular expressions to enable more complex matching functionality. We can create a proxy server with these options by using the following code:
-
-``` js
-var proxyServer = httpProxy.createServer(options);
-proxyServer.listen(80);
-```
-
-### Proxy requests using a 'Hostname Only' ProxyTable
-As mentioned in the previous section, all routes passes to the ProxyTable are by default converted to regular expressions that are evaluated at proxy-time. This is good for complex URL rewriting of proxy requests, but less efficient when one simply wants to do pure hostname routing based on the HTTP 'Host' header. If you are only concerned with hostname routing, you change the lookup used by the internal ProxyTable:
-
-``` js
-var options = {
- hostnameOnly: true,
- router: {
- 'foo.com': '127.0.0.1:8001',
- 'bar.com': '127.0.0.1:8002'
- }
-}
-```
-
-Notice here that I have not included paths on the individual domains because this is not possible when using only the HTTP 'Host' header. Care to learn more? See [RFC2616: HTTP/1.1, Section 14.23, "Host"][4].
-
-### Proxy requests using a 'Pathname Only' ProxyTable
-
-If you dont care about forwarding to different hosts, you can redirect based on the request path.
-
-``` js
-var options = {
- pathnameOnly: true,
- router: {
- '/wiki': '127.0.0.1:8001',
- '/blog': '127.0.0.1:8002',
- '/api': '127.0.0.1:8003'
- }
-}
-```
-
-This comes in handy if you are running separate services or applications on separate paths. Note, using this option disables routing by hostname entirely.
-
-
-### Proxy requests with an additional forward proxy
-Sometimes in addition to a reverse proxy, you may want your front-facing server to forward traffic to another location. For example, if you wanted to load test your staging environment. This is possible when using node-http-proxy using similar JSON-based configuration to a proxy table:
-
-``` js
-var proxyServerWithForwarding = httpProxy.createServer(9000, 'localhost', {
- forward: {
- port: 9000,
- host: 'staging.com'
- }
-});
-proxyServerWithForwarding.listen(80);
-```
-
-The forwarding option can be used in conjunction with the proxy table options by simply including both the 'forward' and 'router' properties in the options passed to 'createServer'.
+* `error`: The error event is emitted if the request to the target fail.
+* `proxyRes`: This event is emitted if the request to the target got a response.
-### Listening for proxy events
-Sometimes you want to listen to an event on a proxy. For example, you may want to listen to the 'end' event, which represents when the proxy has finished proxying a request.
-
-``` js
+```js
var httpProxy = require('http-proxy');
-
-var server = httpProxy.createServer(function (req, res, proxy) {
- var buffer = httpProxy.buffer(req);
-
- proxy.proxyRequest(req, res, {
- host: '127.0.0.1',
- port: 9000,
- buffer: buffer
- });
-});
-
-server.proxy.on('end', function () {
- console.log("The request was proxied.");
+// Error example
+//
+// Http Proxy Server with bad target
+//
+var proxy = httpProxy.createServer({
+ target:'http://localhost:9005'
});
-server.listen(8000);
-```
-
-It's important to remember not to listen for events on the proxy object in the function passed to `httpProxy.createServer`. Doing so would add a new listener on every request, which would end up being a disaster.
-
-## Using HTTPS
-You have all the full flexibility of node-http-proxy offers in HTTPS as well as HTTP. The two basic scenarios are: with a stand-alone proxy server or in conjunction with another HTTPS server.
+proxy.listen(8005);
-### Proxying to HTTP from HTTPS
-This is probably the most common use-case for proxying in conjunction with HTTPS. You have some front-facing HTTPS server, but all of your internal traffic is HTTP. In this way, you can reduce the number of servers to which your CA and other important security files are deployed and reduce the computational overhead from HTTPS traffic.
-
-Using HTTPS in `node-http-proxy` is relatively straight-forward:
-
-``` js
-var fs = require('fs'),
- http = require('http'),
- https = require('https'),
- httpProxy = require('http-proxy');
-
-var options = {
- https: {
- key: fs.readFileSync('path/to/your/key.pem', 'utf8'),
- cert: fs.readFileSync('path/to/your/cert.pem', 'utf8')
- }
-};
-
-//
-// Create a standalone HTTPS proxy server
//
-httpProxy.createServer(8000, 'localhost', options).listen(8001);
+// Listen for the `error` event on `proxy`.
+proxy.on('error', function (err, req, res) {
+ res.writeHead(500, {
+ 'Content-Type': 'text/plain'
+ });
+
+ res.end('Something went wrong. And we are reporting a custom error message.');
+});
//
-// Create an instance of HttpProxy to use with another HTTPS server
+// Listen for the `proxyRes` event on `proxy`.
//
-var proxy = new httpProxy.HttpProxy({
- target: {
- host: 'localhost',
- port: 8000
- }
+proxy.on('proxyRes', function (res) {
+ console.log('RAW Response from the target', JSON.stringify(res.headers, true, 2));
});
-https.createServer(options.https, function (req, res) {
- proxy.proxyRequest(req, res)
-}).listen(8002);
-//
-// Create the target HTTPS server for both cases
-//
-http.createServer(function (req, res) {
- res.writeHead(200, { 'Content-Type': 'text/plain' });
- res.write('hello https\n');
- res.end();
-}).listen(8000);
```
-### Using two certificates
-
-Suppose that your reverse proxy will handle HTTPS traffic for two different domains `fobar.com` and `barbaz.com`.
-If you need to use two different certificates you can take advantage of [Server Name Indication](http://en.wikipedia.org/wiki/Server_Name_Indication).
+#### Using HTTPS
+You can activate the validation of a secure SSL certificate to the target connection (avoid self signed certs), just set `secure: true` in the options.
-``` js
-var https = require('https'),
- path = require("path"),
- fs = require("fs"),
- crypto = require("crypto");
-
-//
-// generic function to load the credentials context from disk
-//
-function getCredentialsContext (cer) {
- return crypto.createCredentials({
- key: fs.readFileSync(path.join(__dirname, 'certs', cer + '.key')),
- cert: fs.readFileSync(path.join(__dirname, 'certs', cer + '.crt'))
- }).context;
-}
-
-//
-// A certificate per domain hash
-//
-var certs = {
- "fobar.com": getCredentialsContext("foobar"),
- "barbaz.com": getCredentialsContext("barbaz")
-};
+##### HTTPS -> HTTP
+```js
//
-// Proxy options
-//
-// This section assumes that myCert, myKey and myCa are defined (they are not
-// in this example). With a SNICallback, the proxy needs a default set of
-// certificates to use.
+// Create the HTTPS proxy server in front of a HTTP server
//
-var options = {
- https: {
- SNICallback: function (hostname) {
- return certs[hostname];
- },
- cert: myCert,
- key: myKey,
- ca: [myCa]
+httpProxy.createServer({
+ target: {
+ host: 'localhost',
+ port: 9009
},
- hostnameOnly: true,
- router: {
- 'fobar.com': '127.0.0.1:8001',
- 'barbaz.com': '127.0.0.1:8002'
+ ssl: {
+ key: fs.readFileSync('valid-ssl-key.pem'), 'utf8'),
+ cert: fs.readFileSync('valid-ssl-cert.pem'), 'utf8')
}
-};
-
-//
-// Create a standalone HTTPS proxy server
-//
-httpProxy.createServer(options).listen(8001);
-
-//
-// Create the target HTTPS server
-//
-http.createServer(function (req, res) {
- res.writeHead(200, { 'Content-Type': 'text/plain' });
- res.write('hello https\n');
- res.end();
-}).listen(8000);
-
+}).listen(8009);
```
-### Proxying to HTTPS from HTTPS
-Proxying from HTTPS to HTTPS is essentially the same as proxying from HTTPS to HTTP, but you must include the `target` option in when calling `httpProxy.createServer` or instantiating a new instance of `HttpProxy`.
-
-``` js
-var fs = require('fs'),
- https = require('https'),
- httpProxy = require('http-proxy');
-
-var options = {
- https: {
- key: fs.readFileSync('path/to/your/key.pem', 'utf8'),
- cert: fs.readFileSync('path/to/your/cert.pem', 'utf8')
- },
- target: {
- https: true // This could also be an Object with key and cert properties
- }
-};
-
-//
-// Create a standalone HTTPS proxy server
-//
-httpProxy.createServer(8000, 'localhost', options).listen(8001);
+##### HTTPS -> HTTPS
+```js
//
-// Create an instance of HttpProxy to use with another HTTPS server
+// Create the proxy server listening on port 443
//
-var proxy = new httpProxy.HttpProxy({
- target: {
- host: 'localhost',
- port: 8000,
- https: true
- }
-});
+httpProxy.createServer({
+ ssl: {
+ key: fs.readFileSync('valid-ssl-key.pem'), 'utf8'),
+ cert: fs.readFileSync('valid-ssl-cert.pem'), 'utf8')
+ },
+ target: 'https://localhost:9010',
+ secure: true // Depends on your needs, could be false.
+}).listen(443);
+```
-https.createServer(options.https, function (req, res) {
- proxy.proxyRequest(req, res);
-}).listen(8002);
+#### Proxying WebSockets
+You can activate the websocket support for the proxy using `ws:true` in the options.
+```js
//
-// Create the target HTTPS server for both cases
+// Create a proxy server for websockets
//
-https.createServer(options.https, function (req, res) {
- res.writeHead(200, { 'Content-Type': 'text/plain' });
- res.write('hello https\n');
- res.end();
-}).listen(8000);
+httpProxy.createServer({
+ target: 'ws://localhost:9014',
+ ws: true
+}).listen(8014);
```
-## Middleware
-`node-http-proxy` now supports connect middleware. Add middleware functions to your createServer call:
-
-``` js
-httpProxy.createServer(
- require('connect-gzip').gzip(),
- 9000, 'localhost'
-).listen(8000);
-```
-
-A regular request we receive is to support the modification of html/xml content that is returned in the response from an upstream server.
-
-[Harmon](https://github.com/No9/harmon/) is a stream based middleware plugin that is designed to solve that problem in the most effective way possible.
-
-If you would like to handle errors passed to `next()` then attach a listener to the proxy:
-
- server = httpProxy.createServer(
- myMiddleWare,
- 9000, 'localhost'
- ).listen(8000);
-
- server.proxy.on('middlewareError', function (err, req, res) {
- // handle the error here and call res.end()
- });
-
-## Proxying WebSockets
-Websockets are handled automatically when using `httpProxy.createServer()`, however, if you supply a callback inside the createServer call, you will need to handle the 'upgrade' proxy event yourself. Here's how:
+Also you can proxy the websocket requests just calling the `ws(req, socket, head)` method.
```js
-
-var options = {
- ....
-};
-
-var server = httpProxy.createServer(
- callback/middleware,
- options
-);
-
-server.listen(port, function () { ... });
-server.on('upgrade', function (req, socket, head) {
- server.proxy.proxyWebSocketRequest(req, socket, head);
-});
-```
-
-If you would rather not use createServer call, and create the server that proxies yourself, see below:
-
-``` js
-var http = require('http'),
- httpProxy = require('http-proxy');
-
//
-// Create an instance of node-http-proxy
+// Setup our server to proxy standard HTTP requests
//
-var proxy = new httpProxy.HttpProxy({
+var proxy = new httpProxy.createProxyServer({
target: {
host: 'localhost',
- port: 8000
+ port: 9015
}
});
-
-var server = http.createServer(function (req, res) {
- //
- // Proxy normal HTTP requests
- //
- proxy.proxyRequest(req, res);
+var proxyServer = http.createServer(function (req, res) {
+ proxy.web(req, res);
});
-server.on('upgrade', function (req, socket, head) {
- //
- // Proxy websocket requests too
- //
- proxy.proxyWebSocketRequest(req, socket, head);
+//
+// Listen to the `upgrade` event and proxy the
+// WebSocket requests as well.
+//
+proxyServer.on('upgrade', function (req, socket, head) {
+ proxy.ws(req, socket, head);
});
-server.listen(8080);
+proxyServer.listen(8015);
```
-### with custom server logic
+### Contributing and Issues
-``` js
-var httpProxy = require('http-proxy')
+* Search on Google/Github
+* If you can't find anything, open an issue
+* If you feel comfortable about fixing the issue, fork the repo
+* Commit to your local branch (which must be different from `master`)
+* Submit your Pull Request (be sure to include tests and update documentation)
-var server = httpProxy.createServer(function (req, res, proxy) {
- //
- // Put your custom server logic here
- //
- proxy.proxyRequest(req, res, {
- host: 'localhost',
- port: 9000
- });
-})
+### Options
-server.on('upgrade', function (req, socket, head) {
- //
- // Put your custom server logic here
- //
- server.proxy.proxyWebSocketRequest(req, socket, head, {
- host: 'localhost',
- port: 9000
- });
-});
-
-server.listen(8080);
-```
-
-### Configuring your Socket limits
-
-By default, `node-http-proxy` will set a 100 socket limit for all `host:port` proxy targets. You can change this in two ways:
+`httpProxy.createProxyServer` supports the following options:
-1. By passing the `maxSockets` option to `httpProxy.createServer()`
-2. By calling `httpProxy.setMaxSockets(n)`, where `n` is the number of sockets you with to use.
+ * **target**: url string to be parsed with the url module
+ * **forward**: url string to be parsed with the url module
+ * **agent**: object to be passed to http(s).request (see Node's [https agent](http://nodejs.org/api/https.html#https_class_https_agent) and [http agent](http://nodejs.org/api/http.html#http_class_http_agent) objects)
+ * **secure**: true/false, if you want to verify the SSL Certs
-## POST requests and buffering
+If you are using the `proxyServer.listen` method, the following options are also applicable:
-express.bodyParser will interfere with proxying of POST requests (and other methods that have a request
-body). With bodyParser active, proxied requests will never send anything to the upstream server, and
-the original client will just hang. See https://github.com/nodejitsu/node-http-proxy/issues/180 for options.
+ * **ssl**: object to be passed to https.createServer()
+ * **ws**: true/false, if you want to proxy websockets
+ * **xfwd**: true/false, adds x-forward headers
-## Using node-http-proxy from the command line
-When you install this package with npm, a node-http-proxy binary will become available to you. Using this binary is easy with some simple options:
-``` js
-usage: node-http-proxy [options]
+### Test
-All options should be set with the syntax --option=value
-
-options:
- --port PORT Port that the proxy server should run on
- --target HOST:PORT Location of the server the proxy will target
- --config OUTFILE Location of the configuration file for the proxy server
- --silent Silence the log output from the proxy server
- -h, --help You're staring at it
```
-
-
-## 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][6]. 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.
-
-## Options
-
-### Http Proxy
-
-`createServer()` supports the following options
-
-```javascript
-{
- forward: { // options for forward-proxy
- port: 8000,
- host: 'staging.com'
- },
- target : { // options for proxy target
- port : 8000,
- host : 'localhost',
- };
- source : { // additional options for websocket proxying
- host : 'localhost',
- port : 8000,
- https: true
- },
- enable : {
- xforward: true // enables X-Forwarded-For
- },
- changeOrigin: false, // changes the origin of the host header to the target URL
- timeout: 120000 // override the default 2 minute http socket timeout value in milliseconds
-}
+$ npm test
```
-## Run Tests
-The test suite is designed to fully cover the combinatoric possibilities of HTTP and HTTPS proxying:
+### Logo
-1. HTTP --> HTTP
-2. HTTPS --> HTTP
-3. HTTPS --> HTTPS
-4. HTTP --> HTTPS
+Logo created by [Diego Pasquali](http://dribbble.com/diegopq)
-```
-vows test/*-test.js --spec
-vows test/*-test.js --spec --https
-vows test/*-test.js --spec --https --target=https
-vows test/*-test.js --spec --target=https
-```
-
-
### License
-(The MIT License)
-
-Copyright (c) 2010 Charlie Robbins, Mikeal Rogers, Fedor Indutny, & Marak Squires
-
-Permission is hereby granted, free of charge, to any person obtaining
-a copy of this software and associated documentation files (the
-"Software"), to deal in the Software without restriction, including
-without limitation the rights to use, copy, modify, merge, publish,
-distribute, sublicense, and/or sell copies of the Software, and to
-permit persons to whom the Software is furnished to do so, subject to
-the following conditions:
-
-The above copyright notice and this permission notice shall be
-included in all copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
-LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
-OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
-WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-[0]: http://nodejitsu.com
-[1]: https://github.com/nodejitsu/node-http-proxy/blob/master/examples/websocket/websocket-proxy.js
-[2]: https://github.com/nodejitsu/node-http-proxy/blob/master/examples/http/proxy-https-to-http.js
-[3]: https://github.com/nodejitsu/node-http-proxy/tree/master/examples
-[4]: http://www.ietf.org/rfc/rfc2616.txt
-[5]: http://socket.io
-[6]: http://github.com/nodejitsu/node-http-proxy/issues
+>The MIT License (MIT)
+>
+>Copyright (c) 2010 - 2013 Nodejitsu Inc.
+>
+>Permission is hereby granted, free of charge, to any person obtaining a copy
+>of this software and associated documentation files (the "Software"), to deal
+>in the Software without restriction, including without limitation the rights
+>to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+>copies of the Software, and to permit persons to whom the Software is
+>furnished to do so, subject to the following conditions:
+>
+>The above copyright notice and this permission notice shall be included in
+>all copies or substantial portions of the Software.
+>
+>THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+>IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+>FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+>AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+>LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+>OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+>THE SOFTWARE.
+
+
diff --git a/UPGRADING.md b/UPGRADING.md
new file mode 100644
index 000000000..8c0db431c
--- /dev/null
+++ b/UPGRADING.md
@@ -0,0 +1,96 @@
+Looking to upgrade from `http-proxy@0.x.x` to `http-proxy@1.0`? You've come to the right place!
+`http-proxy@1.0` is a from-scratch implementation of `http-proxy` and, as such
+brings some breaking changes to APIs.
+
+## Server creation
+
+Available through `.createServer()` or `.createProxyServer()`.
+
+```javascript
+httpProxy.createServer({
+ target:'http://localhost:9003'
+}).listen(8003);
+```
+
+Check the [README.md](https://github.com/nodejitsu/node-http-proxy/blob/caronte/README.md) for a more detailed explanation of the parameters.
+
+## Proxying
+
+Web proying is done by calling the `.web()` method on a Proxy instance. You can check among some use cases in the [examples folder](https://github.com/nodejitsu/node-http-proxy/tree/caronte/examples/http)
+
+```javascript
+//
+// Create a HTTP Proxy server with a HTTPS target
+//
+httpProxy.createProxyServer({
+ target: 'https://google.com',
+ agent : https.globalAgent,
+ headers: {
+ host: 'google.com'
+ }
+}).listen(8011);
+
+```
+
+Websockets are proxied by the `.ws()` method. The [examples folder](https://github.com/nodejitsu/node-http-proxy/tree/caronte/examples/websocket) again provides a lot of useful snippets!
+
+```javascript
+var proxy = new httpProxy.createProxyServer({
+ target: {
+ host: 'localhost',
+ port: 9015
+ }
+});
+var proxyServer = http.createServer(function (req, res) {
+ proxy.web(req, res);
+});
+
+//
+// Listen to the `upgrade` event and proxy the
+// WebSocket requests as well.
+//
+proxyServer.on('upgrade', function (req, socket, head) {
+ proxy.ws(req, socket, head);
+});
+```
+
+## Error Handling
+
+It is possible to listen globally on the `error` event on the server. In alternative, a
+callback passed to `.web()` or `.ws()` as last parameter is also accepted.
+
+```javascript
+var proxy = httpProxy.createServer({
+ target:'http://localhost:9005'
+});
+
+//
+// Tell the proxy to listen on port 8000
+//
+proxy.listen(8005);
+
+//
+// Listen for the `error` event on `proxy`.
+proxy.on('error', function (err, req, res) {
+ res.writeHead(500, {
+ 'Content-Type': 'text/plain'
+ });
+
+ res.end('Something went wrong. And we are reporting a custom error message.');
+});
+```
+
+## Dropped
+
+Since the API was rewritten to be extremely flexible we decided to drop some features
+which were in the core and delegate them to eventual "userland" modules.
+
+- Middleware API
+- ProxyTable API
+
+### Middleware API
+
+The new API makes it really easy to implement code that behaves like the old Middleware API. You can check some examples [here](https://github.com/nodejitsu/node-http-proxy/tree/caronte/examples/middleware)
+
+
+
diff --git a/benchmark/README.md b/benchmark/README.md
new file mode 100644
index 000000000..2a852d14e
--- /dev/null
+++ b/benchmark/README.md
@@ -0,0 +1,33 @@
+# Benchmarking `node-http-proxy`
+
+The long-term goal of these scripts and documentation is to provide a consistent and well understood benchmarking process for `node-http-proxy` so that performance does not degrade over time. They were initially created to compare the performance of `v0.10.3` and `v1.0.0` (which was a significant rewrite).
+
+## Pre-requisites
+
+All benchmarking shall be done with [wrk](https://github.com/wg/wrk) which _is the same tool used for performance testing by the node.js core team._ **Make sure you have `wrk` installed before continuing**.
+
+```
+$ wrk
+Usage: wrk
+ Options:
+ -c, --connections Connections to keep open
+ -r, --requests Total requests to make
+ -t, --threads Number of threads to use
+
+ -H, --header Add header to request
+ -v, --version Print version details
+
+ Numeric arguments may include a SI unit (2k, 2M, 2G)
+```
+
+## Benchmarks
+
+1. [Simple HTTP benchmark](#simple-http)
+
+### Simple HTTP
+
+_This benchmark requires three terminals running:_
+
+1. **A proxy server:** `node benchmark/scripts/proxy.js`
+2. **A target server:** `node benchmark/scripts/hello.js`
+3. **A wrk process:** `wrk -c 20 -r 10000 -t 2 http://127.0.0.1:8000`
\ No newline at end of file
diff --git a/benchmark/scripts/hello.js b/benchmark/scripts/hello.js
new file mode 100644
index 000000000..be09b6388
--- /dev/null
+++ b/benchmark/scripts/hello.js
@@ -0,0 +1,3 @@
+require('http').createServer(function(req, res) {
+ res.end('Hello world!');
+}).listen(9000);
\ No newline at end of file
diff --git a/benchmark/scripts/proxy.js b/benchmark/scripts/proxy.js
new file mode 100644
index 000000000..a70c55817
--- /dev/null
+++ b/benchmark/scripts/proxy.js
@@ -0,0 +1,6 @@
+var http = require('http'),
+ httpProxy = require('../../');
+//
+// Create your proxy server
+//
+httpProxy.createProxyServer({ target: 'http://localhost:9000' }).listen(8000);
\ No newline at end of file
diff --git a/benchmark/websockets-throughput.js b/benchmark/scripts/websockets-throughput.js
similarity index 98%
rename from benchmark/websockets-throughput.js
rename to benchmark/scripts/websockets-throughput.js
index 6787385ad..866e42461 100644
--- a/benchmark/websockets-throughput.js
+++ b/benchmark/scripts/websockets-throughput.js
@@ -1,7 +1,7 @@
var crypto = require('crypto'),
WebSocket = require('ws'),
async = require('async'),
- httpProxy = require('../');
+ httpProxy = require('../../');
var SERVER_PORT = 8415,
PROXY_PORT = 8514;
diff --git a/bin/node-http-proxy b/bin/node-http-proxy
deleted file mode 100755
index 07d199ca6..000000000
--- a/bin/node-http-proxy
+++ /dev/null
@@ -1,113 +0,0 @@
-#!/usr/bin/env node
-
-var path = require('path'),
- fs = require('fs'),
- util = require('util'),
- argv = require('optimist').argv,
- httpProxy = require('../lib/node-http-proxy');
-
-var help = [
- "usage: node-http-proxy [options] ",
- "",
- "Starts a node-http-proxy server using the specified command-line options",
- "",
- "options:",
- " --port PORT Port that the proxy server should run on",
- " --host HOST Host that the proxy server should run on",
- " --target HOST:PORT Location of the server the proxy will target",
- " --config OUTFILE Location of the configuration file for the proxy server",
- " --silent Silence the log output from the proxy server",
- " --user USER User to drop privileges to once server socket is bound",
- " -h, --help You're staring at it"
-].join('\n');
-
-if (argv.h || argv.help || Object.keys(argv).length === 2) {
- return util.puts(help);
-}
-
-var location, config = {},
- port = argv.port || 80,
- host = argv.host || undefined,
- target = argv.target;
- user = argv.user;
-
-//
-// If we were passed a config, parse it
-//
-if (argv.config) {
- try {
- var data = fs.readFileSync(argv.config);
- config = JSON.parse(data.toString());
- } catch (ex) {
- util.puts('Error starting node-http-proxy: ' + ex);
- process.exit(1);
- }
-}
-
-//
-// If `config.https` is set, then load the required file contents into the config options.
-//
-if (config.https) {
- Object.keys(config.https).forEach(function (key) {
- // If CA certs are specified, load those too.
- if (key === "ca") {
- for (var i=0; i < config.https.ca.length; i++) {
- if (config.https.ca === undefined) {
- config.https.ca = [];
- }
- config.https.ca[i] = fs.readFileSync(config.https[key][i], 'utf8');
- }
- } else {
- config.https[key] = fs.readFileSync(config.https[key], 'utf8');
- }
- });
-}
-
-//
-// Check to see if we should silence the logs
-//
-config.silent = typeof argv.silent !== 'undefined' ? argv.silent : config.silent;
-
-//
-// If we were passed a target, parse the url string
-//
-if (typeof target === 'string') location = target.split(':');
-
-//
-// Create the server with the specified options
-//
-var server;
-if (location) {
- var targetPort = location.length === 1 ? 80 : parseInt(location[1]);
- server = httpProxy.createServer(targetPort, location[0], config);
-}
-else if (config.router) {
- server = httpProxy.createServer(config);
-}
-else {
- return util.puts(help);
-}
-
-//
-// Start the server
-//
-if (host) {
- server.listen(port, host);
-} else {
- server.listen(port);
-}
-
-
-//
-// Drop privileges if requested
-//
-if (typeof user === 'string') {
- process.setuid(user);
-}
-
-//
-// Notify that the server is started
-//
-if (!config.silent) {
- util.puts('node-http-proxy server now listening on port: ' + port);
-}
diff --git a/config.sample.json b/config.sample.json
deleted file mode 100644
index 8f15f882b..000000000
--- a/config.sample.json
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "silent": false,
- "router": {
- "localhost": "localhost:9000"
- },
- "forward": {
- "port": 9001,
- "host": "localhost"
- }
-}
\ No newline at end of file
diff --git a/doc/logo.png b/doc/logo.png
new file mode 100644
index 000000000..a36bdcf2a
Binary files /dev/null and b/doc/logo.png differ
diff --git a/examples/balancer/simple-balancer-with-websockets.js b/examples/balancer/simple-balancer-with-websockets.js
index 04564cef2..cc13f4b5c 100644
--- a/examples/balancer/simple-balancer-with-websockets.js
+++ b/examples/balancer/simple-balancer-with-websockets.js
@@ -1,5 +1,31 @@
+/*
+ simple-balancer.js: Example of a simple round robin balancer for websockets
+
+ Copyright (c) Nodejitsu 2013
+
+ Permission is hereby granted, free of charge, to any person obtaining
+ a copy of this software and associated documentation files (the
+ "Software"), to deal in the Software without restriction, including
+ without limitation the rights to use, copy, modify, merge, publish,
+ distribute, sublicense, and/or sell copies of the Software, and to
+ permit persons to whom the Software is furnished to do so, subject to
+ the following conditions:
+
+ The above copyright notice and this permission notice shall be
+ included in all copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+ LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+
+*/
+
var http = require('http'),
- httpProxy = require('../../lib/node-http-proxy');
+ httpProxy = require('../../lib/http-proxy');
//
// A simple round-robin load balancing strategy.
@@ -22,7 +48,7 @@ var addresses = [
//
var proxies = addresses.map(function (target) {
- return new httpProxy.HttpProxy({
+ return new httpProxy.createProxyServer({
target: target
});
});
@@ -43,7 +69,7 @@ function nextProxy() {
//
var server = http.createServer(function (req, res) {
- nextProxy().proxyRequest(req, res);
+ nextProxy().web(req, res);
});
//
@@ -51,8 +77,8 @@ var server = http.createServer(function (req, res) {
//
server.on('upgrade', function (req, socket, head) {
- nextProxy().proxyWebSocketRequest(req, socket, head);
+ nextProxy().ws(req, socket, head);
});
-server.listen(8080);
+server.listen(8001);
\ No newline at end of file
diff --git a/examples/balancer/simple-balancer.js b/examples/balancer/simple-balancer.js
index f1fa0c06b..3f53cc63d 100644
--- a/examples/balancer/simple-balancer.js
+++ b/examples/balancer/simple-balancer.js
@@ -1,4 +1,31 @@
-var httpProxy = require('../../lib/node-http-proxy');
+/*
+ simple-balancer.js: Example of a simple round robin balancer
+
+ Copyright (c) Nodejitsu 2013
+
+ Permission is hereby granted, free of charge, to any person obtaining
+ a copy of this software and associated documentation files (the
+ "Software"), to deal in the Software without restriction, including
+ without limitation the rights to use, copy, modify, merge, publish,
+ distribute, sublicense, and/or sell copies of the Software, and to
+ permit persons to whom the Software is furnished to do so, subject to
+ the following conditions:
+
+ The above copyright notice and this permission notice shall be
+ included in all copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+ LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+
+*/
+
+var http = require('http'),
+ httpProxy = require('../../lib/http-proxy');
//
// A simple round-robin load balancing strategy.
//
@@ -14,23 +41,24 @@ var addresses = [
port: 80
}
];
+var proxy = httpProxy.createServer();
-httpProxy.createServer(function (req, res, proxy) {
+http.createServer(function (req, res) {
//
// On each request, get the first location from the list...
//
- var target = addresses.shift();
+ var target = { target: addresses.shift() };
//
// ...then proxy to the server whose 'turn' it is...
//
console.log('balancing request to: ', target);
- proxy.proxyRequest(req, res, target);
+ proxy.web(req, res, target);
//
// ...and then the server you just used becomes the last item in the list.
//
addresses.push(target);
-}).listen(8000);
+}).listen(8021);
// Rinse; repeat; enjoy.
\ No newline at end of file
diff --git a/examples/http/basic-proxy.js b/examples/http/basic-proxy.js
index b890e69a0..e9be0d79b 100644
--- a/examples/http/basic-proxy.js
+++ b/examples/http/basic-proxy.js
@@ -1,7 +1,7 @@
/*
basic-proxy.js: Basic example of proxying over HTTP
- Copyright (c) 2010 Charlie Robbins, Mikeal Rogers, Fedor Indutny, & Marak Squires.
+ Copyright (c) Nodejitsu 2013
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
@@ -27,7 +27,7 @@
var util = require('util'),
colors = require('colors'),
http = require('http'),
- httpProxy = require('../../lib/node-http-proxy');
+ httpProxy = require('../../lib/http-proxy');
var welcome = [
'# # ##### ##### ##### ##### ##### #### # # # #',
@@ -43,7 +43,9 @@ util.puts(welcome.rainbow.bold);
//
// Basic Http Proxy Server
//
-httpProxy.createServer(9000, 'localhost').listen(8000);
+httpProxy.createServer({
+ target:'http://localhost:9003'
+}).listen(8003);
//
// Target Http Server
@@ -52,7 +54,7 @@ http.createServer(function (req, res) {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.write('request successfully proxied to: ' + req.url + '\n' + JSON.stringify(req.headers, true, 2));
res.end();
-}).listen(9000);
+}).listen(9003);
-util.puts('http proxy server'.blue + ' started '.green.bold + 'on port '.blue + '8000'.yellow);
-util.puts('http server '.blue + 'started '.green.bold + 'on port '.blue + '9000 '.yellow);
+util.puts('http proxy server'.blue + ' started '.green.bold + 'on port '.blue + '8003'.yellow);
+util.puts('http server '.blue + 'started '.green.bold + 'on port '.blue + '9003 '.yellow);
diff --git a/examples/http/concurrent-proxy.js b/examples/http/concurrent-proxy.js
index 230dfc651..30aa53dd6 100644
--- a/examples/http/concurrent-proxy.js
+++ b/examples/http/concurrent-proxy.js
@@ -1,7 +1,7 @@
/*
concurrent-proxy.js: check levelof concurrency through proxy.
- Copyright (c) 2010 Charlie Robbins, Mikeal Rogers, Fedor Indutny, & Marak Squires.
+ Copyright (c) Nodejitsu 2013
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
@@ -27,12 +27,14 @@
var util = require('util'),
colors = require('colors'),
http = require('http'),
- httpProxy = require('../../lib/node-http-proxy');
+ httpProxy = require('../../lib/http-proxy');
//
// Basic Http Proxy Server
//
-httpProxy.createServer(9000, 'localhost').listen(8000);
+httpProxy.createServer({
+ target:'http://localhost:9004'
+}).listen(8004);
//
// Target Http Server
@@ -60,7 +62,7 @@ http.createServer(function (req, res) {
connections.shift()();
}
}
-}).listen(9000);
+}).listen(9004);
-util.puts('http proxy server'.blue + ' started '.green.bold + 'on port '.blue + '8000'.yellow);
-util.puts('http server '.blue + 'started '.green.bold + 'on port '.blue + '9000 '.yellow);
+util.puts('http proxy server'.blue + ' started '.green.bold + 'on port '.blue + '8004'.yellow);
+util.puts('http server '.blue + 'started '.green.bold + 'on port '.blue + '9004 '.yellow);
diff --git a/examples/http/custom-proxy-error.js b/examples/http/custom-proxy-error.js
index dc439ea19..1c54b5ab8 100644
--- a/examples/http/custom-proxy-error.js
+++ b/examples/http/custom-proxy-error.js
@@ -1,7 +1,7 @@
/*
custom-proxy-error.js: Example of using the custom `proxyError` event.
- Copyright (c) 2010 Charlie Robbins, Mikeal Rogers, Fedor Indutny, & Marak Squires.
+ Copyright (c) Nodejitsu 2013
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
@@ -27,22 +27,23 @@
var util = require('util'),
colors = require('colors'),
http = require('http'),
- httpProxy = require('../../lib/node-http-proxy');
+ httpProxy = require('../../lib/http-proxy');
//
-// Http Proxy Server with Latency
+// Http Proxy Server with bad target
//
-var server = httpProxy.createServer(9000, 'localhost');
+var proxy = httpProxy.createServer({
+ target:'http://localhost:9005'
+});
//
-// Tell the server to listen on port 8002
+// Tell the proxy to listen on port 8000
//
-server.listen(8002);
+proxy.listen(8005);
//
-// Listen for the `proxyError` event on `server.proxy`. _It will not
-// be raised on the server itself._
-server.proxy.on('proxyError', function (err, req, res) {
+// Listen for the `error` event on `proxy`.
+proxy.on('error', function (err, req, res) {
res.writeHead(500, {
'Content-Type': 'text/plain'
});
@@ -51,4 +52,4 @@ server.proxy.on('proxyError', function (err, req, res) {
});
-util.puts('http proxy server '.blue + 'started '.green.bold + 'on port '.blue + '8002 '.yellow + 'with custom error message'.magenta.underline);
\ No newline at end of file
+util.puts('http proxy server '.blue + 'started '.green.bold + 'on port '.blue + '8005 '.yellow + 'with custom error message'.magenta.underline);
\ No newline at end of file
diff --git a/examples/middleware/gzip-middleware-proxytable.js b/examples/http/error-handling.js
similarity index 57%
rename from examples/middleware/gzip-middleware-proxytable.js
rename to examples/http/error-handling.js
index 527d3d7b8..292fb6144 100644
--- a/examples/middleware/gzip-middleware-proxytable.js
+++ b/examples/http/error-handling.js
@@ -1,7 +1,7 @@
/*
- gzip-middleware-proxytable.js: Basic example of `connect-gzip` middleware in node-http-proxy
+ error-handling.js: Example of handle erros for HTTP and WebSockets
- Copyright (c) 2010 Charlie Robbins, Mikeal Rogers, Fedor Indutny, Marak Squires, & Dominic Tarr.
+ Copyright (c) Nodejitsu 2013
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
@@ -27,28 +27,37 @@
var util = require('util'),
colors = require('colors'),
http = require('http'),
- httpProxy = require('../../lib/node-http-proxy');
+ httpProxy = require('../../lib/http-proxy');
//
-// Basic Http Proxy Server
+// HTTP Proxy Server
//
-httpProxy.createServer(
- require('connect-gzip').gzip({ matchType: /.?/ }),
- {
- router: {
- "localhost/fun": "localhost:9000"
- }
- }
-).listen(8000);
+var proxy = httpProxy.createProxyServer({target:'http://localhost:9000', ws:true});
//
-// Target Http Server
+// Example of error handling
//
-http.createServer(function (req, res) {
- res.writeHead(200, { 'Content-Type': 'text/plain' });
- res.write('request successfully proxied to: ' + req.url + '\n' + JSON.stringify(req.headers, true, 2));
- res.end();
-}).listen(9000);
-
+function requestHandler(req, res) {
+ // Pass a callback to the web proxy method
+ // and catch the error there.
+ proxy.web(req, res, function (err) {
+ // Now you can get the err
+ // and handle it by your self
+ // if (err) throw err;
+ res.writeHead(502);
+ res.end("There was an error proxying your request");
+ });
+
+ // In a websocket request case
+ req.on('upgrade', function (req, socket, head) {
+ proxy.ws(req, socket, head, function (err) {
+ // Now you can get the err
+ // and handle it by your self
+ // if (err) throw err;
+ socket.close();
+ })
+ })
+}
+
+http.createServer(requestHandler).listen(8000);
util.puts('http proxy server'.blue + ' started '.green.bold + 'on port '.blue + '8000'.yellow);
-util.puts('http server '.blue + 'started '.green.bold + 'on port '.blue + '9000 '.yellow);
diff --git a/examples/http/proxy-table.js b/examples/http/forward-and-target-proxy.js
similarity index 64%
rename from examples/http/proxy-table.js
rename to examples/http/forward-and-target-proxy.js
index 55d97aed5..c564bfbbd 100644
--- a/examples/http/proxy-table.js
+++ b/examples/http/forward-and-target-proxy.js
@@ -1,7 +1,7 @@
/*
- proxy-table.js: Example of proxying over HTTP with proxy table
+ forward-and-target-proxy.js: Example of proxying over HTTP with additional forward proxy
- Copyright (c) 2010 Charlie Robbins, Mikeal Rogers, Fedor Indutny, & Marak Squires.
+ Copyright (c) Nodejitsu 2013
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
@@ -27,16 +27,21 @@
var util = require('util'),
colors = require('colors'),
http = require('http'),
- httpProxy = require('../../lib/node-http-proxy');
+ httpProxy = require('../../lib/http-proxy');
//
-// Http Proxy Server with Proxy Table
+// Setup proxy server with forwarding
//
httpProxy.createServer({
- router: {
- 'localhost': 'localhost:9000'
+ target: {
+ port: 9006,
+ host: 'localhost'
+ },
+ forward: {
+ port: 9007,
+ host: 'localhost'
}
-}).listen(8001);
+}).listen(8006);
//
// Target Http Server
@@ -45,7 +50,18 @@ http.createServer(function (req, res) {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.write('request successfully proxied to: ' + req.url + '\n' + JSON.stringify(req.headers, true, 2));
res.end();
-}).listen(9000);
+}).listen(9006);
-util.puts('http proxy server '.blue + 'started '.green.bold + 'on port '.blue + '8001 '.yellow + 'with proxy table'.magenta.underline);
-util.puts('http server '.blue + 'started '.green.bold + 'on port '.blue + '9000 '.yellow);
+//
+// Target Http Forwarding Server
+//
+http.createServer(function (req, res) {
+ util.puts('Receiving forward for: ' + req.url);
+ res.writeHead(200, { 'Content-Type': 'text/plain' });
+ res.write('request successfully forwarded to: ' + req.url + '\n' + JSON.stringify(req.headers, true, 2));
+ res.end();
+}).listen(9007);
+
+util.puts('http proxy server '.blue + 'started '.green.bold + 'on port '.blue + '8006 '.yellow + 'with forward proxy'.magenta.underline);
+util.puts('http server '.blue + 'started '.green.bold + 'on port '.blue + '9006 '.yellow);
+util.puts('http forward server '.blue + 'started '.green.bold + 'on port '.blue + '9007 '.yellow);
\ No newline at end of file
diff --git a/examples/http/forward-proxy.js b/examples/http/forward-proxy.js
index ecc20fd4c..d94f48414 100644
--- a/examples/http/forward-proxy.js
+++ b/examples/http/forward-proxy.js
@@ -1,7 +1,7 @@
/*
forward-proxy.js: Example of proxying over HTTP with additional forward proxy
- Copyright (c) 2010 Charlie Robbins, Mikeal Rogers, Fedor Indutny, & Marak Squires.
+ Copyright (c) Nodejitsu 2013
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
@@ -27,26 +27,17 @@
var util = require('util'),
colors = require('colors'),
http = require('http'),
- httpProxy = require('../../lib/node-http-proxy');
+ httpProxy = require('../../lib/http-proxy');
//
// Setup proxy server with forwarding
//
-httpProxy.createServer(9000, 'localhost', {
+httpProxy.createServer({
forward: {
- port: 9001,
+ port: 9019,
host: 'localhost'
}
-}).listen(8003);
-
-//
-// Target Http Server
-//
-http.createServer(function (req, res) {
- res.writeHead(200, { 'Content-Type': 'text/plain' });
- res.write('request successfully proxied to: ' + req.url + '\n' + JSON.stringify(req.headers, true, 2));
- res.end();
-}).listen(9000);
+}).listen(8019);
//
// Target Http Forwarding Server
@@ -56,8 +47,7 @@ http.createServer(function (req, res) {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.write('request successfully forwarded to: ' + req.url + '\n' + JSON.stringify(req.headers, true, 2));
res.end();
-}).listen(9001);
+}).listen(9019);
-util.puts('http proxy server '.blue + 'started '.green.bold + 'on port '.blue + '8003 '.yellow + 'with forward proxy'.magenta.underline);
-util.puts('http server '.blue + 'started '.green.bold + 'on port '.blue + '9000 '.yellow);
-util.puts('http forward server '.blue + 'started '.green.bold + 'on port '.blue + '9001 '.yellow);
\ No newline at end of file
+util.puts('http proxy server '.blue + 'started '.green.bold + 'on port '.blue + '8019 '.yellow + 'with forward proxy'.magenta.underline);
+util.puts('http forward server '.blue + 'started '.green.bold + 'on port '.blue + '9019 '.yellow);
\ No newline at end of file
diff --git a/examples/http/latent-proxy.js b/examples/http/latent-proxy.js
index 2063d0e5b..01ec93cc7 100644
--- a/examples/http/latent-proxy.js
+++ b/examples/http/latent-proxy.js
@@ -1,7 +1,7 @@
/*
latent-proxy.js: Example of proxying over HTTP with latency
- Copyright (c) 2010 Charlie Robbins, Mikeal Rogers, Fedor Indutny, & Marak Squires.
+ Copyright (c) Nodejitsu 2013
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
@@ -27,21 +27,19 @@
var util = require('util'),
colors = require('colors'),
http = require('http'),
- httpProxy = require('../../lib/node-http-proxy');
+ httpProxy = require('../../lib/http-proxy');
//
// Http Proxy Server with Latency
//
-httpProxy.createServer(function (req, res, proxy) {
- var buffer = httpProxy.buffer(req);
+var proxy = httpProxy.createProxyServer();
+http.createServer(function (req, res) {
setTimeout(function () {
- proxy.proxyRequest(req, res, {
- port: 9000,
- host: 'localhost',
- buffer: buffer
+ proxy.web(req, res, {
+ target: 'http://localhost:9008'
});
- }, 200);
-}).listen(8002);
+ }, 500);
+}).listen(8008);
//
// Target Http Server
@@ -50,7 +48,7 @@ http.createServer(function (req, res) {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.write('request successfully proxied to: ' + req.url + '\n' + JSON.stringify(req.headers, true, 2));
res.end();
-}).listen(9000);
+}).listen(9008);
-util.puts('http proxy server '.blue + 'started '.green.bold + 'on port '.blue + '8002 '.yellow + 'with latency'.magenta.underline);
-util.puts('http server '.blue + 'started '.green.bold + 'on port '.blue + '9000 '.yellow);
+util.puts('http proxy server '.blue + 'started '.green.bold + 'on port '.blue + '8008 '.yellow + 'with latency'.magenta.underline);
+util.puts('http server '.blue + 'started '.green.bold + 'on port '.blue + '9008 '.yellow);
diff --git a/examples/middleware/url-middleware.js b/examples/http/proxy-http-to-https.js
similarity index 50%
rename from examples/middleware/url-middleware.js
rename to examples/http/proxy-http-to-https.js
index b4f304562..ba5c83816 100644
--- a/examples/middleware/url-middleware.js
+++ b/examples/http/proxy-http-to-https.js
@@ -1,7 +1,7 @@
/*
- url-middleware.js: Example of a simple url routing middleware for node-http-proxy
+ proxy-http-to-https.js: Basic example of proxying over HTTP to a target HTTPS server
- Copyright (c) 2010 Charlie Robbins, Mikeal Rogers, Fedor Indutny, & Marak Squires.
+ Copyright (c) Nodejitsu 2013
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
@@ -24,35 +24,23 @@
*/
-var util = require('util'),
+var https = require('https'),
+ http = require('http'),
+ util = require('util'),
+ path = require('path'),
+ fs = require('fs'),
colors = require('colors'),
- http = require('http'),
- httpProxy = require('../../lib/node-http-proxy');
+ httpProxy = require('../../lib/http-proxy');
//
-// Now we set up our proxy.
+// Create a HTTP Proxy server with a HTTPS target
//
-httpProxy.createServer(
- //
- // This is where our middlewares go, with any options desired - in this case,
- // the list of routes/URLs and their destinations.
- //
- require('proxy-by-url')({
- '/hello': { port: 9000, host: 'localhost' },
- '/charlie': { port: 80, host: 'charlieistheman.com' },
- '/google': { port: 80, host: 'google.com' }
- })
-).listen(8000);
-
-//
-// Target Http Server (to listen for requests on 'localhost')
-//
-http.createServer(function (req, res) {
- res.writeHead(200, { 'Content-Type': 'text/plain' });
- res.write('request successfully proxied to: ' + req.url + '\n' + JSON.stringify(req.headers, true, 2));
- res.end();
-}).listen(9000);
-
-// And finally, some colored startup output.
-util.puts('http proxy server'.blue + ' started '.green.bold + 'on port '.blue + '8000'.yellow);
-util.puts('http server '.blue + 'started '.green.bold + 'on port '.blue + '9000 '.yellow);
+httpProxy.createProxyServer({
+ target: 'https://google.com',
+ agent : https.globalAgent,
+ headers: {
+ host: 'google.com'
+ }
+}).listen(8011);
+
+util.puts('http proxy server'.blue + ' started '.green.bold + 'on port '.blue + '8011'.yellow);
\ No newline at end of file
diff --git a/examples/http/proxy-https-to-http.js b/examples/http/proxy-https-to-http.js
index 378de0362..d2a2d5c0d 100644
--- a/examples/http/proxy-https-to-http.js
+++ b/examples/http/proxy-https-to-http.js
@@ -1,7 +1,7 @@
/*
proxy-https-to-http.js: Basic example of proxying over HTTPS to a target HTTP server
- Copyright (c) 2010 Charlie Robbins, Mikeal Rogers, Fedor Indutny, & Marak Squires.
+ Copyright (c) Nodejitsu 2013
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
@@ -25,27 +25,36 @@
*/
var https = require('https'),
- http = require('http'),
- util = require('util'),
+ http = require('http'),
+ util = require('util'),
+ path = require('path'),
+ fs = require('fs'),
colors = require('colors'),
- httpProxy = require('../../lib/node-http-proxy'),
- helpers = require('../../test/helpers');
+ httpProxy = require('../../lib/http-proxy'),
+ fixturesDir = path.join(__dirname, '..', '..', 'test', 'fixtures');
//
-// Create the target HTTPS server
+// Create the target HTTP server
//
http.createServer(function (req, res) {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.write('hello http over https\n');
res.end();
-}).listen(8000);
+}).listen(9009);
//
-// Create the proxy server listening on port 443
+// Create the HTTPS proxy server listening on port 8000
//
-httpProxy.createServer(8000, 'localhost', {
- https: helpers.https
-}).listen(8080);
-
-util.puts('https proxy server'.blue + ' started '.green.bold + 'on port '.blue + '8080'.yellow);
-util.puts('http server '.blue + 'started '.green.bold + 'on port '.blue + '8000 '.yellow);
+httpProxy.createServer({
+ target: {
+ host: 'localhost',
+ port: 9009
+ },
+ ssl: {
+ key: fs.readFileSync(path.join(fixturesDir, 'agent2-key.pem'), 'utf8'),
+ cert: fs.readFileSync(path.join(fixturesDir, 'agent2-cert.pem'), 'utf8')
+ }
+}).listen(8009);
+
+util.puts('https proxy server'.blue + ' started '.green.bold + 'on port '.blue + '8009'.yellow);
+util.puts('http server '.blue + 'started '.green.bold + 'on port '.blue + '9009 '.yellow);
diff --git a/examples/http/proxy-https-to-https.js b/examples/http/proxy-https-to-https.js
index af0d92275..e543f98a7 100644
--- a/examples/http/proxy-https-to-https.js
+++ b/examples/http/proxy-https-to-https.js
@@ -1,7 +1,7 @@
/*
proxy-https-to-https.js: Basic example of proxying over HTTPS to a target HTTPS server
- Copyright (c) 2010 Charlie Robbins, Mikeal Rogers, Fedor Indutny, & Marak Squires.
+ Copyright (c) Nodejitsu 2013
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
@@ -27,29 +27,33 @@
var https = require('https'),
http = require('http'),
util = require('util'),
+ fs = require('fs'),
+ path = require('path'),
colors = require('colors'),
- httpProxy = require('../../lib/node-http-proxy'),
- helpers = require('../../test/helpers');
+ httpProxy = require('../../lib/http-proxy'),
+ fixturesDir = path.join(__dirname, '..', '..', 'test', 'fixtures'),
+ httpsOpts = {
+ key: fs.readFileSync(path.join(fixturesDir, 'agent2-key.pem'), 'utf8'),
+ cert: fs.readFileSync(path.join(fixturesDir, 'agent2-cert.pem'), 'utf8')
+ };
//
// Create the target HTTPS server
//
-https.createServer(helpers.https, function (req, res) {
+https.createServer(httpsOpts, function (req, res) {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.write('hello https\n');
res.end();
-}).listen(8000);
+}).listen(9010);
//
// Create the proxy server listening on port 443
//
-httpProxy.createServer(8000, 'localhost', {
- https: helpers.https,
- target: {
- https: true,
- rejectUnauthorized: false
- }
-}).listen(8080);
-
-util.puts('https proxy server'.blue + ' started '.green.bold + 'on port '.blue + '8080'.yellow);
-util.puts('https server '.blue + 'started '.green.bold + 'on port '.blue + '8000 '.yellow);
+httpProxy.createServer({
+ ssl: httpsOpts,
+ target: 'https://localhost:9010',
+ secure: false
+}).listen(8010);
+
+util.puts('https proxy server'.blue + ' started '.green.bold + 'on port '.blue + '8010'.yellow);
+util.puts('https server '.blue + 'started '.green.bold + 'on port '.blue + '9010 '.yellow);
diff --git a/examples/http/standalone-proxy.js b/examples/http/standalone-proxy.js
index e1b1011c5..410d70b31 100644
--- a/examples/http/standalone-proxy.js
+++ b/examples/http/standalone-proxy.js
@@ -1,7 +1,7 @@
/*
standalone-proxy.js: Example of proxying over HTTP with a standalone HTTP server.
- Copyright (c) 2010 Charlie Robbins, Mikeal Rogers, Fedor Indutny, & Marak Squires.
+ Copyright (c) Nodejitsu 2013
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
@@ -27,22 +27,19 @@
var util = require('util'),
colors = require('colors'),
http = require('http'),
- httpProxy = require('../../lib/node-http-proxy');
+ httpProxy = require('../../lib/http-proxy');
//
// Http Server with proxyRequest Handler and Latency
//
-var proxy = new httpProxy.RoutingProxy();
+var proxy = new httpProxy.createProxyServer();
http.createServer(function (req, res) {
- var buffer = httpProxy.buffer(req);
setTimeout(function () {
- proxy.proxyRequest(req, res, {
- port: 9000,
- host: 'localhost',
- buffer: buffer
+ proxy.web(req, res, {
+ target: 'http://localhost:9002'
});
}, 200);
-}).listen(8004);
+}).listen(8002);
//
// Target Http Server
@@ -51,7 +48,7 @@ http.createServer(function (req, res) {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.write('request successfully proxied to: ' + req.url + '\n' + JSON.stringify(req.headers, true, 2));
res.end();
-}).listen(9000);
+}).listen(9002);
-util.puts('http server '.blue + 'started '.green.bold + 'on port '.blue + '8004 '.yellow + 'with proxyRequest handler'.cyan.underline + ' and latency'.magenta);
-util.puts('http server '.blue + 'started '.green.bold + 'on port '.blue + '9000 '.yellow);
+util.puts('http server '.blue + 'started '.green.bold + 'on port '.blue + '8002 '.yellow + 'with proxy.web() handler'.cyan.underline + ' and latency'.magenta);
+util.puts('http server '.blue + 'started '.green.bold + 'on port '.blue + '9001 '.yellow);
diff --git a/examples/middleware/bodyDecoder-middleware.js b/examples/middleware/bodyDecoder-middleware.js
index d889548a0..555c3d154 100644
--- a/examples/middleware/bodyDecoder-middleware.js
+++ b/examples/middleware/bodyDecoder-middleware.js
@@ -1,8 +1,40 @@
+/*
+ bodyDecoder-middleware.js: Basic example of `connect.bodyParser()` middleware in node-http-proxy
-var Store = require('../helpers/store')
- , http = require('http')
+ Copyright (c) Nodejitsu 2013
+
+ Permission is hereby granted, free of charge, to any person obtaining
+ a copy of this software and associated documentation files (the
+ "Software"), to deal in the Software without restriction, including
+ without limitation the rights to use, copy, modify, merge, publish,
+ distribute, sublicense, and/or sell copies of the Software, and to
+ permit persons to whom the Software is furnished to do so, subject to
+ the following conditions:
+
+ The above copyright notice and this permission notice shall be
+ included in all copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+ LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+
+*/
+
+var http = require('http'),
+ connect = require('connect'),
+ request = require('request'),
+ colors = require('colors'),
+ util = require('util'),
+ Store = require('../helpers/store'),
+ httpProxy = require('../../lib/http-proxy'),
+ proxy = httpProxy.createProxyServer({});
http.createServer(new Store().handler()).listen(7531, function () {
+ util.puts('http '.blue + 'greetings '.green + 'server'.blue + ' started '.green.bold + 'on port '.blue + '7531'.yellow);
//try these commands:
// get index:
// curl localhost:7531
@@ -33,31 +65,31 @@ http.createServer(new Store().handler()).listen(7531, function () {
//insult server:
http.createServer(new Store().handler()).listen(2600, function () {
+ util.puts('http '.blue + 'insults '.red + 'server'.blue + ' started '.green.bold + 'on port '.blue + '2600'.yellow);
//greetings -> 7531, insults-> 2600
// now, start a proxy server.
- var bodyParser = require('connect/lib/middleware/bodyParser')
//don't worry about incoming contont type
//bodyParser.parse[''] = JSON.parse
- require('../../lib/node-http-proxy').createServer(
+ connect.createServer(
//refactor the body parser and re-streamer into a separate package
- bodyParser(),
+ connect.bodyParser(),
//body parser absorbs the data and end events before passing control to the next
// middleware. if we want to proxy it, we'll need to re-emit these events after
//passing control to the middleware.
require('connect-restreamer')(),
- function (req, res, proxy) {
+ function (req, res) {
//if your posting an obect which contains type: "insult"
//it will get redirected to port 2600.
//normal get requests will go to 7531 nad will not return insults.
var port = (req.body && req.body.type === 'insult' ? 2600 : 7531)
- proxy.proxyRequest(req, res, {host: 'localhost', port: port})
+ proxy.web(req, res, { target: { host: 'localhost', port: port }});
}
).listen(1337, function () {
- var request = require('request')
+ util.puts('http proxy server'.blue + ' started '.green.bold + 'on port '.blue + '1337'.yellow);
//bodyParser needs content-type set to application/json
//if we use request, it will set automatically if we use the 'json:' field.
function post (greeting, type) {
@@ -84,4 +116,4 @@ http.createServer(new Store().handler()).listen(7531, function () {
})
})
-})
+});
\ No newline at end of file
diff --git a/examples/middleware/gzip-middleware.js b/examples/middleware/gzip-middleware.js
index 29097ecd3..756b68fa3 100644
--- a/examples/middleware/gzip-middleware.js
+++ b/examples/middleware/gzip-middleware.js
@@ -1,7 +1,7 @@
/*
gzip-middleware.js: Basic example of `connect-gzip` middleware in node-http-proxy
- Copyright (c) 2010 Charlie Robbins, Mikeal Rogers, Fedor Indutny, Marak Squires, & Dominic Tarr.
+ Copyright (c) Nodejitsu 2013
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
@@ -27,15 +27,30 @@
var util = require('util'),
colors = require('colors'),
http = require('http'),
- httpProxy = require('../../lib/node-http-proxy');
+ connect = require('connect')
+ httpProxy = require('../../lib/http-proxy');
+
+//
+// Basic Connect App
+//
+connect.createServer(
+ connect.compress({
+ // Pass to connect.compress() the options
+ // that you need, just for show the example
+ // we use threshold to 1
+ threshold: 1
+ }),
+ function (req, res) {
+ proxy.web(req, res);
+ }
+).listen(8012);
//
// Basic Http Proxy Server
//
-httpProxy.createServer(
- require('connect-gzip').gzip({ matchType: /.?/ }),
- 9000, 'localhost'
-).listen(8000);
+var proxy = httpProxy.createProxyServer({
+ target: 'http://localhost:9012'
+});
//
// Target Http Server
@@ -44,7 +59,7 @@ http.createServer(function (req, res) {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.write('request successfully proxied to: ' + req.url + '\n' + JSON.stringify(req.headers, true, 2));
res.end();
-}).listen(9000);
+}).listen(9012);
-util.puts('http proxy server'.blue + ' started '.green.bold + 'on port '.blue + '8000'.yellow);
-util.puts('http server '.blue + 'started '.green.bold + 'on port '.blue + '9000 '.yellow);
+util.puts('http proxy server'.blue + ' started '.green.bold + 'on port '.blue + '8012'.yellow);
+util.puts('http server '.blue + 'started '.green.bold + 'on port '.blue + '9012 '.yellow);
diff --git a/examples/middleware/jsonp-middleware.js b/examples/middleware/jsonp-middleware.js
deleted file mode 100644
index 15ab9ee05..000000000
--- a/examples/middleware/jsonp-middleware.js
+++ /dev/null
@@ -1,30 +0,0 @@
-var Store = require('../helpers/store')
- , http = require('http')
-
-//
-// jsonp is a handy technique for getting around the limitations of the same-origin policy.
-// (http://en.wikipedia.org/wiki/Same_origin_policy)
-//
-// normally, to dynamically update a page you use an XmlHttpRequest. this has flakey support
-// is some browsers and is restricted by the same origin policy. you cannot perform XHR requests to
-// someone else's server. one way around this would be to proxy requests to all the servers you want
-// to xhr to, and your core server - so that everything has the same port and host.
-//
-// another way, is to turn json into javascript. (which is exempt from the same origin policy)
-// this is done by wrapping the json object in a function call, and then including a script tag.
-//
-// here we're proxing our own JSON returning server, but we could proxy any server on the internet,
-// and our client side app would be slurping down JSONP from anywhere.
-//
-// curl localhost:1337/whatever?callback=alert
-// alert([]) //which is valid javascript!
-//
-// also see http://en.wikipedia.org/wiki/JSONP#JSONP
-//
-
-http.createServer(new Store().handler()).listen(7531)
-
-require('../../lib/node-http-proxy').createServer(
- require('connect-jsonp')(true),
- 'localhost', 7531
-).listen(1337)
diff --git a/examples/middleware/modifyResponse-middleware.js b/examples/middleware/modifyResponse-middleware.js
index af21236ef..fdd7e6596 100644
--- a/examples/middleware/modifyResponse-middleware.js
+++ b/examples/middleware/modifyResponse-middleware.js
@@ -1,7 +1,7 @@
/*
modifyBody-middleware.js: Example of middleware which modifies response
- Copyright (c) 2010 Charlie Robbins, Mikeal Rogers, Fedor Indutny, Marak Squires, & Dominic Tarr.
+ Copyright (c) Nodejitsu 2013
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
@@ -27,12 +27,13 @@
var util = require('util'),
colors = require('colors'),
http = require('http'),
- httpProxy = require('../../lib/node-http-proxy');
+ connect = require('connect'),
+ httpProxy = require('../../lib/http-proxy');
//
-// Basic Http Proxy Server
+// Basic Connect App
//
-httpProxy.createServer(
+connect.createServer(
function (req, res, next) {
var _write = res.write;
@@ -41,8 +42,17 @@ httpProxy.createServer(
}
next();
},
- 9000, 'localhost'
-).listen(8000);
+ function (req, res) {
+ proxy.web(req, res);
+ }
+).listen(8013);
+
+//
+// Basic Http Proxy Server
+//
+var proxy = httpProxy.createProxyServer({
+ target: 'http://localhost:9013'
+});
//
// Target Http Server
@@ -50,8 +60,8 @@ httpProxy.createServer(
http.createServer(function (req, res) {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Hello, I know Ruby\n');
-}).listen(9000);
+}).listen(9013);
-util.puts('http proxy server'.blue + ' started '.green.bold + 'on port '.blue + '8000'.yellow);
-util.puts('http server '.blue + 'started '.green.bold + 'on port '.blue + '9000 '.yellow);
+util.puts('http proxy server'.blue + ' started '.green.bold + 'on port '.blue + '8013'.yellow);
+util.puts('http server '.blue + 'started '.green.bold + 'on port '.blue + '9013 '.yellow);
diff --git a/examples/middleware/url-middleware2.js b/examples/middleware/url-middleware2.js
deleted file mode 100644
index 2c894e1af..000000000
--- a/examples/middleware/url-middleware2.js
+++ /dev/null
@@ -1,30 +0,0 @@
-var util = require('util'),
- colors = require('colors'),
- http = require('http'),
- httpProxy = require('../../lib/node-http-proxy'),
- Store = require('../helpers/store')
-
-http.createServer(new Store().handler()).listen(7531)
-
-// Now we set up our proxy.
-httpProxy.createServer(
- // This is where our middlewares go, with any options desired - in this case,
- // the list of routes/URLs and their destinations.
- require('proxy-by-url')({
- '/store': { port: 7531, host: 'localhost' },
- '/': { port: 9000, host: 'localhost' }
- })
-).listen(8000);
-
-//
-// Target Http Server (to listen for requests on 'localhost')
-//
-http.createServer(function (req, res) {
- res.writeHead(200, { 'Content-Type': 'text/plain' });
- res.write('request successfully proxied to: ' + req.url + '\n' + JSON.stringify(req.headers, true, 2));
- res.end();
-}).listen(9000);
-
-// And finally, some colored startup output.
-util.puts('http proxy server'.blue + ' started '.green.bold + 'on port '.blue + '8000'.yellow);
-util.puts('http server '.blue + 'started '.green.bold + 'on port '.blue + '9000 '.yellow);
diff --git a/examples/package.json b/examples/package.json
index ca95fd8cf..3daede1f1 100644
--- a/examples/package.json
+++ b/examples/package.json
@@ -1,12 +1,13 @@
{
- "name": "http-proxy-examples",
- "description": "packages required to run the examples",
+ "name": "http-proxy-examples",
+ "description": "packages required to run the examples",
"version": "0.0.0",
"dependencies": {
- "connect": "1.6",
- "connect-gzip": "0.1",
- "connect-jsonp": "0.0.5",
- "connect-restreamer": "1",
- "proxy-by-url": ">= 0.0.1"
+ "colors": "~0.6.2",
+ "socket.io": "~0.9.16",
+ "socket.io-client": "~0.9.16",
+ "connect": "~2.11.0",
+ "request": "~2.27.0",
+ "connect-restreamer": "~1.0.0"
}
-}
\ No newline at end of file
+}
diff --git a/examples/websocket/latent-websocket-proxy.js b/examples/websocket/latent-websocket-proxy.js
index 99a07281e..64d3d7ce0 100644
--- a/examples/websocket/latent-websocket-proxy.js
+++ b/examples/websocket/latent-websocket-proxy.js
@@ -1,7 +1,7 @@
/*
standalone-websocket-proxy.js: Example of proxying websockets over HTTP with a standalone HTTP server.
- Copyright (c) 2010 Charlie Robbins, Mikeal Rogers, Fedor Indutny, & Marak Squires.
+ Copyright (c) Nodejitsu 2013
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
@@ -27,7 +27,7 @@
var util = require('util'),
http = require('http'),
colors = require('colors'),
- httpProxy = require('../../lib/node-http-proxy');
+ httpProxy = require('../../lib/http-proxy');
try {
var io = require('socket.io'),
@@ -43,7 +43,7 @@ catch (ex) {
// Create the target HTTP server and setup
// socket.io on it.
//
-var server = io.listen(8080);
+var server = io.listen(9016);
server.sockets.on('connection', function (client) {
util.debug('Got websocket connection');
@@ -57,15 +57,15 @@ server.sockets.on('connection', function (client) {
//
// Setup our server to proxy standard HTTP requests
//
-var proxy = new httpProxy.HttpProxy({
+var proxy = new httpProxy.createProxyServer({
target: {
host: 'localhost',
- port: 8080
+ port: 9016
}
});
var proxyServer = http.createServer(function (req, res) {
- proxy.proxyRequest(req, res);
+ proxy.web(req, res);
});
//
@@ -73,20 +73,19 @@ var proxyServer = http.createServer(function (req, res) {
// WebSocket requests as well.
//
proxyServer.on('upgrade', function (req, socket, head) {
- var buffer = httpProxy.buffer(socket);
-
setTimeout(function () {
- proxy.proxyWebSocketRequest(req, socket, head, buffer);
+ proxy.ws(req, socket, head);
}, 1000);
});
-proxyServer.listen(8081);
+proxyServer.listen(8016);
//
// Setup the socket.io client against our proxy
//
-var ws = client.connect('ws://localhost:8081');
+var ws = client.connect('ws://localhost:8016');
ws.on('message', function (msg) {
util.debug('Got message: ' + msg);
+ ws.send('I am the client');
});
diff --git a/examples/websocket/standalone-websocket-proxy.js b/examples/websocket/standalone-websocket-proxy.js
index acf43b979..81d019650 100644
--- a/examples/websocket/standalone-websocket-proxy.js
+++ b/examples/websocket/standalone-websocket-proxy.js
@@ -1,7 +1,7 @@
/*
standalone-websocket-proxy.js: Example of proxying websockets over HTTP with a standalone HTTP server.
- Copyright (c) 2010 Charlie Robbins, Mikeal Rogers, Fedor Indutny, & Marak Squires.
+ Copyright (c) Nodejitsu 2013
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
@@ -27,7 +27,7 @@
var util = require('util'),
http = require('http'),
colors = require('colors'),
- httpProxy = require('../../lib/node-http-proxy');
+ httpProxy = require('../../lib/http-proxy');
try {
var io = require('socket.io'),
@@ -43,7 +43,7 @@ catch (ex) {
// Create the target HTTP server and setup
// socket.io on it.
//
-var server = io.listen(8080);
+var server = io.listen(9015);
server.sockets.on('connection', function (client) {
util.debug('Got websocket connection');
@@ -57,14 +57,14 @@ server.sockets.on('connection', function (client) {
//
// Setup our server to proxy standard HTTP requests
//
-var proxy = new httpProxy.HttpProxy({
+var proxy = new httpProxy.createProxyServer({
target: {
- host: 'localhost',
- port: 8080
+ host: 'localhost',
+ port: 9015
}
});
var proxyServer = http.createServer(function (req, res) {
- proxy.proxyRequest(req, res);
+ proxy.web(req, res);
});
//
@@ -72,16 +72,17 @@ var proxyServer = http.createServer(function (req, res) {
// WebSocket requests as well.
//
proxyServer.on('upgrade', function (req, socket, head) {
- proxy.proxyWebSocketRequest(req, socket, head);
+ proxy.ws(req, socket, head);
});
-proxyServer.listen(8081);
+proxyServer.listen(8015);
//
// Setup the socket.io client against our proxy
//
-var ws = client.connect('ws://localhost:8081');
+var ws = client.connect('ws://localhost:8015');
ws.on('message', function (msg) {
util.debug('Got message: ' + msg);
+ ws.send('I am the client');
});
diff --git a/examples/websocket/websocket-proxy.js b/examples/websocket/websocket-proxy.js
index 4e3cf6fd1..33d78c675 100644
--- a/examples/websocket/websocket-proxy.js
+++ b/examples/websocket/websocket-proxy.js
@@ -1,7 +1,7 @@
/*
web-socket-proxy.js: Example of proxying over HTTP and WebSockets.
- Copyright (c) 2010 Charlie Robbins, Mikeal Rogers, Fedor Indutny, & Marak Squires.
+ Copyright (c) Nodejitsu 2013
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
@@ -27,7 +27,7 @@
var util = require('util'),
http = require('http'),
colors = require('colors'),
- httpProxy = require('../../lib/node-http-proxy');
+ httpProxy = require('../../lib/http-proxy');
try {
var io = require('socket.io'),
@@ -43,7 +43,7 @@ catch (ex) {
// Create the target HTTP server and setup
// socket.io on it.
//
-var server = io.listen(8080);
+var server = io.listen(9014);
server.sockets.on('connection', function (client) {
util.debug('Got websocket connection');
@@ -57,13 +57,14 @@ server.sockets.on('connection', function (client) {
//
// Create a proxy server with node-http-proxy
//
-httpProxy.createServer(8080, 'localhost').listen(8081);
+httpProxy.createServer({ target: 'ws://localhost:9014', ws: true }).listen(8014);
//
// Setup the socket.io client against our proxy
//
-var ws = client.connect('ws://localhost:8081');
+var ws = client.connect('ws://localhost:8014');
ws.on('message', function (msg) {
util.debug('Got message: ' + msg);
+ ws.send('I am the client');
});
diff --git a/index.js b/index.js
new file mode 100644
index 000000000..e6fac8584
--- /dev/null
+++ b/index.js
@@ -0,0 +1,13 @@
+/*!
+ * Caron dimonio, con occhi di bragia
+ * loro accennando, tutte le raccoglie;
+ * batte col remo qualunque s’adagia
+ *
+ * Charon the demon, with the eyes of glede,
+ * Beckoning to them, collects them all together,
+ * Beats with his oar whoever lags behind
+ *
+ * Dante - The Divine Comedy (Canto III)
+ */
+
+module.exports = require('./lib/http-proxy');
\ No newline at end of file
diff --git a/lib/http-proxy.js b/lib/http-proxy.js
new file mode 100644
index 000000000..34029e864
--- /dev/null
+++ b/lib/http-proxy.js
@@ -0,0 +1,55 @@
+var http = require('http'),
+ https = require('https'),
+ url = require('url'),
+ httpProxy = require('./http-proxy/');
+
+/**
+ * Export the the proxy "Server" as the main export
+ */
+module.exports = httpProxy.Server;
+
+module.exports.createProxy = function(options) {
+ return {
+ web: httpProxy.createRightProxy('web')(options),
+ ws: httpProxy.createRightProxy('ws')(options)
+ };
+}
+
+/**
+ * Creates the proxy server.
+ *
+ * Examples:
+ *
+ * httpProxy.createProxyServer({ .. }, 8000)
+ * // => '{ web: [Function], ws: [Function] ... }'
+ *
+ * @param {Object} Options Config object passed to the proxy
+ *
+ * @return {Object} Proxy Proxy object with handlers for `ws` and `web` requests
+ *
+ * @api public
+ */
+
+module.exports.createProxyServer = module.exports.createServer = function createProxyServer(options) {
+ /*
+ * `options` is needed and it must have the following layout:
+ *
+ * {
+ * target :
+ * forward:
+ * agent :