Browse files

[api] refactor out middlewares from examples.

  • Loading branch information...
1 parent 020290a commit 2cf4e0a9e6c78dfd093c098fc87100ae71bc9450 @dominictarr dominictarr committed Jul 30, 2011
Showing with 82 additions and 136 deletions.
  1. +1 −11 examples/bodyDecoder-middleware.js
  2. +67 −0 examples/lib/store.js
  3. +12 −0 examples/package.json
  4. +1 −67 examples/url-middleware.js
  5. +1 −58 examples/url-middleware2.js
View
12 examples/bodyDecoder-middleware.js
@@ -48,17 +48,7 @@ http.createServer(new Store().handler()).listen(7531, function () {
//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.
- function (req, res, next) {
- //remove bodyParser's listeners
- req.removeAllListeners('data')
- req.removeAllListeners('end')
- next()
- process.nextTick(function () {
- if(req.body)
- req.emit('data', JSON.stringify(req.body))
- req.emit('end')
- })
- },
+ require('connect-restreamer')(),
function (req, res, proxy) {
//if your posting an obect which contains type: "insult"
//it will get redirected to port 2600.
View
67 examples/lib/store.js
@@ -0,0 +1,67 @@
+
+module.exports = Store
+//
+// just to make these example a little bit interesting,
+// make a little key value store with an http interface
+// (see couchbd for a grown-up version of this)
+//
+// API:
+// GET /
+// retrive list of keys
+//
+// GET /[url]
+// retrive object stored at [url]
+// will respond with 404 if there is nothing stored at [url]
+//
+// POST /[url]
+//
+// JSON.parse the body and store it under [url]
+// will respond 400 (bad request) if body is not valid json.
+//
+// TODO: cached map-reduce views and auto-magic sharding.
+//
+
+
+
+function Store () {
+ this.store = {}
+}
+Store.prototype = {
+ get: function (key) {
+ return this.store[key]
+ },
+ set: function (key, value) {
+ return this.store[key] = value
+ },
+ handler:function () {
+ var store = this
+ return function (req, res) {
+ function send (obj, status) {
+ res.writeHead(200 || status,{'Content-Type': 'application/json'})
+ res.write(JSON.stringify(obj) + '\n')
+ res.end()
+ }
+ var url = req.url.split('?').shift()
+ if(url === '/') {
+ console.log('get index')
+ return send(Object.keys(store.store))
+ } else if(req.method == 'GET') {
+ var obj = store.get (url)
+ send(obj || {error: 'not_found', url: url}, obj ? 200 : 404)
+ } else {
+ //post: buffer body, and parse.
+ var body = '', obj
+ req.on('data', function (c) { body += c})
+ req.on('end', function (c) {
+ try {
+ obj = JSON.parse(body)
+ } catch (err) {
+ return send (err, 400)
+ }
+ store.set(url, obj)
+ send({ok: true})
+ })
+ }
+ }
+ }
+}
View
12 examples/package.json
@@ -0,0 +1,12 @@
+{
+ "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.0"
+ }
+}
View
68 examples/url-middleware.js
@@ -28,72 +28,6 @@ var util = require('util'),
colors = require('colors'),
http = require('http'),
httpProxy = require('http-proxy');
-
-//
-// This is an example of a url-routing middleware.
-// This is not intended for production use, but rather as
-// an example of how to write a middleware.
-//
-
-function matcher (url, dest) {
- //
- // First, turn the URL into a regex.
- // NOTE: Turning user input directly into a Regular Expression is NOT SAFE.
- //
- var r = new RegExp(url.replace(/\//, '\\/'));
-
- //
- // This next block of code may look a little confusing.
- // It returns a closure (anonymous function) for each URL to be matched,
- // storing them in an array - on each request, if the URL matches one that has
- // a function stored for it, the function will be called.
- //
- return function (url) {
- var m = r(url)
- if (!m) {
- return;
- }
- var path = url.slice(m[0].length);
- console.log('proxy:', url, '->', dest);
- return {
- url: path,
- dest: dest
- };
- }
-}
-
-exports.urls = function (urls) {
- // This is the entry point for our middleware.
- // 'matchers' is the array of URL matchers, as mentioned above.
- var matchers = [];
- for (var url in urls) {
- // Call the 'matcher' function above, and store the resulting closure.
- matchers.push(matcher(url, urls[url]));
- }
-
- // This closure is returned as the request handler.
- return function (req, res, next) {
- //
- // in node-http-proxy middlewares, `proxy` is the prototype of `next`
- // (this means node-http-proxy middlewares support both the connect API (req, res, next)
- // and the node-http-proxy API (req, res, proxy)
- //
- var proxy = next;
- for (var k in matchers) {
- // for each URL matcher, try the request's URL.
- var m = matchers[k](req.url);
- // If it's a match:
- if (m) {
- // Replace the local URL with the destination URL.
- req.url = m.url;
- // If routing to a server on another domain, the hostname in the request must be changed.
- req.headers.host = m.host;
- // Once any changes are taken care of, this line makes the magic happen.
- proxy.proxyRequest(req, res, m.dest);
- }
- }
- }
-}
//
// Now we set up our proxy.
@@ -103,7 +37,7 @@ httpProxy.createServer(
// This is where our middlewares go, with any options desired - in this case,
// the list of routes/URLs and their destinations.
//
- exports.urls({
+ require('proxy-by-url')({
'/hello': { port: 9000, host: 'localhost' },
'/charlie': { port: 80, host: 'charlieistheman.com' },
'/google': { port: 80, host: 'google.com' }
View
59 examples/url-middleware2.js
@@ -3,71 +3,14 @@ var util = require('util'),
http = require('http'),
httpProxy = require('http-proxy'),
Store = require('./lib/store')
-//
-// This is an example of a url-routing middleware.
-// This is not intended for production use, but rather as
-// an example of how to write a middleware.
-//
-
-function matcher (url, dest) {
- // First, turn the URL into a regex.
- // NOTE: Turning user input directly into a Regular Expression is NOT SAFE.
- var r = new RegExp(url.replace(/\//, '\\/'));
- // This next block of code may look a little confusing.
- // It returns a closure (anonymous function) for each URL to be matched,
- // storing them in an array - on each request, if the URL matches one that has
- // a function stored for it, the function will be called.
- return function (url) {
- var m = r(url)
- if (!m) {
- return;
- }
- var path = url.slice(m[0].length);
- console.log('proxy:', url, '->', dest);
- return {url: path, dest: dest};
- }
-}
-
-exports.urls = function (urls) {
- // This is the entry point for our middleware.
- // 'matchers' is the array of URL matchers, as mentioned above.
- var matchers = [];
- for (var url in urls) {
- // Call the 'matcher' function above, and store the resulting closure.
- matchers.push(matcher(url, urls[url]));
- }
-
- // This closure is returned as the request handler.
- return function (req, res, next) {
- //
- // in node-http-proxy middlewares, `proxy` is the prototype of `next`
- // (this means node-http-proxy middlewares support both the connect API (req, res, next)
- // and the node-http-proxy API (req, res, proxy)
- //
- var proxy = next;
- for (var k in matchers) {
- // for each URL matcher, try the request's URL.
- var m = matchers[k](req.url);
- // If it's a match:
- if (m) {
- // Replace the local URL with the destination URL.
- req.url = m.url;
- // If routing to a server on another domain, the hostname in the request must be changed.
- req.headers.host = m.host;
- // Once any changes are taken care of, this line makes the magic happen.
- proxy.proxyRequest(req, res, m.dest);
- }
- }
- }
-}
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.
- exports.urls({
+ require('proxy-by-url')({
'/store': { port: 7531, host: 'localhost' },
'/': { port: 9000, host: 'localhost' }
})

0 comments on commit 2cf4e0a

Please sign in to comment.