Skip to content

HTTP

The HTTP layer is the same contract in two implementations: Java (framework-http, with framework-http-jetty running Jetty 12 core handlers on virtual threads) and Go (package httpfw on net/http and encoding/json/v2). The behaviour a client sees is identical. The normative text is the HTTP specification; typed operations and the OpenAPI document are on their own page.

Application code depends on the HTTP types only (Routes, Request, Response, validation, errors). There is no Servlet API, no TLS (terminate in front), no HTTP/2 and no response compression in the server itself. Sessions, the SPA and OpenAPI are their own pages.

In Java, framework-http pulls in framework-core and Jackson and nothing else, so an application that only wants HTTP (an ingestor with no database) does not get the write path, the database module or the driver. The build enforces it with a banned-dependencies rule.

List JettyHttpModule among your modules, last. Routes are registered in each module’s boot; the module compiles the route table and opens the port in its own started hook, and started hooks run in module order. A module listed after Jetty would run its started work with the port already open, so a request could arrive early.

App.builder()
.module(new DatabaseModule())
.module(new OutboxModule())
.module(new UseCaseModule())
.module(new OrdersModule())
.module(new OrdersHttpModule())
.module(new JettyHttpModule())
.shutdownHook(true)
.start();

The module provides Routes and HttpServer (port() returns the bound port, which matters when http.port is 0). Register routes in boot, never register:

@Override
public void boot(App app) {
Routes routes = app.get(Routes.class).forModule(id());
routes.post("/orders", this::create, RouteOptions.requiresContext());
}

forModule(id) attributes registrations to your module in start-up errors. Registering after the server has started listening throws IllegalStateException.

routes.get("/orders/{id}", orders::show);
routes.post("/orders", orders::create);
routes.add(Method.PUT, "/orders/{id}", handler, RouteOptions.requiresContext());

get, post, put, patch, delete and add(Method, ...), each with and without RouteOptions. A Handler is Response handle(Request request) throws Exception.

The matching rules are the same in both:

  • Methods: GET HEAD POST PUT PATCH DELETE OPTIONS. HEAD is answered from GET, with the body dropped (Go sends the length the body would have had), unless a HEAD route exists.
  • A pattern is segments separated by /. A segment is a literal or {name} (name is [a-z][A-Za-z0-9]*), matching one non-empty segment. No wildcards, regular expressions or optional segments.
  • A trailing slash is a different path. Nothing redirects or cleans a path.
  • Literals beat parameters at the same position, so /orders/new wins over /orders/{id}.
  • The path is split first and each segment is percent-decoded after, so %2F stays inside its segment. A malformed escape is 400 VALIDATION.
  • Duplicate routes fail start-up (same method and shape, parameter names ignored), naming both registrants.
  • No route is 404 NOT_FOUND. A path matched with another method is 405 METHOD_NOT_ALLOWED with a sorted Allow. OPTIONS on a known path without an OPTIONS route is 204 with Allow.
  • Route patterns are logged at INFO at start-up, one line each.

Every request is counted in fw_http_server_requests_total and timed in fw_http_server_request_duration_seconds, labelled by the route pattern ((spa) or <unmatched> where there is none), never the path. See background work and metrics.

Request is an immutable view.

Method Returns
method(), path(), rawQuery(), contentLength() request line parts; -1 when no length is declared
pathParam(name), pathInt(name), pathLong(name) a path parameter. An undeclared name is IllegalArgumentException, a bad number a ValidationException
query(name), queries(name) the first value or null; all values
queryRequired, queryInt(name, default), queryLong, queryBool, queryEnum(name, Class, default) typed query parameters. A bad value is a ValidationException naming the parameter
header(name), headers(name) case-insensitive
headers() every header by lower-case name (unmodifiable), for code that passes headers on
body(), bodyBytes(), bodyText() the raw body, limited by http.max-body-bytes or the route’s own limit
json(Validator<T>) decode and validate a JSON body
context() the resolved Context. IllegalStateException on a route without requiresContext
correlationId() the request’s correlation id
attribute(Key), attribute(Key, value) typed values for middleware to pass on. Make keys with Request.Key.of("user", String.class)

Response is a value built with static factories and fluent headers:

Response.ok(Map.of("a", 1)); // 200 JSON
Response.json(201, Map.of("orderId", id));
Response.text(200, "pong");
Response.html(200, "<p>hi</p>");
Response.noContent();
Response.bytes(200, "application/pdf", bytes);
Response.redirect(location); // 302, no body
Response.seeOther(location); // 303, no body: where a browser goes after a form post
Response.stream(200, "text/event-stream", out -> { ... });
response.header("X-Frame-Options", "DENY"); // replaces; addHeader appends

Response.json and ok take records, maps, collections or a JsonNode, not a bare String (use text). JSON is Jackson 3 and strict. Header names and values containing CR or LF fail with IllegalArgumentException.

There are no annotations and no reflection over fields. A body is a record, and its validator is an explicit function you write next to it.

record PlaceOrderBody(String customer) {
static final Validator<PlaceOrderBody> V =
Validator.of(PlaceOrderBody.class)
.field("customer", PlaceOrderBody::customer, Rules.notBlank(), Rules.maxLength(100));
}
routes.post("/orders", request -> {
PlaceOrderBody body = request.json(PlaceOrderBody.V);
// ...
});
  • request.json(validator) requires Content-Type: application/json (else 415), decodes, validates, and returns the record or throws ValidationException.
  • The decoder is strict: unknown properties are an error, null for a primitive is an error, trailing tokens and duplicate keys are errors, dates are ISO. A decode failure is one INVALID_JSON error whose message never echoes the offending value.
  • Validator collects all field errors. Nested records: .nested("address", Order::address, Address.V) gives paths like address.street.
  • Rules: notNull, notBlank, minLength, maxLength, pattern, range, size, oneOf, each(rule) (path tags[2]), valid(validator) and custom(code, message, predicate). A rule other than notNull/notBlank passes on a null value; absence is notNull’s job.

Validation codes: NOT_NULL, NOT_BLANK, TOO_SHORT, TOO_LONG, PATTERN, OUT_OF_RANGE, SIZE, NOT_ONE_OF, INVALID_JSON, and your own. A failed validation responds 400:

{"error": "VALIDATION", "message": "request is invalid",
"details": {"customer": "NOT_BLANK: must not be blank"}}

details holds the first error per field path, as "<CODE>: <message>". The error codes also have translations; see languages.

Every non-2xx response the framework produces has one envelope, content type application/json:

{"error": "<CODE>", "message": "...", "details": {"k": "v"}}

details is omitted when empty; its values are strings.

Situation Status error
malformed JSON, failed validation, bad parameter 400 VALIDATION
no or bad credentials (from a context resolver) 401 UNAUTHENTICATED
not allowed 403 the use case’s code
no route 404 NOT_FOUND
method not allowed 405 METHOD_NOT_ALLOWED
body over the limit 413 PAYLOAD_TOO_LARGE
unsupported content type 415 UNSUPPORTED_MEDIA_TYPE
server draining on shutdown 503 UNAVAILABLE
uncaught exception 500 INTERNAL (message internal error; the cause is logged with the correlation id, never returned)

In a handler you return an error Response or throw:

return HttpErrors.of(failed.error()); // any ServiceError, e.g. a UseCaseError: status by ErrorKind
return HttpErrors.error(409, "TAKEN", "That name is taken.");
throw new HttpException(404, "NO_SUCH_ORDER", "There is no such order.");

HttpErrors.of(...) takes a ServiceError, a small interface in framework-core (httpStatus(), code(), message(), details()). The write path’s UseCaseError implements it, and any other module’s error value can. HttpErrors also has validation, unauthenticated, forbidden and notFound. ValidationException is an HttpException with status 400; the error-mapping middleware turns a thrown HttpException into the envelope.

The fixed middleware cannot be removed. Outermost first: correlation id, error mapping, access log (method, route pattern, status, duration, correlation id; never a query string or a body). Yours runs inside those. On a route that requires a context, application middleware runs after context resolution.

