ThomasBurleson
2/2/2012 - 2:54 PM

Node HTTP-PROXY Server

Node HTTP-PROXY Server

#
# ******************************************************************************************************
#	
#   HTTP-Proxy development server
#   
#   This server listens on http://locahost:8080 and proxies requests based on partial paths.
#   
#      1)  `http://localhost:8080/api/json/`  will  be proxied to  `http://xxx.dev.yourCompany.com/api/json/`
#      2)  All other `http://localhost:8080` requests will be proxied to `http://localhost:8000`
# 
#   Developers can use the standard Node development server availabe in ../web-server.js
#   NOTE: to set the web root properly, the servers should be started in ../../app
#         e.g.
#              node ../scripts/web-server.js
#              node ../scriptes/proxy-dataservices.js
# 
#   Copyright (c) 2012 Mindspace, CodeCatalyst
#   Open source under the MIT License.
# 
# ******************************************************************************************************
# 

sys       = require( 'util' )
http      = require( 'http' )
httpProxy = require( 'http-proxy' )


API_PORT            = 80
DOCUMENT_HOST       = 'localhost'

DOCUMENT_PORT       = 8000
PROXY_SERVER_PORT   = 8080

API_HOST            = 'xxx.dev.yourCompany.com'
API_PATH_EXPRESSION = /^\/api\/json/

httpProxy.createServer( 
	( request, response, proxy ) ->
		shouldProxy = API_PATH_EXPRESSION.test( request.url )
		config      =
			host : if shouldProxy API_HOST else DOCUMENT_HOST
			port : if shouldProxy API_PORT else DOCUMENT_PORT
		
		console.log( "Proxying request to #{ request.url } to #{ config.host }:#{ config.port }." )
		
		request.headers.host = config.host
		proxy.proxyRequest( request, response, config )
		return

).listen( PROXY_SERVER_PORT )

sys.puts( "Http-Proxy Server running at http://localhost:#{PROXY_SERVER_PORT}/" );