Skip to content

Instantly share code, notes, and snippets.

@yssk22
Created August 15, 2010 08:56
Show Gist options
  • Save yssk22/525271 to your computer and use it in GitHub Desktop.
Save yssk22/525271 to your computer and use it in GitHub Desktop.
var http = require('http'),
url = require('url');
PROXY_VIA = 'CouchProxy';
function debug(str){
console.log(str);
}
exports.proxy = function(backendUrl){
var backend = url.parse(backendUrl);
debug('setup proxy for: ' + backendUrl);
return function(req, res, next){
debug('>>> ' + req.method + ' ' + req.url);
var db = http.createClient(backend.port, backend.hostname);
var body = null;
// send a request body
if( req.method == 'POST' || req.method == 'PUT' ){
body = JSON.stringify(req.body);
req.headers['content-length'] = body.length;
}
var proxy = db.request(req.method, req.url, req.headers);
if( body ){
debug(body);
proxy.write(body);
}
proxy.end();
// connection error
proxy.connection.on('error', function(err){
debug('error: ' + err);
res.writeHead(503, {
'Content-Type': 'application/json',
'via': PROXY_VIA
});
if( req.method != 'HEAD' ){
res.write(JSON.stringify({
'error' : 'service temporary unavailable',
'reason' : 'No database found.'
}));
}
res.end('\n');
});
// get a response
proxy.on('response', function(response){
debug('<<<');
response.headers['via'] = PROXY_VIA;
res.writeHead(response.statusCode, response.headers);
response.on('data', function(chunk){
debug(chunk);
if( req.method != 'HEAD' ){
res.write(chunk, 'binary');
}
});
response.on('end', function(){
res.end();
});
});
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment