Soklet Logo

Core Concepts

Response Writing

Soklet's ResponseMarshaler prepares response representations for the client - it might be the result of a Resource Method that executed successfully which you'd like to marshal to JSON, a friendly representation of an uncaught exception that bubbled out, a custom response for an HTTP 405 Method Not Allowed, and so forth.

This approach enforces a clear separation between your business logic and the details of how data is transformed and written back to clients, which simplifies automated testing and hews to the Single Responsibility Principle.

For example, if your Resource Method looks like this:

@POST("/reverse")
public List<Integer> reverse(@RequestBody List<Integer> numbers) {
  List<Integer> reversed = new ArrayList<>(numbers);
  Collections.reverse(reversed);
  return reversed;
}

You might want clients to receive a JSON response body like this:

[3,2,1]

Your ResponseMarshaler transforms the List<Integer> data into a prepared response representation: an instance of MarshaledResponse, optionally with a MarshaledResponseBody. This immutable descriptor can still be replaced by CORS composition, post-processing, HEAD handling, and transport preparation before any bytes are sent.

Writing JSON Responses

Want to see how this looks in practice? Jump to Response Marshaling.

Soklet does not dictate how to encode your data - whether you use JSON or Protocol Buffers or XML or something else is entirely up to you and your application's needs.

If a Resource Method returns an instance of Response, it is provided as-is to your ResponseMarshaler. This permits Resource Methods to explicitly specify response customizations, e.g. explicit status codes, cookies, or other headers.

// This is equivalent to the method above that returns List<Integer>.
// Returning a Response instance enables customizations
@POST("/reverse-again")
public Response reverseAgain(@RequestBody List<Integer> numbers) {
  List<Integer> reversed = new ArrayList<>(numbers);
  Collections.reverse(reversed);

  return Response.withStatusCode(200)    
    .cookies(List.of( /* any cookies you like */ ))
    .headers(Map.of( /* any headers you like */ ))
    .body(reversed)
    .build();
}

If a Resource Method returns an instance of MarshaledResponse, it supplies a prepared body without ordinary response serialization. CORS composition, configured postProcess, HEAD/bodyless handling, and transport framing still apply. See Post-Processing for the final response phase.

MarshaledResponse.withResponse(response) and fromResponse(response) copy status, headers, cookies, and an existing byte[] body. They do not serialize other logical body types; those values are omitted from the copy. A custom marshaler can use withResponse(response).body(serializedBytes) after performing its own serialization. Use the appropriate MarshaledResponse body or streaming builder directly for files, buffers, and streams.

This is useful for one-off kinds of responses, e.g. an API that normally serves up JSON but occasionally needs to serve up an image or other binary file:

// Use MarshaledResponse to serve up an image
@GET("/example-image.png")
public MarshaledResponse exampleImage() {
  Path imageFile = Path.of("/home/user/test.png");

  return MarshaledResponse.withStatusCode(200)
    .body(imageFile)
    .headers(Map.of(
      "Content-Type", List.of("image/png")
    ))
    .build();
}

Serving Files Efficiently

Want to see how file, file-channel, and pre-rendered buffer responses work? Jump to File and Buffer Responses.

Streaming Dynamic Responses

For dynamic output where the final length is not known upfront, return a MarshaledResponse with a StreamingResponseBody. See Streaming Responses.

If a Resource Method returns an instance of any other type or void or null, a Response is synthetically created by Soklet and passed along to your ResponseMarshaler.

The default marshaler rejects Path, File, ByteBuffer, InputStream, and FileChannel as logical Response.body values instead of converting the handle to text. Return a MarshaledResponse with its finite body configured for a path, buffer, or file channel; convert a File with toPath(). For an input stream, use a lazy StreamingResponseBody::fromInputStream factory and configure streamingResponseBody. See File and Buffer Responses and Streaming Body Sources.

Rejection does not read or close the object, or transfer its ownership to Soklet. A custom resource-method handler or ResponseMarshaler retains control of how it serializes logical body values.


Response Status

Final ordinary responses on the built-in HTTP server require status 200 through 599. A 1xx or out-of-range final status fails processing with HTTP 500; these responses do not provide an interim-response API.

The transport sends no body for 204 No Content, 205 Reset Content, or 304 Not Modified. A 205 always has Content-Length: 0, including for HEAD responses. A resource method returning 205 may omit its body or supply an empty string, empty byte array, or zero-length finite MarshaledResponseBody; Soklet normalizes those empty bodies to absent. A nonempty 205 resource body or a streaming body fails processing with HTTP 500. For resource methods returning 204 or 304, omit the body entirely: the existing validation rule treats even an empty string or byte array as present. Custom marshaler hooks for errors, OPTIONS, preflight, and missing routes retain their body-omission behavior for these statuses.

By default, any Resource Method that executes non-exceptionally will return a 200 OK status (or 204 No Content for null values and void return types).

@GET("/status")
public String status() {
  return "Hello!";
}

To test:

% curl -i 'http://localhost:8080/status'
HTTP/1.1 200 OK
Content-Length: 6
Content-Type: text/plain; charset=UTF-8
Date: Sun, 21 Mar 2024 16:19:01 GMT

Hello!

To specify a custom status, your Resource Method should return a Response. Use the Response::withStatusCode builder method to instantiate.

@POST("/widgets")
public Response createWidget(WidgetService widgetService) {
  // Hypothetical widget service
  widgetService.createWidget();

  // Reply with HTTP 201 Created
  return Response.withStatusCode(201)
    .body("Widget created.")
    .build();
}

To test:

% curl -i -X POST 'http://localhost:8080/widgets'
HTTP/1.1 201 Created
Content-Length: 15
Content-Type: text/plain; charset=UTF-8
Date: Sun, 21 Mar 2024 16:19:01 GMT

Widget created.

There are other scenarios in which response statuses may be set. Examples include:

Generally, your Response Marshaling configuration makes the determination of what status will ultimately go over the wire.

Response Headers

The built-in HTTP transport owns finite-response framing: it computes Content-Length, controls Connection, and removes application Transfer-Encoding, Keep-Alive, Proxy-Connection, TE, Trailer, and fields nominated by Connection. A valid single decimal representation length supplied by final HEAD marshaling is preserved when its status allows it. The default HEAD marshaler computes that length from the response body. A bodyless explicit @HEAD method may supply one valid nonnegative decimal Content-Length; the default marshaler preserves it when the status permits it. If a finite body is present, its length takes precedence. A custom HeadHandler can supply the final representation length. A PostProcessor runs before HEAD marshaling, so its length header may be replaced by the later HEAD projection. See the HTTP HEAD example. A validated 426 Upgrade Required response can advertise Upgrade with Connection: Upgrade; other ordinary responses cannot switch protocols.

To specify custom response headers, your Resource Method should return a Response constructed with the Response.Builder::headers method.

@GET("/headers")
public Response headers() {
  return Response.withStatusCode(200)
    .headers(Map.of("One", List.of("Two", "Three")))
    .body("Hello, world")
    .build();
}

Soklet writes one line for each value, in the supplied list order (One: Two, then One: Three).

$ curl -i 'http://localhost:8080/headers'
HTTP/1.1 200 OK
Content-Length: 12
Content-Type: text/plain; charset=UTF-8
Date: Sun, 21 Mar 2024 16:19:01 GMT
One: Two
One: Three

Hello, world

Header values are written in list order. Repeated values are preserved, including identical values.

@GET("/headers/ordered")
public Response headersOrdered() {
  return Response.withStatusCode(200)
    .headers(Map.of(
      "One", List.of("Two", "Three", "Two"),
      "Four", List.of("5", "6")
    ))
    .body("Hello, world")
    .build();
}

The header values are then written as Two, Three, Two and 5, 6, each on its own header line.

% curl -i 'http://localhost:8080/headers/ordered'
HTTP/1.1 200 OK
Content-Length: 12
Content-Type: text/plain; charset=UTF-8
Date: Sun, 21 Mar 2024 16:19:01 GMT
Four: 5
Four: 6
One: Two
One: Three
One: Two

Hello, world

Parameterized Header Values

Some response headers use a special "value; param=value" format (for example, Content-Disposition and Content-Type), which are more nuanced than they might first appear.

Soklet provides ParameterizedHeaderValue to build these safely with strict RFC encoding rules. Invalid tokens or control characters will fail fast, preventing you from creating out-of-spec responses.

All 3 parameter types are supported:

@GET("/resume.pdf")
public MarshaledResponse resume() {
  Path resumeFile = Path.of("/home/user/resume.pdf");

  // Construct our "attachment=..." Content-Disposition value
  String contentDisposition = ParameterizedHeaderValue.withName("attachment")
    .quotedParameter("filename", "resume.pdf")
    .rfc8187Parameter("filename", "résumé.pdf")
    .stringValue();

  return MarshaledResponse.withStatusCode(200)
    .body(resumeFile)
    .headers(Map.of(
      "Content-Disposition", List.of(contentDisposition),
      "Content-Type", List.of("application/pdf")
    ))
    .build();
}

The resulting Content-Disposition header value is:

attachment; filename="resume.pdf"; filename*=UTF-8''r%C3%A9sum%C3%A9.pdf

Which Type[s] Should I Use?

Use the narrowest one that fits your data:

  • tokenParameter for strict RFC 9110 tokens (ASCII only, no spaces, no quotes). Good for values like charset=UTF-8.
  • quotedParameter for ASCII values that may include spaces or punctuation; Soklet will quote and escape as needed.
  • rfc8187Parameter for non-ASCII values; Soklet encodes UTF-8 and percent-escapes it per RFC 8187.

For legacy compatibility (notably Content-Disposition filenames), send both a quotedParameter with a safe ASCII fallback and an rfc8187Parameter with the full Unicode value.

Modern clients prefer filename*, while older ones only understand filename.

Response Cookies

To specify response cookies, your Resource Method should return a Response constructed with a set of ResponseCookie.

@GET("/current-date")
public Response currentDate(@QueryParameter ZoneId timeZone) {
  LocalDate date = LocalDate.now(timeZone);
  Instant now = Instant.now();

  return Response.withStatusCode(200)
    .cookies(List.of(
      ResponseCookie.with("now", String.valueOf(now))
        .build(),
      ResponseCookie.with("lastDate", date.toString())
        .httpOnly(true)
        .secure(true)
        .path("/")
        .maxAge(Duration.ofMinutes(5))
        .sameSite(SameSite.LAX)
        .build()
      ))
    .build();
}

To test:

% curl -i 'http://localhost:8080/current-date?timeZone=America/New_York'
HTTP/1.1 200 OK
Content-Length: 0
Date: Sun, 21 Mar 2024 16:19:01 GMT
Set-Cookie: now=2024-04-21T16:19:01.128027Z
Set-Cookie: lastDate=2024-04-21; Path=/; Max-Age=300; Secure; HttpOnly; SameSite=Lax

To delete a cookie, expire it with zero Max-Age and match the Path and Domain used when it was created. The example above uses Path / and no Domain. A null value alone only clears the cookie's contents; it does not expire it. See the cookie deletion rules.

return Response.withStatusCode(200)
  .cookies(List.of(ResponseCookie.with("lastDate", "")
    .path("/")
    .maxAge(Duration.ZERO)
    .secure(true)
    .httpOnly(true)
    .sameSite(SameSite.LAX)
    .build()))
  .build();

Soklet supports the full Set-Cookie attribute surface, including Expires, Priority, and Partitioned:

ResponseCookie sessionCookie = ResponseCookie.with("session", token)
  .expires(Instant.now().plus(Duration.ofDays(7)))
  .priority(Priority.HIGH)
  .partitioned(true)
  .secure(true)
  .sameSite(SameSite.NONE)
  .path("/")
  .build();

Validation

Soklet validates ResponseCookie instances at construction time and fails fast when invalid. For example:

  • Max-Age must be >= 0
  • SameSite=None requires Secure
  • Partitioned requires Secure, SameSite=None, and Path=/
  • __Secure- cookie names require Secure
  • __Host- cookie names require Secure, Path=/, and no Domain

If you need to parse existing Set-Cookie headers, ResponseCookie::fromSetCookieHeaderRepresentation understands Expires, SameSite, Priority, and Partitioned along with the standard attributes.

Cookie Expires parsing uses the fixed cookie-year rule: two-digit years 00–69 mean 2000–2069, and 70–99 mean 1970–1999. Weekday text does not affect expiry. Only an explicitly supplied Max-Age is retained; zero or negative values normalize to zero for deletion, while a positive value remains authoritative even when Expires is present. An Expires-only cookie keeps its absolute expiry without gaining a synthesized Max-Age. This differs from HTTP conditional dates, whose obsolete two-digit years use a moving fifty-year window.

The response cookie construct is provided as a convenience shorthand so you do not have to compute values for Set-Cookie headers yourself. However, if you prefer, you can write the headers directly - see Response Headers for details.

It is unusual but legal to specify multiple response cookies with the same name. Soklet supports this functionality.

Soklet writes Set-Cookie response headers in cookie-list order, preserving repeated cookies, including identical cookies.

@GET("/double-date")
public Response doubleDate(@QueryParameter ZoneId timeZone) {
  LocalDate date = LocalDate.now(timeZone);
  Instant now = Instant.now();
  Instant later = now.plus(1, ChronoUnit.MINUTES);

  // Explicitly order cookies, which happen to have the same name.
  // Here, put "later" before "now"
  List<ResponseCookie> cookies = new ArrayList<>();
  cookies.add(ResponseCookie.with("now", String.valueOf(later)).build());
  cookies.add(ResponseCookie.with("now", String.valueOf(now)).build());

  return Response.withStatusCode(200)
    .cookies(cookies)
    .build();
}

To test:

% curl -i 'http://localhost:8080/double-date?timeZone=America/New_York'
HTTP/1.1 200 OK
Content-Length: 0
Date: Sun, 21 Mar 2024 16:19:01 GMT
Set-Cookie: now=2024-04-21T16:20:01.706488Z
Set-Cookie: now=2024-04-21T16:19:01.706488Z

Response Marshaling

Hooks are provided for these scenarios:

Normally, you'll want to provide hooks to Soklet's standard ResponseMarshaler implementation (as opposed to implementing the interface yourself) because it provides sensible defaults for things like CORS, OPTIONS, HEAD, and 404s/405s. This way, you can stay focused on how your application writes "normal" Resource Method and uncaught exception responses and let Soklet worry about the rest.

Keep It Simple

Most applications only need to provide handlers for Resource Method and Uncaught Exception scenarios.

But if you'd like to, for example, control how responses are written for HEAD requests - you have the ability to do so. See Advanced Response Marshaling.

Resource Method

This means the request was successfully matched to a Resource Method and executed without throwing an exception.

You have access to the Request, Response, and ResourceMethod that handled the request.

The default resource-method handler passes byte[] bodies through unchanged and encodes a String or another logical body's toString() using the marshaler's configured charset, UTF-8 by default. A charset declaration in Content-Type does not select a different encoder. Keep the declaration and marshaler setting consistent, pre-encode a byte[], or supply a custom resource-method handler when a response needs another encoding.

// Let's use Gson to write response body data
// See https://github.com/google/gson
final Gson GSON = new Gson();

// The request was matched to a Resource Method and executed non-exceptionally
ResourceMethodHandler resourceMethodHandler = (
  @NonNull Request request,
  @NonNull Response response,
  @NonNull ResourceMethod resourceMethod
) -> {
  // Turn response body into JSON bytes with Gson
  Object bodyObject = response.getBody().orElse(null);
  byte[] body = bodyObject == null
    ? null
    : GSON.toJson(bodyObject).getBytes(StandardCharsets.UTF_8);

  // To be a good citizen, set the Content-Type header
  Map<String, List<String>> headers = new HashMap<>(response.getHeaders());
  headers.put("Content-Type", List.of("application/json;charset=UTF-8"));

  // Tell Soklet: "OK - here is the final response data to send"
  return MarshaledResponse.withResponse(response)
    .headers(headers)
    .body(body)
    .build();
};

// Provide the default marshaler with our handler
SokletConfig config = SokletConfig.withHttpServer(
  HttpServer.fromPort(8080)
).responseMarshaler(
  ResponseMarshaler.builder()  
    .resourceMethodHandler(resourceMethodHandler)
    .build()
).build();

Having access to the ResourceMethod that handled the request lets you define processing "hints" (among other things) without warping your method's contract.

For example, we can declare a special annotation...

// An annotation that indicates 
// "include debugging information in the response"
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Debug {}

public class ExampleResource {  
  @Debug // Apply the annotation
  @GET("/example")
  public String example() {
    return "hello, world";
  }
}

...and then access it via reflection at runtime:

ResourceMethodHandler resourceMethodHandler = (
  @NonNull Request request,
  @NonNull Response response,
  @NonNull ResourceMethod resourceMethod
) -> {
  // Prepare standard response headers 
  Map<String, List<String>> headers = new HashMap<>(response.getHeaders());
  headers.put("Content-Type", List.of("application/json;charset=UTF-8"));

  // If our annotation is present, add some debug headers
  if(resourceMethod.getMethod().isAnnotationPresent(Debug.class)) {
    headers.put("X-Debug-Id", List.of(
      String.valueOf(request.getId())
    ));
    headers.put("X-Language-Tag", List.of(
      request.getLocales().get(0).toLanguageTag()
    ));
  }

  // Rest of method elided
};

References:

Uncaught Exceptions

If an exception is thrown while Soklet is processing a request, it is surfaced here so a representation of the error can be written to the response.

Soklet lets you write your applications "normally" - that is, define your own exception types and let them bubble out. There is generally no need to have your application code throw or extend Soklet-specific exceptions.

Because Soklet is responsible for converting request data to the types specified by your Resource Methods via Value Conversions, an abstract BadRequestException and its specific subclasses like IllegalQueryParameterException are available out-of-the-box.

For example, suppose your Resource Method requires a request body, but the client does not provide one. Soklet will throw a MissingRequestBodyException.

The entire set of BadRequestException types is available in the com.soklet.exception package.

// Let's use Gson to write response body data
// See https://github.com/google/gson
final Gson GSON = new Gson();

// Function to create responses for exceptions that bubble out
ThrowableHandler throwableHandler = (
  @NonNull Request request,
  @NonNull Throwable throwable,
  @Nullable ResourceMethod resourceMethod
) -> {
  // Keep track of what to write to the response
  String message;
  int statusCode;

  // Examine the exception that bubbled out and determine what
  // the HTTP status and a user-facing message should be.
  // Note: real systems should localize these messages
  switch (throwable) {
    // Soklet throws this exception - it's a
    // specific subclass of BadRequestException
    case IllegalQueryParameterException e -> {
      message = String.format("Illegal value '%s' for parameter '%s'",
        e.getQueryParameterValue().orElse("[not provided]"),
        e.getQueryParameterName());
      statusCode = 400;
    }

    // Generically handle other BadRequestExceptions
    case BadRequestException ignored -> {
      message = "Your request was improperly formatted.";
      statusCode = 400;
    }

    // Something else?  Fall back to a 500
    default -> {
      message = "An unexpected error occurred.";
      statusCode = 500;
    }
  }

  // Turn response body into JSON bytes with Gson.
  // Note: real systems should expose richer error constructs
  // than an object with a single message field
  byte[] body = GSON.toJson(Map.of("message", message))
    .getBytes(StandardCharsets.UTF_8);

  // Specify our headers
  Map<String, List<String>> headers = new HashMap<>();
  headers.put("Content-Type", List.of("application/json;charset=UTF-8"));

  return MarshaledResponse.withStatusCode(statusCode)
    .headers(headers)
    .body(body)
    .build();
};

// Supply our custom handler to the marshaler
SokletConfig config = SokletConfig.withHttpServer(
  HttpServer.fromPort(8080)
).responseMarshaler(
  ResponseMarshaler.builder()
    .resourceMethodHandler(...)
    .throwableHandler(throwableHandler)
    .build()
).build();

If an exception bubbles out during execution of ResponseMarshaler::forThrowable, Soklet will create its own "failsafe" response and attempt to write it to the client.

References:

404 Not Found

This is invoked by Soklet if no matching Resource Method was found for the Request.

// Let's use Gson to write response body data
// See https://github.com/google/gson
final Gson GSON = new Gson();

// Function to create responses for when no Resource Method
// was found to service the request
NotFoundHandler notFoundHandler = (
  @NonNull Request request
) -> {
  // Specify our headers
  Map<String, List<String>> headers = Map.of(
    "Content-Type", List.of("application/json;charset=UTF-8")
  );

  // Generate response body JSON as a byte array with Gson.
  // Note: real systems should localize this message
  String message = "Resource not found.";
  byte[] body = GSON.toJson(Map.of("message", message))
    .getBytes(StandardCharsets.UTF_8);

  return MarshaledResponse.withStatusCode(404)
    .headers(headers)
    .body(body)
    .build();
};

// Supply our custom handler to the marshaler
SokletConfig config = SokletConfig.withHttpServer(
  HttpServer.fromPort(8080)
).responseMarshaler(
  ResponseMarshaler.builder()
    .resourceMethodHandler(...)
    .notFoundHandler(notFoundHandler)
    .build()
).build();

References:

Post-Processing

Soklet invokes the optional post-processor once after an interceptor selects its final ordinary response, following CORS composition and before HEAD/bodyless and framing projection. Rebuilding the generated response from its parts does not process it twice. The response generator returns an unfinalized descriptor; finalization runs after interceptRequest returns. A transaction or thread-local scope opened inside that interceptor therefore covers generation, not the later final phase. Materialize transaction-dependent values during generation or establish a bounded scope in the processor. A surrounding wrapRequest scope still encloses dispatch. Every forHead implementation receives the finalized GET representation, so forwarding decorators preserve GET/HEAD length and encoding. A configured HeadHandler is a final projection: use response.copy() to retain processed headers and cookies. A fresh descriptor intentionally replaces them. Recovery does not invoke a failed custom head handler again.

ResponseMarshaler.postProcess(MarshaledResponse) is an abstract phase in 4.0. Direct implementations must implement it; decorators must forward it to their delegate. Check for preexisting helper methods with this signature, which now participate in framework dispatch. Calls to the forX methods return intermediate responses. Outside Soklet dispatch, invoke postProcess once on the completed response; direct calls are not intrinsically idempotent. Inside dispatch, leave that phase to Soklet. Reuse in another request gets that request's own phase. The parser-owned forUnparsedRequest path invokes its processor itself. Its inherited implementation applies postProcess to the conventional bodyless rejection response. A decorator must also forward forUnparsedRequest to preserve its delegate's configured unparsed-request handler and finalization.

Dispatch-generated and eligible SSE rejection responses use this phase. Emergency HTTP handler-timeout, handler-queue, shutdown and streaming-admission failsafes bypass application marshaling, CORS and post-processing to preserve bounded rejection when application execution is unavailable. Accepted SSE handshakes retain their framing after an interceptor replaces the response; a post-processor may replace acceptance with a finite denial.

// After response composition and CORS, before HEAD projection
PostProcessor postProcessor = (
  @NonNull MarshaledResponse marshaledResponse
) -> {
  // Copy the response and tack on an 'X-Powered-By' header
  return marshaledResponse.copy()
    // Copier convenience: acquire a temporarily-mutable copy
    // of response headers so you can adjust as needed
    .headers((Map<String, List<String>> mutableHeaders) -> {
      mutableHeaders.put("X-Powered-By", List.of("Soklet"));
    })
    .finish();
};

// Supply our custom post-processor to the marshaler
SokletConfig config = SokletConfig.withHttpServer(
  HttpServer.fromPort(8080)
).responseMarshaler(
  ResponseMarshaler.builder()
    .resourceMethodHandler(...)
    .throwableHandler(...)
    .notFoundHandler(...)
    .postProcessor(postProcessor)
    .build()
).build();

References:

Response Compression

The standard HTTP server can compress finalized in-memory byte-array and ByteBuffer responses. Compression is disabled by default. Enable the built-in gzip behavior with a minimum uncompressed body size:

HttpServer httpServer = HttpServer.withPort(8080)
  .responseCompressor(
    ResponseCompressor.fromDefaultsWithMinimumBodySizeInBytes(1_024)
  )
  .build();

This selects gzip for text/*, JSON and XML (including +json and +xml types), JavaScript, GraphQL, form-encoded data, and SVG when the finalized body meets the threshold. Soklet supplies gzip through the JDK without a codec dependency. Passing null or ResponseCompressor::disabledInstance to responseCompressor(...) disables compression again.

Selecting a Compression Plan

ResponseCompressor is the single application configuration point. Its plan(Request request, MarshaledResponse marshaledResponse) method chooses a ResponseCompressionPlan:

PlanMeaning
ResponseCompressionPlan.none()Apply no compression to this response.
ResponseCompressionPlan.compress(codec)Compress the response with the selected codec when body bytes are needed.
ResponseCompressionPlan.compress(codec, compressedBodyProvider)Obtain encoded body bytes through an application callback, which can use a cache or invoke Soklet's lazy compression supplier.

For example, this compressor applies gzip to every protocol-eligible response of at least 1,024 bytes, regardless of media type:

ResponseCompressionCodec gzip = ResponseCompressionCodec.gzipInstance();

HttpServer httpServer = HttpServer.withPort(8080)
  .responseCompressor((request, marshaledResponse) -> {
    long bodySize = marshaledResponse.getBody()
      .map(MarshaledResponseBody::getLength)
      .orElse(0L);

    if (bodySize < 1_024)
      return ResponseCompressionPlan.none();

    return ResponseCompressionPlan.compress(gzip);
  })
  .build();

The compressor sees the finalized, uncompressed representation. Soklet excludes file, file-channel, streaming, already-encoded, range, transfer-encoded, and bodyless responses before consulting it. The compressor must be thread-safe, and the returned plan must be non-null.

Otherwise eligible responses carrying Content-Digest, Repr-Digest, Digest, or Content-MD5 retain their original bytes and integrity metadata. Soklet skips the compressor for them, while still applying Vary: Accept-Encoding and returning 406 if the client forbids identity coding. To serve a compressed representation with integrity metadata, encode the body and supply its matching Content-Encoding and digest yourself.

Soklet then checks Accept-Encoding against the selected codec, honoring explicit rejections and wildcard preferences. When Accept-Encoding is absent, Soklet conservatively sends the uncompressed representation. If the selected encoding is not accepted, or the plan is none(), Soklet likewise uses the uncompressed representation when permitted. For an eligible response considered by an enabled compressor, explicitly forbidding the uncompressed identity coding (identity;q=0, or *;q=0 without an explicit identity override) instead produces 406 Not Acceptable when the plan cannot supply an accepted encoding. These outcomes invoke neither the body provider nor the codec. One plan selects one codec; Soklet does not automatically try another codec as a fallback.

For an eligible response considered by an enabled compressor, Soklet adds or extends Vary: Accept-Encoding on both compressed and uncompressed outcomes, including none() and a client rejection of the selected codec. This keeps shared caches from reusing a representation for a different encoding preference. When compression applies, Soklet sets Content-Encoding, weakens a strong ETag, and replaces the original Content-Length with the compressed byte count. These rules apply equally to cache hits and freshly compressed bytes. The disabled default and protocol-ineligible responses do not gain compression-related headers.

For HEAD, planning sees the original in-memory representation before its body is omitted. Soklet can therefore make the same size-based decision and emit the selected encoding and validator headers without invoking the body provider or codec. A compressed HEAD response omits Content-Length because the compressed size has not been computed.

Caching Compressed Bodies

There is no built-in compression cache across responses. Without an application cache, each eligible response that sends a compressed body performs its own compression. A plan's optional provider receives a Supplier<byte[]> bound to that response's uncompressed body and selected codec. Calling get() performs compression lazily; repeated calls within that provider invocation return the same computed bytes.

The following is an integration sketch: shouldCompress, compressionKey, and compressedBodies.getOrCompute are application-owned helpers, not Soklet APIs. The cache must be bounded and thread-safe, with synchronous lookup and computation:

ResponseCompressionCodec gzip = ResponseCompressionCodec.gzipInstance();

HttpServer httpServer = HttpServer.withPort(8080)
  .responseCompressor((request, marshaledResponse) -> {
    if (!shouldCompress(request, marshaledResponse))
      return ResponseCompressionPlan.none();

    return ResponseCompressionPlan.compress(gzip, compressedBodySupplier ->
      compressedBodies.getOrCompute(
        compressionKey(marshaledResponse, gzip),
        compressedBodySupplier
      )
    );
  })
  .build();

A cache hit supplies the existing encoded bytes without running the codec. A miss calls compressedBodySupplier.get() and stores the result. The callback itself is deferred, so HEAD performs neither cache lookup nor compression.

Cache keys must identify the exact uncompressed body or a reliable representation version covering all variants, plus the codec and its settings. A URL or weak ETag alone is not sufficient for responses that vary by user, language, request data, or resource version. Store only compressed body bytes; Soklet constructs headers and cookies separately for each response. This cache saves compression work after the handler and marshaler run; avoiding that earlier work requires a separate application response cache.

The provider must return non-null encoded bytes representing the exact input body. Invoke the supplier synchronously while the callback is running; do not retain it or submit it to another thread. Cached output arrays must remain unmodified while retained or used by responses. Applications own cache invalidation, eviction, memory limits, and concurrent access. A null result or exception from the provider or codec is a response-processing failure; it does not request an uncompressed fallback.

Providing Another Codec

ResponseCompressionCodec binds a content encoding to its implementation. getContentEncoding() returns a stable single HTTP token such as gzip or br, excluding identity and *. Plans validate this token and capture its lowercase form when created. compress(ByteBuffer uncompressedBody) returns the bytes encoded with that coding. Implementations must be thread-safe. Soklet supplies a read-only buffer containing exactly the response slice; implementations must use its remaining bytes and must not retain the input buffer.

Select an application codec through ResponseCompressionPlan.compress(codec) or its provider overload. The application supplies the actual encoder and any dependency it requires; naming an encoding does not implement it. Soklet currently includes only ResponseCompressionCodec::gzipInstance, with no built-in Brotli codec or automatic precompressed-file negotiation. A custom codec uses the same protocol checks, lazy body handling, and cache integration as built-in gzip.

References:

File and Buffer Responses

When a Resource Method already knows the exact body it wants to write, it can return MarshaledResponse directly. This supplies the body without ordinary serialization and lets Soklet's standard HTTP server write some known-length bodies more efficiently. Configured final post-processing, HEAD/bodyless projection and transport framing still apply.

MarshaledResponseBody.File bodies are known-length. Soklet validates the path as a readable regular file, records its size, and the standard HTTP server can write it without first loading the whole file into a byte[]. For the JDK's standard file channels, delivery passes the real socket target to FileChannel.transferTo, allowing native transfer when supported; native zero-copy is not guaranteed across platforms or file/channel implementations. Only a failed transfer on that implementation performs bounded source/socket probes to identify peer loss. A readable source alone never suppresses the original failure. Custom and other filesystem-provider file channels use a typed socket adapter that distinguishes source and target failures without a probe write or retry after uncertain partial progress. Delivery ends after a failed transfer.

The adapter also applies to delegating channel wrappers and ZIP/JAR filesystem channels. It can lose native zero-copy transfer, reduce throughput, and use more CPU. You can supply a wrapper's underlying JDK channel to retain the native path only when bypassing the wrapper preserves the intended bytes, behavior, and ownership. A custom FileChannel.transferTo runs on the socket event loop: honor partial and zero-byte target writes, return the completed byte count, and avoid spinning or blocking while waiting for socket capacity.

There are three file-serving layers:

APIUse it whenWhat it does
MarshaledResponse.Builder::body(Path)You already chose a file and only want that file as the response bodyAdds a raw file body. You set status, Content-Type, cache headers, and any other headers yourself. It does not evaluate validators or ranges.
MarshaledResponse::withFileYou already chose one trusted file, but want HTTP file-response semanticsBuilds a request-aware file response with validators, Last-Modified, single byte ranges, If-Range, Content-Encoding, and HEAD behavior. It does not do static-root path containment.
StaticFilesA client-provided path participates in resolving a file under a static rootPerforms root containment, path rejection, index lookup, symlink policy, MIME defaults, per-path resolvers, validators, and single byte ranges.

You can also provide a file slice, a FileChannel, or a pre-rendered ByteBuffer:

// Known-length responses can use a regular file path...
Path filePath = Path.of("/home/user/export.bin");
Long offset = 1024L;
Long count = Files.size(filePath) - offset;

return MarshaledResponse.withStatusCode(206)
  .headers(Map.of("Content-Type", List.of("application/octet-stream")))
  .body(filePath, offset, count)
  .build();
// ...or an NIO FileChannel...
FileChannel fileChannel = FileChannel.open(
  Path.of("/home/user/export.bin"),
  StandardOpenOption.READ
);
Long offset = 0L;
Long count = fileChannel.size();
Boolean closeOnComplete = true;

return MarshaledResponse.withStatusCode(200)
  .body(fileChannel, offset, count, closeOnComplete)
  .headers(Map.of("Content-Type", List.of("application/octet-stream")))
  .build();
// ...or an NIO ByteBuffer.
ByteBuffer cachedPayload = ByteBuffer.wrap(
  "{\"status\":\"ok\"}".getBytes(StandardCharsets.UTF_8)
);

return MarshaledResponse.withStatusCode(200)
  .body(cachedPayload)
  .headers(Map.of("Content-Type", List.of("application/json")))
  .build();

For ByteBuffer bodies, the buffer's position and limit at call time define the response slice. Soklet stores a read-only slice and does not mutate the caller's buffer position. For file-channel bodies, pass false for closeOnComplete when you retain ownership, or true for terminal cleanup by the receiving transport after success or failure. Custom transports implement that cleanup themselves.

When an interceptor or post-processor replaces a response, owned predecessor channels remain retained until replacement delivery completes or is abandoned. This allows a delegating channel or streaming wrapper to consume the original channel without it being closed during transformation. Copier chains, including copy().withoutBody().stream(...), preserve that deferred ownership.

MarshaledResponse has an explicit idempotent close() method and does not implement AutoCloseable. Constructing an unused copy never closes the original response. Do not use try-with-resources around responses handed to Soklet. Built-in transports and the simulator close it after terminal delivery/cancelation/failure. Custom transports must call MarshaledResponse.close() at their actual terminal point to release both the delivered body and retained predecessors; receiving a descriptor is not yet delivery completion. Closing is idempotent. Caller-owned channels marked closeOnComplete=false remain the caller's responsibility.

For already-compressed files, use MarshaledResponse::withFile and set contentEncoding("gzip"). Soklet does not automatically negotiate precompressed file variants; if the chosen file depends on Accept-Encoding, add an appropriate Vary: Accept-Encoding header yourself. Standard HTTP's opt-in responseCompressor setting applies to finalized in-memory byte-array and ByteBuffer responses, not file or streaming responses.

Use byte-array bodies when your marshaler already has finalized bytes in memory:

// Here we turn JSON into UTF-8 bytes
byte[] body = GSON.toJson(Map.of("status", "ok"))
  .getBytes(StandardCharsets.UTF_8);

return MarshaledResponse.withStatusCode(200)
  .headers(Map.of("Content-Type", List.of("application/json;charset=UTF-8")))
  .body(body)
  .build();

Passing null to a single-argument MarshaledResponse body builder method removes any current body. This lets custom marshalers pass nullable serialized bytes directly when the logical response has no body. Multi-argument body methods require a non-null body source because their offset, count, and ownership parameters only make sense when that source is present.

MarshaledResponse::getBody returns an Optional containing a MarshaledResponseBody. Inspect the concrete descriptor when you need to distinguish byte-array, file, file-channel, or ByteBuffer bodies:

// You might need to work with a marshaled response body
// directly in test code, e.g. verifying JSON sent over the wire
// See "Testing" documentation for examples
MarshaledResponseBody responseBody =
  marshaledResponse.getBody().orElseThrow();

if (responseBody instanceof MarshaledResponseBody.Bytes bytesBody) {
  // Do something with a byte-array-backed body
  byte[] bytes = bytesBody.getBytes();
} else if (responseBody instanceof MarshaledResponseBody.File fileBody) {
  // Do something with a file-backed body
  Path file = fileBody.getPath();
  Long offset = fileBody.getOffset();
  Long count = fileBody.getCount();
} else if (responseBody instanceof MarshaledResponseBody.SecureFile secureFile) {
  // StaticFiles bodies have their own acquisition policy.
  Long offset = secureFile.getOffset();
  Long count = secureFile.getCount();
  // A custom transport opens secureFile.openChannel(), seeks to offset,
  // sends exactly count bytes, and closes the channel with try-with-resources.
}

SecureFile is a new permitted subtype in 4.0.0. Include it in exhaustive switches over MarshaledResponseBody and recompile callers. Direct MarshaledResponse.withFile(...) responses continue to produce File.

If you only need the number of body bytes, use MarshaledResponse::getBodyLength; it works for all known-length body types.

References:

Streaming Responses

Return MarshaledResponse with .stream(...) or .streamingResponseBody(...). The default marshaler rejects a StreamingResponseBody supplied through Response.body(...); it is a stream descriptor rather than a finite logical body.

Use a streaming response when bytes are produced over time and the final length is not known upfront: token streams, log tails, or generated CSV and NDJSON exports. Use file and buffer responses for an existing, known-length byte sequence such as a file.

The Servlet response adapters capture their entire body in memory and convert it to a finite response. Flushing a servlet response does not deliver incremental bytes through these native streaming APIs.

Return a MarshaledResponse and supply its writer with stream(StreamingResponseWriter). The writer receives one ResponseStream, which provides output, request metadata, cancelation, and resource ownership:

@GET("/greeting")
public MarshaledResponse greeting() {
  return MarshaledResponse.withStatusCode(200)
    .headers(Map.of(
      "Content-Type", List.of("text/plain; charset=UTF-8"),
      "Cache-Control", List.of("no-transform")
    ))
    .stream(responseStream -> {
      responseStream.write("hello\n".getBytes(StandardCharsets.UTF_8));
      responseStream.flush(); // Optional latency hint
      responseStream.getCancelationToken().throwIfCanceled();
      responseStream.write("goodbye\n".getBytes(StandardCharsets.UTF_8));
    })
    .build();
}

Each response execution gets a fresh stream and token. Writers and source factories run lazily when the body is needed; a HEAD request does not invoke them. Use only the producer thread for output and ownership operations, including OutputStream view operations. Serializing calls from other threads does not make those calls valid. The request, deadline, idle timeout, graceful-shutdown state, and thread-safe token may be read from other threads. Interceptor scopes do not carry into production; see Streaming Context and Transactions.

write(byte[]), its array-slice overload, and write(ByteBuffer) copy their input; the ByteBuffer overload leaves the caller's position and limit unchanged. Encode a short text chunk explicitly with write(text.getBytes(StandardCharsets.UTF_8)), or use a Writer over asOutputStream() for sustained text. The application chooses the charset; ResponseStream has no text-encoding shorthand.

flush() is an advisory latency hint. Soklet flushes remaining bytes after successful producer cleanup. Accepted bytes are not an acknowledgment that the client received them. An I/O failure or interruption during valid output makes the response fail even if the writer catches the exception.

The built-in HTTP server commits status and headers before invoking the writer. A producer failure, even before its first body byte, aborts delivery under that status; it cannot become a replacement 500. Perform fallible work that determines the status in the Resource Method before returning a stream. Simulation materializes output off-network, so it cannot reproduce an already committed socket head.

Streaming queue memory

HTTP streaming bounds both retained payload and chunk metadata. The payload budget is streamingQueueCapacityInBytes; queued and in-flight payload chunks also share a count ceiling of max(16, streamingQueueCapacityInBytes / 256). Small writes can coalesce into pending chunks up to streamingChunkSizeInBytes; an in-flight chunk is never modified. Reaching either bound applies backpressure until socket progress frees capacity or the stream terminates. These settings bound the transport queue, not application-owned buffers or total process memory.

Streaming Context and Transactions

RequestInterceptor wraps synchronous request handling and response handoff. The built-in HTTP server runs writers and source factories on a separate producer thread without propagating ThreadLocal, ScopedValue, database transaction, or ambient tracing scopes. Production can overlap remaining wrapping or lifecycle observation; do not rely on an ordering in which all callbacks have returned before the writer starts.

Capture the needed immutable values or data snapshots while the Resource Method runs. Pass those values directly to producer helpers where possible. If a helper requires ambient application context, bind it explicitly inside the writer and restore it in finally. This example assumes the application interceptor binds CURRENT_LOCALE during request handling:

public class LocalizedGreetingResource {
  public static final ThreadLocal<Locale> CURRENT_LOCALE = new ThreadLocal<>();

  @GET("/localized-greeting")
  public MarshaledResponse localizedGreeting() {
    // Capture the immutable value while the interceptor's binding is visible.
    Locale locale = Optional.ofNullable(CURRENT_LOCALE.get()).orElse(Locale.ENGLISH);

    return MarshaledResponse.withStatusCode(200)
      .headers(Map.of("Content-Type", List.of("text/plain; charset=UTF-8")))
      .stream(responseStream -> {
        Locale previousLocale = CURRENT_LOCALE.get();
        CURRENT_LOCALE.set(locale);
        try {
          responseStream.getCancelationToken().throwIfCanceled();
          responseStream.write(greetingForCurrentLocale().getBytes(StandardCharsets.UTF_8));
        } finally {
          if (previousLocale == null)
            CURRENT_LOCALE.remove();
          else
            CURRENT_LOCALE.set(previousLocale);
        }
      }).build();
  }

  private static String greetingForCurrentLocale() {
    return CURRENT_LOCALE.get().getLanguage().equals("es") ? "Hola\n" : "Hello\n";
  }
}

For Java 25+ ScopedValue bindings, capture the bound value before returning the descriptor and establish a new binding around producer work. No automatic context-propagation hook is provided. Publisher signals may run on publisher-owned threads; a scope in a writer does not bind those threads.

A transaction opened by interceptRequest covers response generation, not later production or delivery. Materialize the needed data before the transaction ends, or open a separate bounded transaction in the producer. Do not capture a request-owned cursor or lazy entity after its transaction closes. A streaming response can fail after some bytes have been delivered; a transaction around response generation does not make network delivery atomic.

Normal response-owned finalization runs after the writer returns, so a binding removed at the end of the writer does not cover that finalization. Use ResponseStream.using(...) inside the bound scope when normal lexical cleanup needs that context, or bind context explicitly in the finalizer. Cancelation callbacks can run on other threads and need their own explicit context as well.

The HTTP simulator materializes the body on the performHttpRequest caller's thread after request handling returns. Interceptor scopes have ended, but ambient bindings around the simulator call can still be visible; that visibility does not prove production propagation. Use the explicit capture-and-bind pattern in both paths.

ResponseStream.getRequest() retains the original request identity received by Soklet. If an interceptor replaced the request, capture context derived from the effective request during resource handling rather than assuming the stream exposes that replacement.

Streaming Admission and Protocol

A custom executor configured with streamingExecutorServiceSupplier must execute accepted producer tasks asynchronously and promptly, or throw RejectedExecutionException when it cannot accept them. Silent discard policies such as DiscardPolicy and DiscardOldestPolicy are unsupported: an accepted producer that never starts can retain a streaming lifecycle slot and cause incomplete shutdown.

Streaming admission stops at quiesce. A previously dispatched handler may finish its side effects and then receive a finite 503 if it returns a new stream after admission closes; already admitted streams and buffered responses may drain.

For token or event delivery through a reverse proxy, configure that proxy to forward chunks promptly. Cache-Control: no-transform does not itself disable buffering. For nginx, a response header X-Accel-Buffering: no can disable response buffering when permitted by the proxy configuration. Set the appropriate content type and account for proxy read/idle timeouts.

Streaming HTTP responses use HTTP/1.1 chunked transfer encoding. Do not set Content-Length or Transfer-Encoding; Soklet owns those headers. HTTP/1.0 streaming requests receive 505 HTTP Version Not Supported and PROTOCOL_UNSUPPORTED. Streaming bodies are rejected for bodyless status codes such as 204 and 304.

The HTTP/1.0 rejection happens after the handler and interceptors have run and returned a streaming response, so their side effects have already occurred. Soklet does not invoke the producer or its resource factory. It sends a bodyless 505 with Connection: close and reports one termination for the original stream handle. willWriteResponse sees the logical candidate; write and request-finish callbacks and metrics see the finite 505 replacement. Buffered HTTP/1.0 responses and normal HEAD body omission remain supported. The simulator has no HTTP wire version, so use a real connection to test this rejection.

Configure reverse proxies to use HTTP/1.1 on their connection to Soklet. For nginx, explicitly set proxy_http_version; use proxy_buffering off when you want chunks forwarded as they arrive:

location /stream/ {
    proxy_pass http://127.0.0.1:8080;
    proxy_http_version 1.1;
    proxy_buffering off;
}

Owning Resources

Acquire a close-aware upstream resource inside the writer with ResponseStream.open(...). Soklet owns it until producer cleanup, and coordinates one close attempt for normal completion or cancelation:

@GET("/ai/tokens")
public MarshaledResponse tokens(OpenAiClient openAiClient) {
  return MarshaledResponse.withStatusCode(200)
    .headers(Map.of("Content-Type", List.of("text/plain; charset=UTF-8")))
    .stream(responseStream -> {
      OpenAiStream upstream = responseStream.open(
        () -> openAiClient.startStreaming(responseStream.getRequest()));

      for (String token : upstream) {
        responseStream.getCancelationToken().throwIfCanceled();
        responseStream.write(token.getBytes(StandardCharsets.UTF_8));
      }
    })
    .build();
}

OpenAiClient and OpenAiStream above are illustrative application-defined adapters, not an SDK API. This form requires a provider whose close() safely races consumption and unblocks it. AutoCloseable alone does not establish that contract. A resource acquired after cancelation wins is disposed instead of returned for use. Factories use StreamResourceFactory, whose open() can throw checked exceptions. Do not separately close a resource after transferring its ownership to Soklet. An ambiguous upstream IOException after cancelation can produce one RESPONSE_STREAM_FAILED diagnostic; classify a known provider cancellation with StreamingResponseCanceledException when the provider gives reliable cancellation evidence.

This also applies to classic socket upstreams owned through open(...) or StreamingResponseBody.fromInputStream(...): cancelation can close the socket or input stream before producer interruption takes effect, causing a SocketException such as Socket closed and a RESPONSE_STREAM_FAILED diagnostic. On platform threads, interruption alone does not unblock a classic socket read; this applies when a custom streaming executor uses platform threads. When cancelation must close the resource to unblock that read, the close-induced exception remains diagnostic if it escapes the producer. It does not replace the elected disconnect or other cancelation outcome.

For an encoder whose final close writes response bytes, use own(resource). It closes on the producer thread after the writer returns, without concurrent close-as-abort:

@GET("/archive.zip")
public MarshaledResponse archive() {
  return MarshaledResponse.withStatusCode(200)
    .headers(Map.of("Content-Type", List.of("application/zip")))
    .stream(responseStream -> {
      ZipOutputStream zipOutputStream = responseStream.own(
        new ZipOutputStream(responseStream.asOutputStream()));
      zipOutputStream.putNextEntry(new ZipEntry("greeting.txt"));
      zipOutputStream.write("hello\n".getBytes(StandardCharsets.UTF_8));
      zipOutputStream.closeEntry();
      // Soklet closes zipOutputStream and writes its archive trailer before completing.
    })
    .build();
}

asOutputStream() creates an independently closeable Java I/O view. Closing it flushes shared staging and closes only that view; it does not close the socket or other views. Native output and views preserve write order. An interrupted view call restores the interrupt flag and throws InterruptedIOException with the accepted prefix in bytesTransferred, unless an already-elected cancelation takes precedence.

Use using(factory, consumer) for a shorter lexical lifetime. It closes that resource and resources acquired through the stream within its consumer, in reverse ownership order, before returning. Root-owned resources close in reverse order after the writer returns. The open(factory, aborter) and using(factory, aborter, consumer) overloads support a separate provider-approved concurrent abort operation and final producer-thread close. Passing Resource::close as that aborter can close twice and is not equivalent to the one-factory open method.

Streaming Body Sources

StreamingResponseBody remains useful for reusable body descriptions and adapters:

StreamingResponseBody writerBody =
  StreamingResponseBody.fromWriter(responseStream -> {
    responseStream.write("hello\n".getBytes(StandardCharsets.UTF_8));
  });

Attach one with streamingResponseBody(StreamingResponseBody). Body descriptors are reusable; any captured application state must support the concurrent executions your application allows.

StreamingResponseBody publisherBody =
  StreamingResponseBody.fromPublisher(byteBufferPublisher);

The Flow.Publisher adapter requests one item at a time and copies each emitted ByteBuffer before onNext returns. The callback blocks its delivering thread when the bounded transport queue is full, so each slow client can occupy one delivery thread. Prefer a dedicated publisher-delivery executor over the common ForkJoin pool: managed blocking has finite compensation capacity and falls back to ordinary blocking when that capacity is exhausted. Output waits park outside state monitors, so they do not occupy virtual-thread carriers while waiting on JDK 21. Synchronous publishers receive iterative demand after each request() returns, without recursive demand calls. Cancelation cancels the subscription. A publisher that returns from subscribe before delivering onSubscribe remains pending work until that acquisition resolves; a late subscription must still be canceled. Providers must cooperate with cancelation and finish their calls for physical cleanup to complete.

fromInputStream(...) and fromReader(...) accept lazy checked factories:

StreamingResponseBody inputStreamBody =
  StreamingResponseBody.fromInputStream(() -> blobStore.openObjectStream(key));
StreamingResponseBody readerBody =
  StreamingResponseBody.withReader(
    () -> reportService.openReportReader(),
    StandardCharsets.UTF_8
  )
  .malformedInputAction(CodingErrorAction.REPORT)
  .unmappableCharacterAction(CodingErrorAction.REPORT)
  .build();

These adapters own and close their source on completion or cancelation. The source must support close racing a read and unblocking that read. Reader bodies require a charset; malformed and unmappable input actions default to CodingErrorAction.REPORT.

For off-network streaming behavior, including synchronous producers, absent HTTP timeouts and failure handling, see HTTP streaming simulation.

Exhausted HTTP streaming admission in simulation returns the same built-in finite 503 as HTTP: Content-Type: text/plain; charset=UTF-8, Connection: close, and body HTTP 503: Service Unavailable. The result clears the rejected logical response and retains the resource method. didWriteResponse and didFinishRequestHandling observers and metrics describe that finite response. willWriteResponse sees the original stream before admission, as it does in HTTP. The producer or source factory is never acquired; a bounded asynchronous rejection notification retains the original streaming descriptor and reports BACKPRESSURE, without delaying the finite result. An admitted simulator call still waits for its own termination observer.

Graceful Shutdown of Feeds

ResponseStream.isGracefulShutdownRequested() lets an indefinite HTTP feed finish during the owner's graceful shutdown budget. The thread-safe flag belongs to one response execution and stays true once requested. It is advisory: finite downloads may continue draining, and the request does not cancel the token, interrupt the writer, abort resources or close output.

Check the flag between items and use bounded waits comfortably within the configured graceful budget. Stop acquiring new items, write any final record, then return normally so owned encoders can finalize and queued output can drain:

@GET("/feed")
public MarshaledResponse feed() {
  return MarshaledResponse.withStatusCode(200)
    .stream(responseStream -> {
      while (!responseStream.isGracefulShutdownRequested()) {
        responseStream.getCancelationToken().throwIfCanceled();
        responseStream.write("tick\n".getBytes(StandardCharsets.UTF_8));
        responseStream.flush();
        Thread.sleep(100);
      }
      responseStream.getCancelationToken().throwIfCanceled();
      responseStream.write("feed ended\n".getBytes(StandardCharsets.UTF_8));
    })
    .build();
}

Disconnects, configured response/idle deadlines and forced shutdown still govern output and can win while a feed is finishing. getDeadline() continues to mean the configured response deadline. A graceful request alone does not prove delivery or termination; an uncooperative feed can still exhaust the budget. Automatic InputStream, Reader and Publisher bodies retain finite draining; an indefinite source needs application-managed completion or a writer that observes this flag. The same state is available in HTTP simulation when the owning scope shuts down.

Cancelation and Termination

ResponseStream.getCancelationToken() exposes cooperative cancelation. The stream also provides getRequest(), getDeadline(), and getIdleTimeout(). Trace context is available through responseStream.getRequest().getTraceContext(); see Trace Context.

HTTP cancelation cooperatively interrupts the producer thread. Output preserves the interrupt flag when translating interruption into an elected StreamingResponseCanceledException; managed cleanup temporarily clears and restores it so resources can close. Check the token between expensive operations. onCancel(Runnable) returns an unchecked-close CallbackRegistration for removing a callback before it is claimed. Each registration is independent. Normal completion discards cancelation callbacks; use resource ownership for cleanup needed on both completion and cancelation. Managed callbacks use bounded runtime dispatch; registration after cancelation can invoke the callback inline, so callbacks should return promptly.

Ordinary HTTP preserves input half-close and buffered pipelining within its finite buffering bound: clients can stop sending while continuing to read a response. TCP FIN alone cannot distinguish that from a full peer close. A reset or recognized remote write failure cancels delivery with CLIENT_DISCONNECTED, without a routine WRITE_ERROR transport diagnostic. A quiet feed with no next write may retain its lifecycle slot until the streaming idle or total timeout. Disabling both timeouts and making no further writes removes that bound. Keep a finite timeout or emit application heartbeats for long-lived feeds. MCP uses a separate response-channel EOF policy. If bytes for later pipelined requests coalesced with a streaming request exceed maximumRequestSizeInBytes, the connection closes before streaming response headers are committed. Very small limits can therefore reject an otherwise small first request when its buffered successors exceed that bound.

Client disconnect, shutdown, timeouts, producer failure, simulator output limits, and explicit application abort can cancel a response. Throw StreamingResponseCanceledException with APPLICATION_CANCELED for an intentional abort. The first elected terminal outcome wins. Healthy encoder tail writes remain writable during finalization. Time waiting for the HTTP output queue pauses the remaining application-cleanup budget; response and idle deadlines still apply, and actual socket progress refreshes idle activity after the producer returns. Cancellation starts finite cleanup supervision; output attempted by managed encoder close is discarded while the encoder releases its resources. Ordinary producer writes still fail after cancellation, and independent close failures remain visible. A cleanup deadline that expires during otherwise normal finalization yields CLEANUP_TIMEOUT; it does not replace an earlier disconnect or timeout.

A terminal notification does not prove that application cleanup has physically finished. Blocked cleanup retains its lifecycle capacity until it exits and can appear in incomplete shutdown diagnostics. Configure the streaming lifecycle bounds for your workload. StreamTerminationReason is shared by HTTP streaming and dedicated SSE; MCP has its own McpStreamTerminationReason.

Owned-resource close/abort and publisher cancel failures in built-in HTTP streaming and simulation produce RESPONSE_STREAM_CLOSE_FAILED log events. These include the original exception, request, optional resource method and original streaming response. Framework supervision failures and cleanup-deadline expiry use SERVER_INTERNAL_ERROR. A diagnostic does not replace an already elected termination; a failed finalizer may also cause a PRODUCER_FAILED termination. An ambiguous producer IOException observed after cancelation can produce RESPONSE_STREAM_FAILED through the same bounded diagnostic allowance after cleanup and physical owners exit. Actual cleanup failures take priority; evidence arriving after that diagnostic returns is not dispatched again. The runtime delivers diagnostics asynchronously and admits only the first diagnostic for each lifetime. A blocked log observer retains that lifetime's physical work and admission slot through shutdown. Choose which fields to log; context and exceptions can contain application data.

Admitted termination notifications and diagnostics use separate executors, each allowing one observation per admitted lifetime and at most streamingLifecycleCapacity workers. Workers grow with outstanding work and are reused; idle workers expire. Worker-exit repair preserves delivery capacity across idle expiry. Helper thread factories capture their context class loader when created, so lazy stream workers do not retain a later request's loader. A blocked observation retains its own slot while other admitted streams can deliver their observations and retire. Observers can run more concurrently than streamingCallbackConcurrency, which bounds cancelation batches and unadmitted rejection observers. Blocking that pool can still queue later cancelation batches and retain their slots. If every lifecycle slot contains blocked application work, admission still returns 503. Keep hooks short; Soklet cannot forcibly stop application code.

References:

Copying Responses

When you want to adjust an existing Response (for example, adding a header during post-processing), use Response::copy to get a mutable copier, change the fields you need, then call Response.Copier::finish to build the new instance.

This "copy-to-change" workflow is necessary because Response objects are effectively immutable.

Response updatedResponse = response.copy()
  // Convenience method to get a mutable copy of
  // existing headers which you can modify in-place
  .headers((Map<String, List<String>> mutableHeaders) -> {
    mutableHeaders.put("X-Powered-By", List.of("Soklet"));
  })
  .finish();

The copy is shallow for performance (for example, the response body object reference is reused), so treat the original as immutable.

If you're working with a MarshaledResponse, it also provides MarshaledResponse::copy for the same purpose (tweaking headers, status, or body) before writing the final response.

Advanced Response Marshaling

Experts Only

You can normally use the out-of-the-box implementation provided by ResponseMarshaler::builder for the below scenarios instead of writing your own.

Unparsed HTTP Requests

Most ResponseMarshaler methods receive a valid Request. Some HTTP and SSE handshake failures happen earlier: the transport must reject the input before Soklet can safely construct a Request. For those failures, Soklet invokes ResponseMarshaler::forUnparsedRequest with an immutable UnparsedRequest describing that particular rejection.

An UnparsedRequest provides:

The built-in HTTP and SSE transports capture at most 64 KiB. The attributed byte count can therefore be larger than the number of bytes available through getCapturedBytes(). For parser failures, the count and capture end at the parser-proven failure boundary; for partial read timeouts, they end at the received input. Bytes beyond the rejected request are excluded because they might belong to a later pipelined request.

Later HTTP request-construction failures, such as invalid URI encoding or malformed compressed bodies, report the observed wire count with an empty capture and isCaptureTruncated() == true. Soklet does not retain a second raw copy of successfully parsed traffic for this hook.

Soklet does not fabricate a nullable or partial Request, and this type does not expose parsed targets, headers, cookies, bodies, or a parser exception. If an application truly needs more detail, it can cautiously interpret the bounded raw capture according to its own protocol and disclosure policy.

ReasonDefault and fallback status
MALFORMED_REQUEST400 Bad Request
REQUEST_TARGET_TOO_LONG414 URI Too Long
EXPECTATION_FAILED417 Expectation Failed
REQUEST_HEADERS_TOO_LARGE431 Request Header Fields Too Large
REQUEST_READ_TIMEOUT408 Request Timeout
REQUEST_TOO_LARGE413 Content Too Large
UNSUPPORTED_CONTENT_ENCODING415 Unsupported Media Type
REQUEST_BODY_DECOMPRESSION_FAILED400 Bad Request

Those statuses are defaults, not properties of the reason enum. A custom handler controls its MarshaledResponse status and may select any final status from 200 through 599.

Raw Input Is Sensitive

The captured bytes are unparsed, unredacted network input. They can contain credentials in a request target, Authorization or Cookie values, body fragments, control bytes, or non-text data. Do not log, meter, decode, reflect, or persist them indiscriminately. Inspect them only when necessary, apply application-specific redaction, and keep any derivative data bounded. UnparsedRequest::toString() omits both captured bytes and the remote address.

Here is an example that returns JSON and prevents caches from retaining responses generated by this handler. The emergency built-in fallback remains bodyless and does not inherit these application headers:

// Let's use Gson to write response body data
// See https://github.com/google/gson
final Gson GSON = new Gson();

UnparsedRequestHandler unparsedRequestHandler = (
  @NonNull UnparsedRequest unparsedRequest
) -> {
  StatusCode statusCode = switch (unparsedRequest.getReason()) {
    case MALFORMED_REQUEST -> StatusCode.HTTP_400;
    case REQUEST_TARGET_TOO_LONG -> StatusCode.HTTP_414;
    case EXPECTATION_FAILED -> StatusCode.HTTP_417;
    case REQUEST_HEADERS_TOO_LARGE -> StatusCode.HTTP_431;
    case REQUEST_READ_TIMEOUT -> StatusCode.HTTP_408;
    case REQUEST_TOO_LARGE -> StatusCode.HTTP_413;
    case UNSUPPORTED_CONTENT_ENCODING -> StatusCode.HTTP_415;
    case REQUEST_BODY_DECOMPRESSION_FAILED -> StatusCode.HTTP_400;
  };

  String message = switch (unparsedRequest.getReason()) {
    case MALFORMED_REQUEST -> "Malformed HTTP request.";
    case REQUEST_TARGET_TOO_LONG -> "Request target is too long.";
    case EXPECTATION_FAILED -> "Request expectation is unsupported.";
    case REQUEST_HEADERS_TOO_LARGE -> "Request headers are too large.";
    case REQUEST_READ_TIMEOUT -> "Request reading timed out.";
    case REQUEST_TOO_LARGE -> "Request body is too large.";
    case UNSUPPORTED_CONTENT_ENCODING -> "Request content encoding is unsupported.";
    case REQUEST_BODY_DECOMPRESSION_FAILED -> "Request body decompression failed.";
  };

  byte[] body = GSON.toJson(Map.of("message", message))
    .getBytes(StandardCharsets.UTF_8);

  return MarshaledResponse.withStatusCode(
    statusCode.getStatusCode()
  )
    .headers(Map.of(
      "Cache-Control", List.of("no-store"),
      "Content-Type", List.of("application/json;charset=UTF-8")
    ))
    .body(body)
    .build();
};

SokletConfig config = SokletConfig.withHttpServer(
  HttpServer.fromPort(8080)
).responseMarshaler(
  ResponseMarshaler.builder()
    .resourceMethodHandler(...)
    .unparsedRequestHandler(unparsedRequestHandler)
    .build()
).build();

This is a per-rejection hook, invoked at most once with the bounded details for one rejected input. The built-in HTTP and SSE transports run the work on their configured request-handler executor and never runs either callback inline on the socket selector. The framework-managed default executor has bounded concurrency and queue capacity; a custom executor controls its own capacity. requestHandlerTimeout bounds how long the transport waits for the combined observation and marshaling pipeline. Later HTTP construction failures and SSE rejections use the remaining handler budget, including any earlier queue wait. On timeout Soklet claims the fallback and interrupts the worker, but cancellation remains cooperative if application code ignores interruption. Before invoking the marshaler, Soklet offers the same UnparsedRequest to LifecycleObserver::didRejectUnparsedRequest for application-owned telemetry. Observer failures are contained and do not prevent marshaling when timeout budget remains.

The hook covers malformed input, target/header limits, partial read timeouts and aggregate-size violations that prevent constructing a valid request. The HTTP server also uses it for URI/encoding validation, unsupported content coding and malformed compressed bodies. SSE keeps its existing 400 policy for unsupported expectations, represented as MALFORMED_REQUEST. The strict HTTP parser also classifies unrecognized methods, unsupported transfer codings and unsupported HTTP versions as MALFORMED_REQUEST (400); it does not expose separate 501/505 reasons.

Idle read timeouts and EOF before complete headers close quietly. Admission overload, shutdown and broken-socket failsafes do not invoke this hook: they must work without available application capacity or a usable socket.

Detailed handling is deliberately best-effort during overload. If the request-handler executor rejects the work, neither didRejectUnparsedRequest nor forUnparsedRequest runs; Soklet immediately writes the built-in response and records its existing low-cardinality transport-failure metric. Soklet uses the same built-in fallback if the admitted work times out, the observer consumes the available timeout, the marshaler fails, or its result cannot be written safely on this pre-request path.

Soklet retains ownership of wire safety. It closes the connection and canonicalizes transport framing, including Connection, Content-Length, and Transfer-Encoding, regardless of the application response. The complete serialized response is capped at 64 KiB. Custom responses must use a final status from 200 through 599 and a finite, in-memory byte-array or ByteBuffer body; an informational or out-of-range status, an oversized response, a forbidden body on a bodyless status, or a streaming or file-backed body falls back to the built-in bodyless response. Direct implementations of ResponseMarshaler inherit the conventional bodyless response followed by their postProcess implementation unless they override forUnparsedRequest. Forwarding decorators should delegate forUnparsedRequest as well, preserving the delegate's rejection handler and post-processing. When you use the standard builder, its normal post-processor also applies to this result.

ResponseMarshaler::forContentTooLarge remains separate by design. Soklet uses it when parsing progressed far enough to construct a real request, so the marshaler can use request and matched-resource context for a route-aware 413 Content Too Large response. forUnparsedRequest covers only failures for which no trustworthy Request exists.

References:

405 Method Not Allowed

This is invoked by Soklet if a Resource Method was matched for the Request, but the HTTP Method is inapplicable.

Here is an example of a custom implementation:

// Let's use Gson to write response body data
// See https://github.com/google/gson
final Gson GSON = new Gson();

MethodNotAllowedHandler methodNotAllowedHandler = (
  @NonNull Request request,
  @NonNull Set<HttpMethod> allowedHttpMethods
) -> {
  // Soklet provides the set of permitted HTTP methods
  List<String> allowedHttpMethodsAsStrings = allowedHttpMethods.stream()
    .map(httpMethod -> httpMethod.name())
    .sorted()
    .toList();

  // Ensure we set the "Allow" header
  Map<String, List<String>> headers = Map.of(
    "Allow", allowedHttpMethodsAsStrings,
    "Content-Type", List.of("application/json;charset=UTF-8")
  );

  // This response body tells callers what is expected
  Map<String, Object> responseBody = new LinkedHashMap<>();
  // Note: real systems should localize this message
  responseBody.put("message", "Method not allowed.");
  responseBody.put("requested", request.getHttpMethod().name());
  responseBody.put("allowed", allowedHttpMethodsAsStrings);
  byte[] body = GSON.toJson(responseBody)
    .getBytes(StandardCharsets.UTF_8);

  return MarshaledResponse.withStatusCode(405)
    .headers(headers)
    .body(body)
    .build();
};

// Supply our custom handler to the marshaler
SokletConfig config = SokletConfig.withHttpServer(
  HttpServer.fromPort(8080)
).responseMarshaler(
    ResponseMarshaler.builder()
      .resourceMethodHandler(...)
      .methodNotAllowedHandler(methodNotAllowedHandler)
      .build()
).build();

For example, suppose we configure a Resource Method to handle PUT, POST, and DELETE.

@PUT("/example")
@POST("/example")
@DELETE("/example")
public void example405() {
  // Implementation doesn't matter
}

Accessing it with a GET and the above ResponseMarshaler will result in this response:

% curl -i 'http://localhost:8080/example'
HTTP/1.1 405 Method Not Allowed
Allow: DELETE
Allow: OPTIONS
Allow: POST
Allow: PUT
Content-Length: 95
Content-Type: application/json;charset=UTF-8
Date: Sun, 21 Mar 2024 16:19:01 GMT

{"message":"Method not allowed.","requested":"GET","allowed":["DELETE","OPTIONS","POST","PUT"]}

References:

413 Content Too Large

This is invoked by Soklet if the size of the Request is above the maximum size configured for the server. For the standard HTTP server, the configured limit applies to the whole received HTTP request, including request line, headers, transfer framing, and body bytes. These scenarios are usually triggered by a multipart file upload or an otherwise unusually large request body.

You can detect "content too large" status by querying Request::isContentTooLarge.

Use Caution

Depending on when the "content too large" state was reached, Request might contain incomplete header/cookie collections. It will always have a zero-length body. If the transport cannot parse enough data to identify a request target before the limit is exceeded, Soklet may close the connection instead of invoking this marshaling path.

Soklet is designed to power systems that exchange small "transactional" payloads. It can serve known-length file-backed responses, but request uploads are still buffered and bounded by the configured request-size limit; Soklet is not intended for handling multipart uploads at scale, buffering uploads to disk, streaming request bodies, etc.

Explicitly handling 413 Content Too Large is an unusual case.

Here is an example of a custom implementation:

// Let's use Gson to write response body data
// See https://github.com/google/gson
final Gson GSON = new Gson();

ContentTooLargeHandler contentTooLargeHandler = (
  @NonNull Request request,
  @Nullable ResourceMethod resourceMethod
) -> {
  // Specify our headers
  Map<String, List<String>> headers = Map.of(
    "Content-Type", List.of("application/json;charset=UTF-8")
  );

  // Turn response body into JSON bytes with Gson.
  // Note: real systems should localize this message
  String message = "Request was too large.";
  byte[] body = GSON.toJson(Map.of("message", message))
    .getBytes(StandardCharsets.UTF_8);

  return MarshaledResponse.withStatusCode(413)
    .headers(headers)
    .body(body)
    .build();
};

// Supply our custom handler to the marshaler
SokletConfig config = SokletConfig.withHttpServer(
  HttpServer.fromPort(8080)
).responseMarshaler(
  ResponseMarshaler.builder()
    .resourceMethodHandler(...)
    .contentTooLargeHandler(contentTooLargeHandler)
    .build()
).build();

Exercising by including a large file in the request body results in this response:

% curl -i -d '@very-big-file.mp4' 'http://localhost:8080/big-file'
HTTP/1.1 413 Content Too Large
Content-Length: 41
Content-Type: application/json;charset=UTF-8
Date: Sun, 21 Mar 2024 16:19:01 GMT

{
  "message": "Request was too large."
}

References:

503 Service Unavailable

Soklet returns a 503 Service Unavailable response for standard HTTP request-handler queue overload and SSE connection-limit rejection. The standard HTTP connection cap instead closes excess sockets without an HTTP response. MCP has its own bounded processor and overload mapping; see the MCP documentation for those controls and the Server Configuration documentation for HTTP and SSE limits.

For standard HTTP and SSE, the default 503 response includes a plain-text body and a Connection: close header to signal clients to terminate the connection and back off:

HTTP/1.1 503 Service Unavailable
Content-Type: text/plain; charset=UTF-8
Connection: close

HTTP 503: Service Unavailable

HTTP streaming lifecycle-capacity or producer-executor rejection uses a fixed finite failsafe 503 before streaming headers or producer entry. HTTP handler-timeout, exhausted-handler-queue and shutdown responses use the same emergency policy. These failsafes bypass ServiceUnavailableHandler, CORS and postProcess; they cannot be customized with the handler below.

For eligible ordinary HTTP/SSE overload responses, customize the response (for example, return JSON and add Retry-After) with a ServiceUnavailableHandler:

ServiceUnavailableHandler serviceUnavailableHandler = (
  @NonNull Request request,
  @Nullable ResourceMethod resourceMethod
) -> {
  int statusCode = 503;

  // Turn response body into JSON bytes with Gson.
  // Note: real systems should localize this message
  String message = "Try again shortly.";
  byte[] body = GSON.toJson(Map.of("message", message))
    .getBytes(StandardCharsets.UTF_8);

  return MarshaledResponse.withStatusCode(statusCode)
    .headers(Map.of(
      "Content-Type", List.of("application/json;charset=UTF-8"),
      "Connection", List.of("close"),
      "Retry-After", List.of("10")
    ))
    .body(body)
    .build();
};

SokletConfig config = SokletConfig.withHttpServer(
  HttpServer.fromPort(8080)
).responseMarshaler(
  ResponseMarshaler.builder()
    .serviceUnavailableHandler(serviceUnavailableHandler)
    .build()
).build();

References:

HTTP OPTIONS

Soklet invokes this handler for an ordinary, non-CORS-preflight OPTIONS request when there is no explicit matching OPTIONS Resource Method. It runs only when the path has a matching route on that listener. Unknown paths, including paths served only by another listener, use not-found handling: by default, OPTIONS /nope returns 404 Not Found. CORS preflight requests use CORS handling, and OPTIONS * has a separate handler described below.

Experts Only

If you're looking to customize OPTIONS handling, it's likely that you want to manually handle CORS scenarios.

Soklet already provides comprehensive CORS support. But if you prefer to roll your own, read on.

Here is an example of a custom implementation:

OptionsHandler optionsHandler = (
  @NonNull Request request,
  @NonNull Set<HttpMethod> allowedHttpMethods
) -> {
  // Soklet examines your Resource Methods and provides you with
  // the set of HTTP methods supported for the request.
  // This enables you to easily write the "Allow" response header
  List<String> allowedHttpMethodsAsStrings = allowedHttpMethods.stream()
    .map(httpMethod -> httpMethod.name())
    .sorted()
    .toList();

  // Normally OPTIONS is a 204 with an Allow header
  return MarshaledResponse.withStatusCode(204)
    .headers(Map.of("Allow", allowedHttpMethodsAsStrings))
    .build();
};

// Supply our custom handler to the marshaler
SokletConfig config = SokletConfig.withHttpServer(
  HttpServer.fromPort(8080)
).responseMarshaler(
  ResponseMarshaler.builder()
    .resourceMethodHandler(...)
    .optionsHandler(optionsHandler)
    .build()
).build();

For example, suppose we configure a Resource Method to handle PUT, POST, and DELETE.

@PUT("/example")
@POST("/example")
@DELETE("/example")
public void exampleOptions() {
  // Implementation doesn't matter
}

Accessing it via OPTIONS and the above customized ResponseMarshaler will result in this response:

% curl -i -X OPTIONS 'http://localhost:8080/example'
HTTP/1.1 204 No Content
Allow: DELETE
Allow: OPTIONS
Allow: POST
Allow: PUT
Date: Sun, 21 Mar 2024 16:19:01 GMT

It's also possible for clients to issue a special OPTIONS * request (colloquially, OPTIONS Splat). This is a special HTTP/1.1 request defined in RFC 7231 which permits querying of server-wide capabilities, not the capabilities of a particular resource. For example, a load balancer might want to ask "is the system up?" without hitting an explicit health-check URL.

By default, Soklet will write an HTTP 200 OK response for OPTIONS * requests like this:

% curl -X OPTIONS --request-target '*' 'http://localhost:8080' -i
HTTP/1.1 200 OK
Allow: DELETE
Allow: GET
Allow: HEAD
Allow: OPTIONS
Allow: PATCH
Allow: POST
Allow: PUT
Content-Length: 0
Date: Sun, 21 Mar 2024 16:19:01 GMT

You may override this behavior by providing an OptionsSplatHandler:

OptionsSplatHandler optionsSplatHandler = (
  @NonNull Request request
) -> {
  // Expose a subset of HTTP methods in the Allow header
  List<String> allowedHttpMethods = List.of("GET", "OPTIONS", "POST");

  // Normally OPTIONS * is a 200 with an Allow header,
  // we add an extra 'Server' header here
  return MarshaledResponse.withStatusCode(200)
    .headers(Map.of(
      "Allow", allowedHttpMethods,
      "Server", List.of("Soklet")
    )).build();
};

// Supply our custom handler to the marshaler
SokletConfig config = SokletConfig.withHttpServer(
  HttpServer.fromPort(8080)
).responseMarshaler(
  ResponseMarshaler.builder()
    .resourceMethodHandler(...)
    .optionsSplatHandler(optionsSplatHandler)
    .build()
).build();

With the custom handler, OPTIONS * responses now look like this:

% curl -X OPTIONS --request-target '*' 'http://localhost:8080' -i
HTTP/1.1 200 OK
Allow: GET
Allow: OPTIONS
Allow: POST
Content-Length: 0
Date: Sun, 21 Mar 2024 16:19:01 GMT
Server: Soklet

References:

HTTP HEAD

This is invoked by Soklet if a Resource Method was matched for the Request and the HTTP Method is HEAD. The idea behind HEAD is for the client to determine the size of the response body that would be returned by a GET request but without the server providing the body.

Four rules:

  1. A HEAD must never write a response body
  2. A HEAD for a known-length response uses that representation length in Content-Length when its status permits it (205 uses zero; bodyless status rules still apply)
  3. A HEAD must pass through whatever HTTP status would have been returned by the GET response body
  4. A HEAD should pass through whatever HTTP headers would have been returned by the GET response

For streaming responses, the default HEAD behavior removes the stream and omits Content-Length, because the GET length is not known upfront.

For an implicit HEAD match, HeadHandler receives the equivalent GET method's marshaled response. If you declare an explicit @HEAD Resource Method, it receives that method's own marshaled response instead. The parameter retains the name getMethodMarshaledResponse in both cases. The default handler computes length from a present finite body. For a bodyless explicit @HEAD response it preserves one valid application-supplied representation length when the status permits it; absent that header, the representation length is unknown and no length is synthesized.

As an optional customization, this handler also keeps a valid application-supplied representation length when the finite body is explicitly empty. Otherwise it computes length from the body, and it still removes the body and streaming descriptor:

HeadHandler headHandler = (
  @NonNull Request request,
  @NonNull MarshaledResponse getMethodMarshaledResponse
) -> {
  // This is the GET response or the explicit HEAD method's response.
  Long getResponseLength = getMethodMarshaledResponse.getBodyLength();

  // MarshaledResponse is immutable so we make a mutable copy
  // of the input response to construct our HEAD response.
  MarshaledResponse.Copier responseCopier = getMethodMarshaledResponse.copy()
    // Ensure no response body bytes are written
    .withoutBody()
    .withoutStreamingResponseBody()
    .cookies(getMethodMarshaledResponse.getCookies());

  if (getMethodMarshaledResponse.isStreaming()) {
    responseCopier.headers((mutableHeaders) -> {
      mutableHeaders.remove("Content-Length");
    });
  } else {
    responseCopier.headers((mutableHeaders) -> {
      Long representationLength = getResponseLength;
      List<String> suppliedLengths = mutableHeaders.get("Content-Length");

      if (getResponseLength == 0L && suppliedLengths != null
          && suppliedLengths.size() == 1) {
        String suppliedLength = suppliedLengths.get(0);

        if (suppliedLength.matches("[0-9]+")) {
          try {
            representationLength = Long.valueOf(suppliedLength);
          } catch (NumberFormatException ignored) {
            // An out-of-range value falls back to the body length.
          }
        }
      }

      mutableHeaders.put("Content-Length", List.of(
        String.valueOf(representationLength)
      ));
    });
  }

  return responseCopier.finish();
};

// Supply our custom handler to the marshaler
SokletConfig config = SokletConfig.withHttpServer(
  HttpServer.fromPort(8080)
).responseMarshaler(
  ResponseMarshaler.builder()
    .headHandler(headHandler)
    .build()
).build();

For example, an explicit @HEAD method can return an empty response with Content-Length: 1234; this handler preserves 1234. A PostProcessor runs before HEAD marshaling. It can change the representation that HEAD projects, but cannot override a length chosen later by that projection. Use the HeadHandler for the final representation-length header. The transport still validates that header and applies status-specific bodyless framing rules.

This example trusts an application-supplied length for any empty finite response, including a GET response used for an implicit HEAD. A 200 OK GET with an empty representation must not supply a nonzero Content-Length: the transport sends that GET with length zero, so preserving another length for HEAD would misadvertise its representation. The handler receives Request, so an application can instead restrict length preservation using a known route or other application context; the HEAD HTTP method alone does not distinguish an explicit match from an implicit one.

Given this Resource Method:

@GET("/hello")
public String hello() {
  return "world";
}

...here's how a GET might look:

% curl -i -X GET 'http://localhost:8080/hello'
HTTP/1.1 200 OK
Content-Length: 5
Content-Type: application/json;charset=UTF-8
Date: Sun, 21 Mar 2024 16:19:01 GMT

world

...and here's how a HEAD might look:

% curl --head -i 'http://localhost:8080/hello'
HTTP/1.1 200 OK
Content-Length: 5
Content-Type: application/json;charset=UTF-8
Date: Sun, 21 Mar 2024 16:19:01 GMT

References:

CORS

If Soklet sees an Origin header is specified in the Request - that is, it appears to be a CORS request - it consults its configured CorsAuthorizer, which provides preflight requests with a thumbs-up or thumbs-down and supplements approved requests with additional data in the response headers.

Experts Only

Unless you have special requirements, you should prefer to use Soklet's CORS support instead of writing your own.

Please refer to Soklet's CORS documentation for a comprehensive treatment of CORS, from basic whitelisting of permitted domains to full customization of authorization and response writing.

Should you prefer to roll your own CORS responses, the hooks below are available to you:

// Preflight: the request is allowed
CorsPreflightAllowedHandler corsPreflightAllowedHandler = (
  @NonNull Request request,
  @NonNull CorsPreflight corsPreflight,
  @NonNull CorsPreflightResponse corsPreflightResponse
) -> {
  // Return a MarshaledResponse with headers like
  // Access-Control-Allow-Origin, Vary, etc.
};

// Preflight: the request is not allowed
CorsPreflightRejectedHandler corsPreflightRejectedHandler = (
  @NonNull Request request,
  @NonNull CorsPreflight corsPreflight
) -> {
  // Return a MarshaledResponse with 403 or similar status
};

// Supplement responses for requests that have "passed" preflight
CorsAllowedHandler corsAllowedHandler = (
  @NonNull Request request,
  @NonNull Cors cors,
  @NonNull CorsResponse corsResponse,
  @NonNull MarshaledResponse marshaledResponse
) -> {
  // Supplement the provided MarshaledResponse with
  // Access-Control-Allow-Origin, Vary, etc. and return it
};

// Supply our custom handlers to the marshaler
SokletConfig config = SokletConfig.withHttpServer(
  HttpServer.fromPort(8080)
).responseMarshaler(
  ResponseMarshaler.builder()
    .resourceMethodHandler(...)
    .corsPreflightAllowedHandler(corsPreflightAllowedHandler)
    .corsPreflightRejectedHandler(corsPreflightRejectedHandler)
    .corsAllowedHandler(corsAllowedHandler)
    .build()
).build();

References:

Full Customization

You may directly implement the ResponseMarshaler interface. This is unusual; most applications are better served by providing "handler" functions to Soklet's internal implementation as outlined above. The following is an interface sketch, not a complete compilable implementation: implement every omitted method and replace the response-path comments with your returned responses.

SokletConfig config = SokletConfig.withHttpServer(
  HttpServer.fromPort(8080)
// Bring your own totally-custom response marshaler
).responseMarshaler(new ResponseMarshaler() {
  @NonNull
  @Override
  public MarshaledResponse forResourceMethod(
    @NonNull Request request,
    @NonNull Response response,
    @NonNull ResourceMethod resourceMethod
  ) {
    // Application response path
  }

  @NonNull
  @Override
  public MarshaledResponse forThrowable(
    @NonNull Request request,
    @NonNull Throwable throwable,
    @Nullable ResourceMethod resourceMethod
  ) {
    // Exception response path
  }

  @NonNull
  @Override
  public MarshaledResponse postProcess(@NonNull MarshaledResponse response) {
    // Decorators must call their delegate's postProcess here.
    return response;
  }

  // Other ResponseMarshaler methods elided
}).build();

References:

Redirects

Soklet provides special convenience shorthand for the following types of HTTP Redirect:

For the below examples, assume they will redirect to a GET /new Resource Method.

@GET("/new")
public String redirectTarget() {
  return "Hello from /new!";
}

301 Moved Permanently

@GET("/test/301")
public Response test301() {
  return Response.withRedirect(
    RedirectType.HTTP_301_MOVED_PERMANENTLY, "/new"
  ).build();  
}

To test:

% curl -L -i 'http://localhost:8080/test/301'
HTTP/1.1 301 Moved Permanently
Content-Length: 0
Date: Sun, 21 Mar 2024 16:19:01 GMT
Location: /new

HTTP/1.1 200 OK
Content-Length: 16
Content-Type: text/plain; charset=UTF-8
Date: Sun, 21 Mar 2024 16:19:01 GMT

Hello from /new!

302 Found

@GET("/test/302")
public Response test302() {
  return Response.withRedirect(
    RedirectType.HTTP_302_FOUND, "/new"
  ).build();  
}

To test:

% curl -L -i 'http://localhost:8080/test/302'
HTTP/1.1 302 Found
Content-Length: 0
Date: Sun, 21 Mar 2024 16:19:01 GMT
Location: /new

HTTP/1.1 200 OK
Content-Length: 16
Content-Type: text/plain; charset=UTF-8
Date: Sun, 21 Mar 2024 16:19:01 GMT

Hello from /new!

303 See Other

@GET("/test/303")
public Response test303() {
  return Response.withRedirect(
    RedirectType.HTTP_303_SEE_OTHER, "/new"
  ).build();  
}

To test:

% curl -L -i 'http://localhost:8080/test/303'
HTTP/1.1 303 See Other
Content-Length: 0
Date: Sun, 21 Mar 2024 16:19:01 GMT
Location: /new

HTTP/1.1 200 OK
Content-Length: 16
Content-Type: text/plain; charset=UTF-8
Date: Sun, 21 Mar 2024 16:19:01 GMT

Hello from /new!

307 Temporary Redirect

@GET("/test/307")
public Response test307() {
  return Response.withRedirect(
    RedirectType.HTTP_307_TEMPORARY_REDIRECT, "/new"
  ).build();  
}

To test:

% curl -L -i 'http://localhost:8080/test/307'
HTTP/1.1 307 Temporary Redirect
Content-Length: 0
Date: Sun, 21 Mar 2024 16:19:01 GMT
Location: /new

HTTP/1.1 200 OK
Content-Length: 16
Content-Type: text/plain; charset=UTF-8
Date: Sun, 21 Mar 2024 16:19:01 GMT

Hello from /new!

308 Permanent Redirect

@GET("/test/308")
public Response test308() {
  return Response.withRedirect(
    RedirectType.HTTP_308_PERMANENT_REDIRECT, "/new"
  ).build();  
}

To test:

% curl -L -i 'http://localhost:8080/test/308'
HTTP/1.1 308 Permanent Redirect
Content-Length: 0
Date: Sun, 21 Mar 2024 16:19:01 GMT
Location: /new

HTTP/1.1 200 OK
Content-Length: 16
Content-Type: text/plain; charset=UTF-8
Date: Sun, 21 Mar 2024 16:19:01 GMT

Hello from /new!

Custom

It's not required to use Soklet's RedirectType shorthand for redirects - manually setting the HTTP status code and Location response header works just as well.

@GET("/test/307-custom")
public Response test307Custom() {
  return Response.withStatusCode(307)
    .headers(Map.of("Location", List.of("/new")))
    .build();
}
Previous
Request Handling