Created
May 8, 2012 06:34
-
-
Save hakobera/2633058 to your computer and use it in GitHub Desktop.
router-line-exercise
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
var http = require('http'), | |
url = require('url'), | |
Router = require('router-line').Router; | |
var router = new Router(); | |
function send(res, status, contentType, body) { | |
res.writeHead(status, { 'Content-Type': contentType }); | |
res.end(body); | |
} | |
/* | |
* Return function. | |
*/ | |
router.add('GET', '/', function (req, res) { | |
res.end('index'); | |
}); | |
/* | |
* Return string. | |
*/ | |
router.add('GET', '/text', 'path'); | |
/* | |
* Return object. | |
*/ | |
router.add('GET', '/object', { message: 'hello' }); | |
/* | |
* Return function with path parameters. | |
*/ | |
router.add('GET', '/users/:user/apps/:app/:id', function (req, res, pathParams) { | |
send(res, 200, 'application/json', JSON.stringify(pathParams)); | |
}); | |
/* | |
* Return function with path parameters, include optional path parameters. | |
*/ | |
router.add('GET', '/items/:item(/type/:type)', function (req, res, pathParams) { | |
send(res, 200, 'application/json', JSON.stringify(pathParams)); | |
}); | |
/* | |
* Path parameter with querystring | |
*/ | |
router.add('GET', '/object', { message: 'hello' }); | |
var app = http.createServer(function (req, res) { | |
var uri, r, handler; | |
uri = url.parse(req.url, true); | |
r = router.route(req.method, uri.pathname); | |
if (r) { | |
req.param = function (key) { | |
return r.params[key] ? r.params[key] : uri.query[key]; | |
} | |
handler = r.value; | |
if (typeof handler === 'function') { | |
handler(req, res, r.params); | |
} else if (typeof handler === 'string') { | |
send(res, 200, 'text/plain', handler); | |
} else { | |
send(res, 200, 'application/json', JSON.stringify(handler)); | |
} | |
} else { | |
send(res, 404, 'application/json', JSON.stringify({ reason: 'This not the URL you are looking for' })); | |
} | |
}); | |
app.listen(process.env.PORT || 3000); | |
console.log('Server listen on port %d', app.address().port); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment