@@ -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' }
0 commit comments