HttpHandler
that implement various useful handlers, such as a static response handler,
or a conditional handler that complements one handler with another.
The factory method of(int, Headers, String) provides a
means to create handlers with pre-set static response state. For example, a
jsonHandler that always returns 200 with the same json:
HttpHandlers.of(200,
Headers.of("Content-Type", "application/json"),
Files.readString(Path.of("some.json")));
or a notAllowedHandler that always replies with 405 -
Method Not Allowed, and indicates the set of methods that are allowed:
HttpHandlers.of(405, Headers.of("Allow", "GET"), "");
The functionality of a handler can be extended or enhanced through the
use of handleOrElse,
which allows to complement a given handler. For example, complementing a
jsonHandler with notAllowedHandler:
Predicate<Request> IS_GET = r -> r.getRequestMethod().equals("GET");
var handler = HttpHandlers.handleOrElse(IS_GET, jsonHandler, notAllowedHandler);
The above handleOrElse handler offers an if-else like construct;
if the request method is "GET" then handling of the exchange is delegated to
the jsonHandler, otherwise handling of the exchange is delegated to
the notAllowedHandler.
| Access | Constructor and Description |
|---|---|
| private |
| Modifier and Type | Method and Description |
|---|---|
| public static HttpHandler | Returns: a handlera request predicate handlerTest, HttpHandler a conditional handler handler, HttpHandler a fallback handler fallbackHandler)Complements a conditional |
| public static HttpHandler |
| HttpHandlers | back to summary |
|---|---|
| private HttpHandlers() | |
| handleOrElse | back to summary |
|---|---|
| public static HttpHandler handleOrElse(Predicate<Request> handlerTest, HttpHandler handler, HttpHandler fallbackHandler) Complements a conditional This method creates a handleOrElse handler; an if-else like
construct. Exchanges who's request matches the Example of a nested handleOrElse handler:
The h3 handleOrElse handler delegates handling of the exchange to
SomeDigestHandler if the "Want-Digest" request header is present
and the request method is GET, otherwise it delegates handling of
the exchange to the h2 handler. The h2 handleOrElse
handler, in turn, delegates handling of the exchange to SomeGetHandler if the request method is GET, otherwise it
delegates handling of the exchange to the h1 handler. The h1 handler handles all exchanges that are not previously delegated to
either SomeGetHandler or SomeDigestHandler.
| |
| of | back to summary |
|---|---|
| public static HttpHandler of(int statusCode, Headers headers, String body) Returns an This method creates a handler that reads and discards the request body before it sets the response state and sends the response.
| |