Liking cljdoc? Tell your friends :D

Ring requests and responses

This reference lists the request fields Busker supplies, the response forms it accepts, and known compatibility limits. See Ring compatibility for the reasons behind its handler and streaming model.

Busker accepts only synchronous (one-argument) Ring handlers; a handler receives one request map and returns one response map. Ring’s asynchronous (three-argument) handler API is not supported, and neither is middleware that requires it. Busker requires JDK 25 and runs each handler on a virtual thread.

Request maps

Busker supplies these Ring keys on every request. It sets :body or :query-string to nil when the request has no body or query string.

KeyValueNotes

:server-port

Integer

Port selected from the request authority.

:server-name

String

Host selected from the request authority.

:remote-addr

String

Client address, usually numeric for TCP and possibly nonnumeric or empty for Unix sockets or lookup failures.

:uri

String

Path without the query string.

:query-string

String or nil

Text after ?, without the ?.

:scheme

Keyword

:http or :https.

:request-method

Keyword

Lowercase method such as :get, :head, or :post.

:protocol

String

"HTTP/1.1", "HTTP/2.0", or "HTTP/3.0".

:headers

Map of String to String, or nil

Header names are lowercase.

:body

java.io.InputStream or nil

A stream for the request body.

Ring requires :headers to be a map. Busker currently sets it to nil when the libh2o request contains no ordinary headers. This empty-header case is a known Ring incompatibility.

Busker does not supply Ring’s deprecated :character-encoding, :content-length, or :content-type request keys. Read those values from :headers. It also does not supply :ssl-client-cert, as client certificate authentication is not implemented.

Busker joins duplicate request header values in arrival order. It uses the ASCII comma delimiter for ordinary fields and the ASCII semicolon delimiter for cookie, as Ring requires.

Busker request keys

KeyValueMeaning

:ol.busker/entrypoint

Keyword

The entrypoint, a named listener group, whose listener accepted the connection.

:ol.busker/early-data?

Boolean

True when the TLS handshake had not finished when the request was handed to the handler. Such a request arrived in 0-RTT early data and may be a replay.

:ol.busker.request/emitter

ResponseEmitter

The response stream for this request.

The Host header and the HTTP/2 or HTTP/3 :authority do not change :ol.busker/entrypoint, so a client cannot reach a dispatcher restricted to another entrypoint by naming that entrypoint’s port. A request map built by hand without this key, for example in a test that calls the dispatch handler directly, is treated as a request to the first configured entrypoint.

The early-data flag is always present, including on ordinary requests where its value is false. A request sent in 0-RTT data reads false when the handshake finished before the request was handed over, because a replayed request cannot finish the handshake. Only HTTP/3 accepts 0-RTT data, so over TCP the flag is always false. Busker’s wrap-reject-early-data middleware can reject unsafe methods received through 0-RTT.

Request bodies

A handler reads :body as an InputStream. Busker requests another libh2o body chunk as the handler consumes the current chunk, so a slow reader does not make Busker read the whole upload into JVM memory first. A read may wait for the client. Busker runs each handler on a virtual thread, a lightweight JVM thread managed by the request executor for that runtime generation. Busker does not run the handler on the event loop thread that drives socket I/O.

The stream is single-use and closes when the request ends or the client disconnects. Busker does not parse form, multipart, or other request data into parameters. Add the Ring middleware that your application needs. Set :max-request-entity-size to reject an upload above a chosen byte limit.

Response maps

An ordinary handler response uses the usual Ring shape:

{:status 200
 :headers {"content-type" "text/plain; charset=utf-8"}
 :body "ok"}

Ring defines status codes from 100 through 599. Busker accepts integer final statuses from 200 through 999. Applications should keep ordinary final statuses in the Ring range of 200 through 599. Busker treats an omitted :headers map as empty and an omitted or nil :body as an empty body. If a handler returns nil, Busker sends a 404 response.

