Routing (including handlers)

To understand how the routing works, a quick introduction to the code flow is provided below:

code flow

  1. synapticloop.nanohttpd.RouteMasterServer is instantiated and listens on the defined port (default 5474), and the defined host (default 127.0.0.1). All incoming requests then invoke the RouteMaster.route method.
  2. synapticloop.nanohttpd.router.RouteMaster.route(File rootDir, IHTTPSession httpSession) is invoked for EVERY request. This will determine which router should be invoked for the incoming request. To determine which router to invoke, the following flow is followed:
    1. If the route is cached, then the router is known and is invoked.
    2. If the route is not cached, then the synapticloop.nanohttpd.router.Router.route method is invoked, which will return the assigned router
  3. synapticloop.nanohttpd.router.Router.route(IHTTPSession httpSession, StringTokenizer stringTokenizer) is invoked to determine which router should handle the incoming request. This will walk the URL path until a suitable router is found.
  4. serveResource(File rootDir, IHTTPSession httpSession) depending on which router is found, this method is invoked, and depending on the functionality of the implementation, will depend on whether Handlers are theninvoked.
  5. In the instance of the synapticloop.nanohttpd.servant.ClasspathFileServant, the handlers are then consulted as to whether they will be able to handle the request. If so, the Handler will be invoked before the Servant. Note that each implementation may work differently, and use the local file before invoking the Handler.

Wildcard routes

Wildcard routes allow you to bind a specific router to multiple URLs. The simplest example is the:

route./*=synapticloop.nanohttpd.servant.StaticFileServant

Which binds the root of the site (i.e. /) and all paths beyond it that are not bound to any other route. Contrast this with the following:

route./=synapticloop.nanohttpd.servant.StaticFileServant

Which only binds the root of the site to the StaticFileServant and no other routes.

In fact, if you only wanted to spin up a static file web server, you could use the above route (route./*=synapticloop.nanohttpd.servant.StaticFileServant) and that is all that would be needed.

To understand the different types of routers, have a look at the simple routes andRESTful routes documentation.

Handlers

Handlers are implementation specific and work on an extension basis, i.e. handlers are mapped to specific extensions. If a file exists on either the filesystem or classpath which may either be served the Servant or Handler, then the precedence from a syanpticloop convention should use the Handler first.

However: It must be noted that whilst synapticloop observes this convention, it is not a pre-requisite and other Handlers may use differing conventions and favour the local resource.