273. Complementing a conditional HttpHandler with another handler
Let’s assume that we want to choose between two HttpHandler
instances based on a condition. For instance, for all GET
requests, we want to use the following well-known HttpHandler
:
HttpHandler fileHandler = SimpleFileServer.createFileHandler(
Path.of("./docs").toAbsolutePath());
For all other requests, we want to use an HttpHandler
that always returns the same resource (for instance, the text No data available). Defining a HttpHandler
that always returns the same code and resource (so, a canned response) can be done via the HttpHandlers.of(int statusCode, Headers headers, String body)
method as in the following example:
HttpHandler complementHandler = HttpHandlers.of(200,
Headers.of("Content-Type", "text/plain"),
"No data available");
In addition, the HttpHandler
class exposes a method that can decide between two HttpHandler
instances based...