Taking advantage of unique D features
In the previous chapters, each application initialized routes and associated them with the handler functions or delegates. There are two shortcomings: you have to type a lot, and there is a certain distance between the places where the route is initialized and the handler is defined.
For sure, we can do better. Let's assume that the handler functions are all methods of an object:
class WebApp { void getIndex(HTTPServerRequest req, HTTPServerResponse res) { /* ... */ } void postNote(HTTPServerRequest req, HTTPServerResponse res) { /* ... */ } }
Then, you can perform the following functions:
The route and HTTP method can be derived from the method name
User-defined attributes can be used to associate a route with a method, set up an error handler, require authentication, and so on
This is possible with D at compile time! With compile-time reflection, you can enumerate all the methods of an object. Then, you can derive a route from the method name...