From 2cf4e0a9e6c78dfd093c098fc87100ae71bc9450 Mon Sep 17 00:00:00 2001 From: Dominic Tarr Date: Sat, 30 Jul 2011 20:00:24 +1000 Subject: [PATCH] [api] refactor out middlewares from examples. --- examples/bodyDecoder-middleware.js | 12 +----- examples/lib/store.js | 67 +++++++++++++++++++++++++++++ examples/package.json | 12 ++++++ examples/url-middleware.js | 68 +----------------------------- examples/url-middleware2.js | 59 +------------------------- 5 files changed, 82 insertions(+), 136 deletions(-) create mode 100644 examples/lib/store.js create mode 100644 examples/package.json diff --git a/examples/bodyDecoder-middleware.js b/examples/bodyDecoder-middleware.js index ec10db3..180372f 100644 --- a/examples/bodyDecoder-middleware.js +++ b/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. diff --git a/examples/lib/store.js b/examples/lib/store.js new file mode 100644 index 0000000..8144b13 --- /dev/null +++ b/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}) + }) + } + } + } +} diff --git a/examples/package.json b/examples/package.json new file mode 100644 index 0000000..16af680 --- /dev/null +++ b/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" + } +} \ No newline at end of file diff --git a/examples/url-middleware.js b/examples/url-middleware.js index 920a477..669a73e 100644 --- a/examples/url-middleware.js +++ b/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' } diff --git a/examples/url-middleware2.js b/examples/url-middleware2.js index c59acfc..95dfef4 100644 --- a/examples/url-middleware2.js +++ b/examples/url-middleware2.js @@ -3,63 +3,6 @@ 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) @@ -67,7 +10,7 @@ http.createServer(new Store().handler()).listen(7531) 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' } })