Response header names are strings in any letter case. Busker sends them in lowercase on every protocol, as HTTP/2 and HTTP/3 require. Busker sends scalar strings unchanged and applies str to other scalar values. It emits each element of a sequential response header value as a separate field line, in sequence order. This supports Ring vector values and the sequential Set-Cookie values produced by wrap-cookies and wrap-session.

Busker sets no limit on response headers. A head above 64 header pairs or 16384 staging bytes takes the streaming path. Busker logs at most one :ol.busker.response/large-head warning a minute for such heads.

Busker does not infer a response content-type; set that header in the response or with middleware.

Response body types

ring.core.protocols/StreamableResponseBody is Ring’s general protocol for writing a response body (and is not specific onlyto streaming responses). When org.ring-clojure/ring-core-protocols is on the classpath, Busker accepts any value that satisfies this protocol. Ring provides implementations for:

  • byte[]

  • String

  • clojure.lang.ISeq

  • java.io.InputStream

  • java.io.File

  • nil

Applications may extend the protocol for another body type. Sequences and input streams can produce data as Busker reads them, as described in the next section.

Busker does not require ring-core-protocols. Without it, Busker’s writer accepts byte[], String, java.nio.ByteBuffer, java.io.InputStream, nil, and sequential collections of fallback values. The writer encodes a String with the response charset, using UTF-8 when the charset is absent or invalid. A charset that cannot encode gives 500 Internal Server Error. The writer writes a number as one byte using OutputStream.write(int). The writer does not accept java.io.File or custom Ring protocol implementations.

Streaming responses

Sequences and input streams

The ISeq or InputStream are the "traditional" streaming response types. A handler can return one of those as the :body ant the contents will be streamed to the client as it arrives.

Busker reads from that source and sends each part through a bounded response queue. The queue limits pending response data, and the writer waits for space when the client cannot keep up. Busker does not collect the whole body before the response starts (looking at you http-kit).

Response emitters

HTTP can do more than Ring’s single response map allows. Informational responses and responses that continue after the handler returns do not fit that model. Busker exposes those parts of HTTP through a ResponseEmitter for these HTTP features.

With an emitter, an application can:

  • send zero or more informational responses with statuses from 100 through 199, except 101 Switching Protocols;

  • send 103 Early Hints with link headers so the client can start preloading resources;

  • send 102 Processing while work continues;

  • send one final status and header map, followed by body data over time;

  • tell Busker when the response is complete; and

  • run application cleanup through an on-close! callback.

An informational response cannot contain a body. Each informational response has a separate complete header map. After the final response is committed, its status and headers cannot change.

The emitter is available in the request under :ol.busker.request/emitter. A handler uses it by returning it as the response body. The response then continues until the application closes or ends it. If the handler returns another response or throws after the emitter accepted final headers, Busker ends the response as failed.

In the example below, the handler starts a virtual thread to send the informational response, final response, and body data.

(require '[ol.busker.protocols :as response])

(defn my-handler
  [{emitter :ol.busker.request/emitter}]
  ;; register an on close handler
  (response/on-close! emitter #(println "event stream closed"))
  ;; do work in the background and emit events
  (Thread/startVirtualThread
   (fn []
     (try
       (response/emit! emitter
        {:status 103
         :headers {"link" "</events.css>; rel=preload; as=style"}})
       (Thread/sleep 1000)
       (response/emit! emitter
        {:status 200
         :headers {"cache-control" "no-cache"
                   "content-type" "text/event-stream"}})
       (doseq [event ["one" "two" "three"]]
         (response/emit! emitter (str "data: " event "\n\n"))
         (response/flush! emitter))
       (finally
         (response/close! emitter)))))
  ;; return the emitter right away with no additional data in the response map
  {:body emitter})

The first emit! sends 103 Early Hints, allowing the client to preload the stylesheet. The next emit! commits the final status and headers. Later calls accept body data, and flush! makes buffered data ready to send.

emit! parks the calling virtual thread when capacity is full. With {:wait? false} it returns {:status :full} and accepts no part of the call. flush! and close! never wait. An accepted body write returns {:status :accepted :progress receipt}, a promise of {:status :proceeded}, {:status :closed} or {:status :failed :cause error}.

The finally block closes the emitter whether the producer finishes normally or fails.

The zero-argument on-close! callback runs when Busker learns that the response has ended.

Emitter calls do not pass through Ring middleware. Set the emitted status, headers, and body data in the producer itself. See the ResponseEmitter protocol reference for the complete API and close behavior.

Nonblocking events and heartbeats

One application caller can keep the last receipt in an atom and skip writes while its output is pending:

(defn next-event! [emitter pending_ event]
  (let [receipt @pending_]
    (cond
      (and receipt (not (realized? receipt))) :pending
      (and receipt (not= :proceeded (:status @receipt))) :closed
      :else
      (let [result (response/emit! emitter event {:wait? false :flush? true})]
        (when (= :accepted (:status result))
          (reset! pending_ (:progress result)))
        (:status result)))))

A scheduled heartbeat can pass ":\n\n" to this function. Do not queue missed heartbeats. Use on-close! to remove closed connections. See HTTP/1 streaming timeouts for what heartbeats are for and how to choose their interval.

Content length

Busker uses an explicit content-length response header when present. Header lookup is case-insensitive, and the value must be a non-negative decimal string or number. Busker removes that field from the ordinary header map and passes its numeric value to libh2o.

The value must equal the byte length of the body, and Busker does not correct it. For a body whose length Busker knows, any other value is a handler error: Busker logs it and sends 500 Internal Server Error. Statuses 204, 205 and 304, and a HEAD response with an empty body, are not checked. For a body of unknown length, Busker never sends a byte past the value. A longer or shorter body fails the response: Busker logs it and closes the HTTP/1.1 connection or resets the HTTP/2 or HTTP/3 stream. A client of a longer body can receive every declared byte before the failure and take it as a complete response.

Without an explicit value, Busker calculates the byte length of String, byte[], java.nio.ByteBuffer (its remaining bytes), java.io.File, and nil bodies. Strings use the charset in content-type, or UTF-8 when it is absent or invalid, and malformed or unmappable characters use replacement bytes. A charset that Java can decode but not encode, such as x-JISAutoDetect, gives 500 Internal Server Error for a String or sequence body. Applications can extend SizableResponseBody for another fixed-size type.

Busker leaves the length unknown for streams and sequences. libh2o then chooses the framing required by the negotiated HTTP version, such as chunked transfer encoding for HTTP/1.1.

HEAD requests

HTTP defines HEAD with the same semantics as GET except that the server sends no response content. The response headers describe the representation that a corresponding GET request would receive. For example, content-length on a HEAD response gives the size of the GET response body, not the zero bytes sent for HEAD.

Busker passes the request to the application as :request-method :head. Busker sends no body bytes for HEAD. A HEAD response with a body of known length, such as a string, byte array, ByteBuffer or File, gets that length as content-length.

Ring provides the optional ring.middleware.head/wrap-head middleware for applications that want to reuse GET behavior. For a HEAD request, wrap-head calls the wrapped handler with :request-method :get and then replaces the returned body with nil. This lets an existing GET handler produce the status and headers for HEAD without duplicating handler logic. Applications may also handle HEAD explicitly.

If middleware derives content-length from the GET body, it must calculate the length before wrap-head replaces the body with nil. Otherwise Busker sees an empty body and sends no content-length. A HEAD handler can instead provide an explicit content-length equal to the number of bytes that the corresponding GET response would send.

Middleware

Synchronous Ring middleware works when it produces the request and response forms supported on this page. You can wrap the application handler yourself, or list wrappers in a dispatcher’s :middleware vector. The configuration reference accepts a wrapper function, a qualified symbol, or [wrapper options].

Can you improve this documentation?Edit on GitHub

cljdoc builds & hosts documentation for Clojure/Script libraries

Keyboard shortcuts
Ctrl+kJump to recent docs
←Move to previous article
→Move to next article
Ctrl+/Jump to the search field
× close