1.0.1 • Published 9 years ago

rooster v1.0.1

Weekly downloads
3
License
MIT
Repository
github
Last release
9 years ago

rooster

Code Climate Test Coverage

A tiny tool to route HTTP requests with path parameters.

use:
var http = require("http");
var rooster = require("rooster");

// route parameters are between {curlybraces}
var routes = {
 "GET /": function (req, res) {
    res.writeHead(200, {"Content-Type": "text/plain"});
    res.write("HOME");
    res.end();
 },
 "GET /articles/{article}": function (req, res) {
    res.writeHead(200, {"Content-Type": "text/plain"});
    res.write("you are looking at article: " + req.params.article);
    res.end();
 }
}

// add routes with addRoutes
rooster.addRoutes(routes);

// override the built-in handler for when route doesn't exist
rooster.addDefault(function (req, res) {
  res.writeHead(404);
  res.write("Not found!");
  res.end();
});

var server = http.createServer(function (req, res) {

  // route the request
  rooster.route(req, res);
});

server.listen(4444);

console.log("listening on 4444");

api

rooster exposes 3 very simple methods

addRoutes(routes)

addRoutes is a configuration method for adding routes to rooster

routes - an object of paths and handlers e.g:

var routes = {
  "GET /": function (req, res) {...},
  "GET /articles/{article}": function (req, res) {
    res.writeHead(200);
    res.write(req.params.article);
    res.end();
  }
}

rooster.addRoutes(routes);

Add routes can be called multiple times and, each time, the new routes will be ADDED rather than the old ones being overwritten.

Path parameters are defined within {curly-braces} and are available on the request object through req.params.

For example, if the route "GET /articles/{article}" is matched with a GET request to "/articles/13", the request object will look like this:

{
  path: "GET /articles/13",
  params: {
    article: "13"
  },
  ...
}

addDefault(handler)

addRoutes is a configuration method for adding routes to rooster

handler(req, res) - a cb for when requests are made to undefined paths

  • handler(req, res) takes 2 arguments:

    • req - the HTTP request object
    • res - the HTTP response object

e.g:

rooster.addDefault(function (req, res) {

  res.writeHead(404);
  res.write("Not found!");
  res.end();
});

route(req, res)

route is the routing method that will match a request against one of the predefined routes

req - the HTTP request object

res - the HTTP request object

e.g:

var server = http.createServer(function (req, res) {

  // route the request
  rooster.route(req, res);
});

note

rooster is build ontop of overalls so check it out for more documentation.

license

MIT