Skip to content

Commit 2cf4e0a

Browse files
committed
[api] refactor out middlewares from examples.
1 parent 020290a commit 2cf4e0a

File tree

5 files changed

+82
-136
lines changed

5 files changed

+82
-136
lines changed

examples/bodyDecoder-middleware.js

+1-11
Original file line numberDiff line numberDiff line change
@@ -48,17 +48,7 @@ http.createServer(new Store().handler()).listen(7531, function () {
4848
//body parser absorbs the data and end events before passing control to the next
4949
// middleware. if we want to proxy it, we'll need to re-emit these events after
5050
//passing control to the middleware.
51-
function (req, res, next) {
52-
//remove bodyParser's listeners
53-
req.removeAllListeners('data')
54-
req.removeAllListeners('end')
55-
next()
56-
process.nextTick(function () {
57-
if(req.body)
58-
req.emit('data', JSON.stringify(req.body))
59-
req.emit('end')
60-
})
61-
},
51+
require('connect-restreamer')(),
6252
function (req, res, proxy) {
6353
//if your posting an obect which contains type: "insult"
6454
//it will get redirected to port 2600.

examples/lib/store.js

+67
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
2+
module.exports = Store
3+
//
4+
// just to make these example a little bit interesting,
5+
// make a little key value store with an http interface
6+
// (see couchbd for a grown-up version of this)
7+
//
8+
// API:
9+
// GET /
10+
// retrive list of keys
11+
//
12+
// GET /[url]
13+
// retrive object stored at [url]
14+
// will respond with 404 if there is nothing stored at [url]
15+
//
16+
// POST /[url]
17+
//
18+
// JSON.parse the body and store it under [url]
19+
// will respond 400 (bad request) if body is not valid json.
20+
//
21+
// TODO: cached map-reduce views and auto-magic sharding.
22+
//
23+
24+
25+
26+
function Store () {
27+
this.store = {}
28+
}
29+
Store.prototype = {
30+
get: function (key) {
31+
return this.store[key]
32+
},
33+
set: function (key, value) {
34+
return this.store[key] = value
35+
},
36+
handler:function () {
37+
var store = this
38+
return function (req, res) {
39+
function send (obj, status) {
40+
res.writeHead(200 || status,{'Content-Type': 'application/json'})
41+
res.write(JSON.stringify(obj) + '\n')
42+
res.end()
43+
}
44+
var url = req.url.split('?').shift()
45+
if(url === '/') {
46+
console.log('get index')
47+
return send(Object.keys(store.store))
48+
} else if(req.method == 'GET') {
49+
var obj = store.get (url)
50+
send(obj || {error: 'not_found', url: url}, obj ? 200 : 404)
51+
} else {
52+
//post: buffer body, and parse.
53+
var body = '', obj
54+
req.on('data', function (c) { body += c})
55+
req.on('end', function (c) {
56+
try {
57+
obj = JSON.parse(body)
58+
} catch (err) {
59+
return send (err, 400)
60+
}
61+
store.set(url, obj)
62+
send({ok: true})
63+
})
64+
}
65+
}
66+
}
67+
}

examples/package.json

+12
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
{
2+
"name": "http-proxy-examples"
3+
, "description": "packages required to run the examples"
4+
, "version": "0.0.0"
5+
, "dependencies": {
6+
"connect": "1.6"
7+
, "connect-gzip": "0.1"
8+
, "connect-jsonp": "0.0.5"
9+
, "connect-restreamer": "1"
10+
, "proxy-by-url": "0.0.0"
11+
}
12+
}

examples/url-middleware.js

+1-67
Original file line numberDiff line numberDiff line change
@@ -28,72 +28,6 @@ var util = require('util'),
2828
colors = require('colors'),
2929
http = require('http'),
3030
httpProxy = require('http-proxy');
31-
32-
//
33-
// This is an example of a url-routing middleware.
34-
// This is not intended for production use, but rather as
35-
// an example of how to write a middleware.
36-
//
37-
38-
function matcher (url, dest) {
39-
//
40-
// First, turn the URL into a regex.
41-
// NOTE: Turning user input directly into a Regular Expression is NOT SAFE.
42-
//
43-
var r = new RegExp(url.replace(/\//, '\\/'));
44-
45-
//
46-
// This next block of code may look a little confusing.
47-
// It returns a closure (anonymous function) for each URL to be matched,
48-
// storing them in an array - on each request, if the URL matches one that has
49-
// a function stored for it, the function will be called.
50-
//
51-
return function (url) {
52-
var m = r(url)
53-
if (!m) {
54-
return;
55-
}
56-
var path = url.slice(m[0].length);
57-
console.log('proxy:', url, '->', dest);
58-
return {
59-
url: path,
60-
dest: dest
61-
};
62-
}
63-
}
64-
65-
exports.urls = function (urls) {
66-
// This is the entry point for our middleware.
67-
// 'matchers' is the array of URL matchers, as mentioned above.
68-
var matchers = [];
69-
for (var url in urls) {
70-
// Call the 'matcher' function above, and store the resulting closure.
71-
matchers.push(matcher(url, urls[url]));
72-
}
73-
74-
// This closure is returned as the request handler.
75-
return function (req, res, next) {
76-
//
77-
// in node-http-proxy middlewares, `proxy` is the prototype of `next`
78-
// (this means node-http-proxy middlewares support both the connect API (req, res, next)
79-
// and the node-http-proxy API (req, res, proxy)
80-
//
81-
var proxy = next;
82-
for (var k in matchers) {
83-
// for each URL matcher, try the request's URL.
84-
var m = matchers[k](req.url);
85-
// If it's a match:
86-
if (m) {
87-
// Replace the local URL with the destination URL.
88-
req.url = m.url;
89-
// If routing to a server on another domain, the hostname in the request must be changed.
90-
req.headers.host = m.host;
91-
// Once any changes are taken care of, this line makes the magic happen.
92-
proxy.proxyRequest(req, res, m.dest);
93-
}
94-
}
95-
}
96-
}
9731

9832
//
9933
// Now we set up our proxy.
@@ -103,7 +37,7 @@ httpProxy.createServer(
10337
// This is where our middlewares go, with any options desired - in this case,
10438
// the list of routes/URLs and their destinations.
10539
//
106-
exports.urls({
40+
require('proxy-by-url')({
10741
'/hello': { port: 9000, host: 'localhost' },
10842
'/charlie': { port: 80, host: 'charlieistheman.com' },
10943
'/google': { port: 80, host: 'google.com' }

examples/url-middleware2.js

+1-58
Original file line numberDiff line numberDiff line change
@@ -3,71 +3,14 @@ var util = require('util'),
33
http = require('http'),
44
httpProxy = require('http-proxy'),
55
Store = require('./lib/store')
6-
//
7-
// This is an example of a url-routing middleware.
8-
// This is not intended for production use, but rather as
9-
// an example of how to write a middleware.
10-
//
11-
12-
function matcher (url, dest) {
13-
// First, turn the URL into a regex.
14-
// NOTE: Turning user input directly into a Regular Expression is NOT SAFE.
15-
var r = new RegExp(url.replace(/\//, '\\/'));
16-
// This next block of code may look a little confusing.
17-
// It returns a closure (anonymous function) for each URL to be matched,
18-
// storing them in an array - on each request, if the URL matches one that has
19-
// a function stored for it, the function will be called.
20-
return function (url) {
21-
var m = r(url)
22-
if (!m) {
23-
return;
24-
}
25-
var path = url.slice(m[0].length);
26-
console.log('proxy:', url, '->', dest);
27-
return {url: path, dest: dest};
28-
}
29-
}
30-
31-
exports.urls = function (urls) {
32-
// This is the entry point for our middleware.
33-
// 'matchers' is the array of URL matchers, as mentioned above.
34-
var matchers = [];
35-
for (var url in urls) {
36-
// Call the 'matcher' function above, and store the resulting closure.
37-
matchers.push(matcher(url, urls[url]));
38-
}
39-
40-
// This closure is returned as the request handler.
41-
return function (req, res, next) {
42-
//
43-
// in node-http-proxy middlewares, `proxy` is the prototype of `next`
44-
// (this means node-http-proxy middlewares support both the connect API (req, res, next)
45-
// and the node-http-proxy API (req, res, proxy)
46-
//
47-
var proxy = next;
48-
for (var k in matchers) {
49-
// for each URL matcher, try the request's URL.
50-
var m = matchers[k](req.url);
51-
// If it's a match:
52-
if (m) {
53-
// Replace the local URL with the destination URL.
54-
req.url = m.url;
55-
// If routing to a server on another domain, the hostname in the request must be changed.
56-
req.headers.host = m.host;
57-
// Once any changes are taken care of, this line makes the magic happen.
58-
proxy.proxyRequest(req, res, m.dest);
59-
}
60-
}
61-
}
62-
}
636

647
http.createServer(new Store().handler()).listen(7531)
658

669
// Now we set up our proxy.
6710
httpProxy.createServer(
6811
// This is where our middlewares go, with any options desired - in this case,
6912
// the list of routes/URLs and their destinations.
70-
exports.urls({
13+
require('proxy-by-url')({
7114
'/store': { port: 7531, host: 'localhost' },
7215
'/': { port: 9000, host: 'localhost' }
7316
})

0 commit comments

Comments
 (0)