Created
February 23, 2011 13:38
-
-
Save jeromeetienne/840439 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Callback for http_server | |
* - it handles the proxying itself | |
*/ | |
function http_server_cb(request, response){ | |
// extract path extname for the request url | |
var parsedUrl = require('url').parse(request.url, true); | |
var query = parsedUrl.query; | |
var req_url = query.url; | |
// log the event | |
console.log("proxy to "+req_url); | |
//console.dir(parsedUrl); | |
// normal http proxying | |
var host_field = require('url').parse(req_url).host.split(':'); | |
var proxy = http.createClient(host_field[1] || 80, host_field[0]) | |
var proxy_request = proxy.request(request.method, req_url, request.headers); | |
proxy_request.addListener('response', function(proxy_response) { | |
proxy_response.setEncoding('utf8'); | |
// read data from proxy_response and queue them | |
var body = ""; | |
proxy_response.addListener('data', function(chunk) { | |
//console.log("data", chunk.toString('utf8')); | |
body += chunk.toString('utf8'); | |
}); | |
// when proxy_reponse is over | |
proxy_response.addListener('end', function() { | |
console.log("end of "+req_url) | |
if( parsedUrl.pathname == "/feed" ){ | |
body = postprocessSpectatorFeed(body); | |
}else if( parsedUrl.pathname == "/feedRaw" ){ | |
}else if( parsedUrl.pathname == "/raw" ){ | |
}else if( parsedUrl.pathname == "/channels" ){ | |
}else console.assert(false); | |
// handle the jsonp escaping | |
if( query.callback ){ | |
body = query.callback + "(" + JSON.stringify(body) + ")"; | |
// update the content-length | |
proxy_response.headers['content-type'] = "text/javascript"; | |
} | |
// update the content-length | |
proxy_response.headers['content-length'] = body.length; | |
// put the header | |
response.writeHead(proxy_response.statusCode, proxy_response.headers); | |
console.log(body) | |
console.log(body.length) | |
response.end(body, 'utf8'); | |
}); | |
}); | |
request.addListener('data', function(chunk) { | |
proxy_request.write(chunk, 'utf8'); | |
}); | |
request.addListener('end', function() { | |
proxy_request.end(); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment