Created
December 18, 2011 14:55
-
-
Save Raynos/1493631 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| 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); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This code fails if you do not enter a url parameter. You need to check if
parsedUrl.query.urlis defined before continuing with call toexpand(urlToExpand, writeResponse);