Handlers

Handlers allow bindings from extensions to particular functionality. The easiest way to understand this is to look at a very simple example.

Registration

To register the handler - you will need to add the following to the routemaster.properties file.

handler.xyz=synapticloop.nanohttpd.example.handler.XyzHandler
NOTE that you MUST also have a route registered to be able to invoke any handler

The code

The following code can be found in the XyzHandler.java class file.

package synapticloop.nanohttpd.example.handler;

import java.io.File;
import java.util.Map;
import java.util.Random;

import fi.iki.elonen.NanoHTTPD.IHTTPSession;
import fi.iki.elonen.NanoHTTPD.Response;
import synapticloop.nanohttpd.handler.Handler;
import synapticloop.nanohttpd.utils.HttpUtils;

public class XyzHandler extends Handler {
	private static final String XYZ_POSTFIX = ".xyz";
	private static final String ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

	@Override
	public boolean canServeUri(String uri) {
		return(uri.endsWith(XYZ_POSTFIX));
	}


	@Override
	public Response serveFile(File rootDir, String uri, Map headers, IHTTPSession session) {
		Random random = new Random(System.currentTimeMillis());
		int nextInt = random.nextInt(ALPHABET.length() -1);
		String letter = ALPHABET.substring(nextInt, nextInt + 1);
		return(HttpUtils.okResponse("XYZ handler - responded - is brought to you by the letter " + letter));
	}

}

There are two methods that need to be over-written:

  1. boolean canServeUri(String uri)
  2. Response serveFile(File rootDir, String uri, Map headers, IHTTPSession session)

Can Serve URI?

This simply returns whether this URI is able to serve the request, for this example, all URIs can be served by this Handler. There may be some instances where a URI may not be able to be handled, despite the requested extension.

Serve the file

This method returns a response object (either OK, INTERNAL SERVER ERROR, NOT FOUND etc.). In the instance of the XyzHandler this will always return a string of the form:

XYZ handler - responded - is brought to you by the letter Y

With a randomly assigned letter at the end.

For this handler, it will respond to any URI that ends with .xzy, whether or not a local file on the filesystem exists.

mime types

Routemaster will automatically send through the mimetype if it is for a known type, when it comes to handlers, routemaster will use the extension before the registered handler extension. For example: index.html.templar will return a mimetype of text/html, whilst index.txt.templar will return a mimetype of text/plain.