One abstraction, Middleware<I, O> in io.flowcatalyst.framework.pipeline:

interface Middleware<I, O> { O handle(I input, Next<I, O> next) throws Exception; }
routes.use(
(request, next) -> {
Response response = next.handle(request);
return response.header("X-Frame-Options", "DENY");
});

Routes.use is global, in registration order. RouteOptions.with(middleware) is per route, inside the global ones. A middleware may short-circuit by returning without calling next.

Correlation id. The X-Correlation-Id request header is used when it matches [A-Za-z0-9._-]{1,100}; otherwise one is generated (an invalid supplied value is replaced, not rejected). It is echoed on every response, including errors and 404s, and is available to handlers and in the resolved Context.

http.max-body-bytes (5 MiB) applies to every route unless the route sets its own, larger or smaller. This is how an upload route accepts photos while the rest of the API stays small.

routes.post("/photo", length, RouteOptions.none().maxBodyBytes(100));
routes.bind(NOTE, r -> Outcome.ok(new Echo(r.body().text().length())), RouteOptions.none().maxBodyBytes(200));

The limit applies once the route is matched: a declared Content-Length over it is 413 PAYLOAD_TOO_LARGE before the handler runs, and reading past it is 413 too. Paths with no route, 405 answers and OPTIONS keep the global limit, and global middleware (which runs before routing) reads under the global limit. A negative or zero limit is rejected at start-up.

A route declared as requiring a context gets its Context from a context resolver, which throws a 401 UNAUTHENTICATED error when it cannot resolve. Start-up fails, naming the route, if any route requires a context and no resolver was provided.

The framework’s resolver is the auth module (AuthModule in Java, package auth in Go): every context route is authenticated by the session cookie or a platform bearer token, with CSRF rules for cookie requests and a 302 to /auth/login for HTML navigations. See sessions and login. A placeholder resolver of your own is fine in tests; see context.

For a request authenticated by a session cookie, an unsafe method (anything but GET, HEAD, OPTIONS) is checked by the sessions guard: Sec-Fetch-Site must be same-origin or none; without it Origin must equal the public base URL’s origin; with neither header the request is refused with 403 CROSS_ORIGIN_REQUEST. Then any body must be application/json or application/*+json (415 otherwise). There is no synchroniser token. Bearer requests are not checked. The full rules are in sessions and login.

A route that server-rendered pages post native forms to is declared as a form route: RouteOptions.acceptForms() in Java, httpfw.AcceptForms() in Go. The guard then also accepts application/x-www-form-urlencoded and multipart/form-data on it, after the same provenance checks. Every other route keeps the JSON-only rule, and a typed operation cannot be a form route.

In Go, httpfw.PublicFormGuard(base) is the variant for an application’s own public POST routes (a sign-up form): a request with neither header passes, and the body must still be JSON.

Both languages serve text/event-stream routes with heartbeats, Last-Event-ID replay from the application’s own log, and an end on shutdown before the drain.

EventStreams (package io.flowcatalyst.framework.http.sse; the HTTP module provides one):

EventStreams streams = app.get(EventStreams.class);
routes.get(
"/api/stores/{store}/events",
r -> streams.serve(r, e -> e.type().startsWith("pick-"), (after, limit) -> log.after(r.pathParam("store"), after, limit)),
RouteOptions.requiresContext());
// where the application learns of a committed change, for example its tail of the log table:
streams.publish(new SseEvent(row.id(), row.type(), row.payloadJson()));

publish is in-process and never blocks. Each instance publishes what its own tail of the shared log reads, so any instance serves any stream. A stream ends when the client goes, when it falls more than 256 events behind (it is sent what it held and reconnects with its last id), when the replay throws, and when closeAll() runs, which the HTTP module registers with HttpServer.beforeDrain.

An event has an id (at least 1, increasing in publish order, usually a log table’s sequence), a one-line type and text data. On the wire: id:, event:, and one data: line per line of data. A stream sends retry: 3000 first. When the client sends Last-Event-ID (or the lastEventId query parameter, for clients that cannot set the header; anything that is not a number of 0 or more counts as none), the replay is sent first, then live events, each once and in id order: the stream subscribes before it replays and skips any id already sent. Idle for http.sse.heartbeat (25 s) it sends a : ping comment. Headers: Cache-Control: no-cache and X-Accel-Buffering: no.

For pushing events to browsers and apps through a managed service rather than serving your own stream, see push.

A write sent twice runs once. This is for clients with offline queues that replay what they could not confirm. It is route middleware on a route that requires a context.

RouteOptions once = RouteOptions.requiresContext().with(Idempotency.middleware(store, clock));
routes.post("/claims", handler, once);

Stores: MemoryIdempotencyStore (one process; tests) and, in module framework-idempotency-database, IdempotencyDatabaseModule (module id http-idempotency, table fw_idempotency_keys), which migrates the default database, provides IdempotencyStore and Idempotency.Options, and runs an hourly prune loop.

.module(new DatabaseModule())
.module(new IdempotencyDatabaseModule())
// in a module's boot:
Middleware<Request, Response> once =
Idempotency.middleware(
app.get(IdempotencyStore.class), app.get(InstantSource.class), app.get(Idempotency.Options.class));
Request Answer
no Idempotency-Key header runs as it is
a key that is not 1 to 200 printable ASCII characters, or the header twice 400 IDEMPOTENCY_KEY_INVALID
a key on a request whose context has no principal 400 IDEMPOTENCY_KEY_UNSUPPORTED (it cannot be scoped to a caller)
the first request with a key (per client, principal and key) runs; a 2xx answer with a body is kept (status, Content-Type, body)
the same method, path, query and body again the kept answer, with Idempotency-Replayed: true. Other headers of the first answer are not kept
again while the first still runs waits for it (10 s) and gets its answer; 409 IDEMPOTENCY_IN_PROGRESS when the wait runs out
another request under the same key 422 IDEMPOTENCY_KEY_REUSED
the first failed (not 2xx, an exception, or a streamed body) its key is freed, so a retry does the work
the key is older than the retention taken over: the request runs again
the first never finished and took the key over 5 minutes ago taken over; the stuck one can no longer complete or free the key

A request is identified by the SHA-256 of METHOD SP path "?" query LF body. The body is read within the route’s limit and cached, so the handler reads the same bytes.

Setting Default Meaning
idempotency.retention 24h how long a key and its answer are kept
idempotency.wait 10s how long a repeat waits for the first request’s answer
idempotency.in-flight-timeout 5m how long an unfinished reservation holds its key

Off by default. Setting http.cors.allowed-origins turns it on for every response.

Setting Default
http.cors.allowed-origins empty: CORS off. Entries are scheme://host[:port] with no path, or the single entry *
http.cors.allowed-methods GET, HEAD, POST, PUT, PATCH, DELETE
http.cors.allowed-headers Content-Type, Authorization, DPoP, X-Correlation-Id, Idempotency-Key, Last-Event-ID
http.cors.exposed-headers X-Correlation-Id, Idempotency-Replayed
http.cors.max-age 10m (at most 24h in Go)
  • The middleware runs just inside the correlation id, outside the error mapping, so error answers, 404s and refusals carry the headers too.
  • A request with an allowed Origin gets Access-Control-Allow-Origin, Access-Control-Expose-Headers and Vary: Origin. Another origin gets only Vary: Origin. A request without Origin is untouched.
  • A preflight (OPTIONS with Access-Control-Request-Method) from an allowed origin asking for an allowed method and headers is 204. In Java any other preflight is 403 CORS_REFUSED. In Go the preflight is answered before the application’s middleware and the context resolver run, so it is never authenticated.
  • Credentials are never allowed. Access-Control-Allow-Credentials is never sent and there is no setting for it, so the session cookie is never usable across origins. CORS is for callers that hold a bearer token.
  • A malformed origin, method or header name fails start-up naming the setting.

For server-driven pages, the framework follows the Datastar 1.0 SDK wire format (HTTP specification section 10). In Java it is io.flowcatalyst.framework.http.datastar; in Go it is package ds in the go/ui module.

routes.get(
"/feed",
request ->
Datastar.stream(
request,
sse -> {
sse.patchElements("<div id=\"feed\">hello</div>");
sse.patchElements("<li>one</li>", PatchElementsOptions.defaults().selector("#list"));
sse.patchSignals("{\"count\":1}");
}));
  • Datastar.signals(request) returns the client’s signals as a JsonNode: the JSON in the datastar query parameter for GET, HEAD and DELETE, otherwise the JSON body. A body above 1 MiB is 413. Absent or invalid signals are a ValidationException.
  • Datastar.stream(request, events) runs your callback with a ServerSentEventGenerator and streams text/event-stream. The stream ends when the callback returns.
  • Generator methods: patchElements(html[, options]) (selector, mode, useViewTransition, namespace, eventId, retry), patchSignals(json[, options]) (onlyIfMissing, eventId, retry), remove(selector) and close(). There is no executeScript; patch a <script> element instead.
  • Writes are flushed per event. A client disconnect surfaces as the unchecked ClientDisconnectedException from the next write; let it propagate (it is logged at DEBUG).

Datastar streams are not event streams and are not ended before the drain.

The server’s settings are configuration, because they are service settings (see config and code). The module claims the http component, so any other key under http (a typo such as http.prot) fails start-up as unknown, listing the keys below.

Key Type Default
http.host string 0.0.0.0
http.port integer 8080 (0 = any free port)
http.max-body-bytes long 5242880 (5 MiB)
http.request-timeout duration 30s (idle timeout of reads and writes)
http.shutdown-grace duration falls back to app.shutdown.drain
http.metrics.enabled boolean false. When true, mounts the Prometheus endpoint
http.metrics.path string /metrics
http.metrics.bearer-token secret none. When set, scrapes need it (compared in constant time in Go). Enabling metrics without a token logs a warning in Go
http.sse.heartbeat duration 25s (Java)
http.cors.* see CORS

Registered by the module, with no authentication and no context.

  • GET /health/live always answers 200 {"status":"UP"}.
  • GET /health/ready runs the health checks and answers 200 with {"status":"UP","checks":{...}}, or 503 with DOWN or TIMED_OUT and the reason. It answers 503 from the moment shutdown begins.
  • Only critical checks decide the status code. When only informational checks are not up, the answer is 200 with top-level "status":"DEGRADED", and each informational check’s entry carries "informational": true.
{"status":"DEGRADED","checks":{"platform":{"status":"DOWN","reason":"IllegalStateException: platform unreachable","informational":true},"good":{"status":"UP"}}}

Add your own checks with the application’s health registry; see modules and lifecycle.

On shutdown the server first marks itself draining: new requests get 503 UNAVAILABLE with Connection: close, and /health/ready is down. It then runs the before-drain hooks, stops accepting, lets in-flight requests finish for up to http.shutdown-grace, and closes the rest. The server never sends a Server header or a stack trace.

A long-lived response (a stream) would hold the drain until the grace ran out, so end such responses in a before-drain hook.

HttpServer.beforeDrain(Runnable) adds an action that runs when shutdown begins. A module’s own shutdown hook is too late, because the HTTP module is listed last and so its shutdown (the drain) runs first. Actions run once, in the order added, on the stopping thread; one that throws is logged at WARN and the rest still run.

server.beforeDrain(
() -> {
drainingInHook.set(server.isDraining());
stop.set(true);
});

TestClient runs the full pipeline in-process with no socket:

Routes routes = new Routes();
routes.get("/ping", r -> Response.text(200, "pong"));
TestResponse response = TestClient.of(routes).get("/ping").header("X-Correlation-Id", "t-1").send();

TestClient.of(routes, resolver) supplies a context resolver. TestResponse has status(), header(name), body(), json(Class) and tree().

See testing.