Skip to content

Instantly share code, notes, and snippets.

@Raynos
Created December 18, 2011 14:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Raynos/1493631 to your computer and use it in GitHub Desktop.
Save Raynos/1493631 to your computer and use it in GitHub Desktop.
var http = require('http'),
url = require('url');
var server = http.createServer(onRequest)
server.listen(8888);
function onRequest(request, response) {
var parsedUrl = url.parse(request.url, true),
urlToExpand = parsedUrl.query.url;
expand(urlToExpand, writeResponse);
function writeResponse(error, newUrl) {
if (error) {
response.writeHead(500, { 'Content-Type': 'text/plain'});
return response.end(error.message);
}
response.writeHead(200, { 'Content-Type': 'text/plain'});
response.end(newUrl);
}
}
function expand(urlToParse, callback) {
var short = url.parse(urlToParse);
var options = {
host: short.hostname,
port: 80,
path: short.pathname
};
var clientRequest = http.get(options, extractRealURL);
clientRequest.on("error", forwardError);
function extractRealURL(res) {
callback(null, res.headers.location);
}
function forwardError(error) {
callback(err);
}
}
@wavesailor
Copy link

This code fails if you do not enter a url parameter. You need to check if parsedUrl.query.url is defined before continuing with call to expand(urlToExpand, writeResponse);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment