Commit 2cf4e0a9 authored by Dominic Tarr's avatar Dominic Tarr

[api] refactor out middlewares from examples.

parent 020290a1
......@@ -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.
......
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})
})
}
}
}
}
{
"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
......@@ -29,72 +29,6 @@ var util = require('util'),
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' }
......
......@@ -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' }
})
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment