-
Notifications
You must be signed in to change notification settings - Fork 4
SimpleRouter
The SimpleRouter is the most basic of router objects. It simply finds the first route that matches the request.url string.
To create a simple router, use the following syntax:
var router = new fw.SimpleRouter(friendlyname);
The friendlyname arg is an optional string, and only really used for console logging purposes.
Adding routes is done using the addRoute() method:
router.addRoute(path, stack, destination);
Where path is a string that matches a route, such as "/images", stack is a Fastworks.js Stack object, and destination is a function which accepts the usual request and response arguments.
Paths are matched on a first added basis, so if you added "/" as your first path, no additional routes will be matched since "/" effectively matches all routes.
Creating a server is done using the createServer() method:
router.createServer(graceful, port, hostname, backlog, callback);
Note that none of these options are required, if none are specified, then all the router will do is create the server, you will need to call the listen() method on it as well.
If you specify the port, then all the remaining arguments are passed to the listen() method.
If your server supports the Fuser command, then the graceful option can be set to true, and the router will attempt to terminate any other apps on the same port before trying itself. It will also gracefully exit if sent a termination signal itself, closing the port and then serving any remaining connections before quitting.
For a secure https server, use the matching createSecureServer() method:
createSecureServer(graceful, options, port, hostname, backlog, callback);
The graceful argument is as before, the options is passed to the https server. If you specify a port then listen() will be called automatically.
If you want to start the server listening, then you can use the listen() method.
listen(graceful, port, hostname, backlog, callback);
graceful is as mentioned before, the other arguments are passed to the http.listen() or https.listen() methods respectively.
This example creates a simple router and adds routes for a few static paths, and the root path. All these routes are sent through the yourstack Stack to the yourfunc Function.
var router = new fw.SimpleRouter("My First WebApp");
router.addRoute("/images", yourstack, yourfunc);
router.addRoute("/styles", yourstack, yourfunc);
router.addRoute("/scripts", yourstack, yourfunc);
router.addRoute("/", yourstack, yourfunc);
router.listen(true, 8080);
function yourfunc(request, response)
{
response.writeHead(200, { "Content-Type": "text/plain");
response.end("Wibble!");
}