Liking cljdoc? Tell your friends :D

org.httpkit.server


as-channelclj

(as-channel ring-req
            {:keys [on-receive on-ping on-close on-open init on-handshake-error]
             :or {on-handshake-error
                    (fn [ch] (send! ch bad-ring-websocket-resp true))}})
Returns `{:body ch}`, where `ch` is the request's underlying
asynchronous HTTP or WebSocket `AsyncChannel`.

Main options:
  :init       - (fn [ch])             for misc pre-handshake setup.
  :on-receive - (fn [ch message])     called for client WebSocket messages.
  :on-ping    - (fn [ch data])        called for client WebSocket pings.
  :on-close   - (fn [ch status-code]) called when AsyncChannel is closed.
  :on-open    - (fn [ch])             called when AsyncChannel is ready for `send!`, etc.

See `Channel` protocol for more info on handlers and `AsyncChannel`s.
See `org.httpkit.timer` ns for optional timeout utils.

---

Example - Async HTTP response:

  (def clients_ (atom #{}))
  (defn my-async-handler [ring-req]
    (as-channel ring-req
      {:on-open (fn [ch] (swap! clients_ conj ch))}))

  ;; Somewhere else in your code
  (doseq [ch @clients_]
    (swap! clients_ disj ch)
    (send! ch {:status 200 :headers {"Content-Type" "text/html"}
               :body "Your async response"}
      ;; false ; Uncomment to use chunk encoding for HTTP streaming
      ))

Example - WebSocket response:

  (defn my-chatroom-handler [ring-req]
    (if-not (:websocket? ring-req)
      {:status 200 :body "Welcome to the chatroom! JS client connecting..."}
      (as-channel ring-req
        {:on-receive (fn [ch message]     (println "on-receive:" message))
         :on-close   (fn [ch status-code] (println "on-close:"   status-code))
         :on-open    (fn [ch]             (println "on-open:"    ch))})))
source

Channelcljprotocol

Unified asynchronous channel interface for HTTP (streaming or long-polling)
and WebSocket.

on-receiveclj

(on-receive ch callback)
Sets handler (fn [message]) for notification of client WebSocket
messages. Message ordering is guaranteed by server.

The message argument could be a string or a byte[].

writable?clj

(writable? ch)
Is the peer keeping up?

False once more than `:queue-high-water-bytes` is queued for this
connection, and true again only once the queue falls below
`:queue-low-water-bytes` -- two marks, so a connection sitting at the
boundary does not flip state on every write.

`send!` is unaffected: a write past the mark is still accepted. This is how
a caller decides whether to offer more, and `on-writable` is how it learns
it may resume. Same shape as Netty's `Channel.isWritable()`.

send!clj

(send! ch data)
(send! ch data close-after-send?)
Sends data to client and returns true if the data was successfully sent,
or false if the channel is closed. Data is sent directly to the client,
NO RING MIDDLEWARE IS APPLIED.

When unspecified, `close-after-send?` defaults to true for HTTP channels
and false for WebSocket.

Data form: {:headers _ :status _ :body _} or just body. Note that :headers
and :status will be stripped for WebSocket and for HTTP streaming responses
after the first.

For WebSocket, a text frame is sent to client if data is String,
a binary frame when data is byte[] or InputStream. For for HTTP streaming
responses, data can be one of the type defined by Ring spec

on-closeclj

(on-close ch callback)
Sets handler (fn [status-code]) for notification of channel being closed by
the server or client. Handler will be invoked at most once. Useful for clean-up.

Callback status argument:
  :server-close   : Channel closed by sever
  :client-close   : HTTP channel closed by client
  :normal         : WebSocket closed by client (CLOSE_NORMAL)
  :going-away     : WebSocket closed by client (CLOSE_GOING_AWAY)
  :protocol-error : WebSocket closed by client (CLOSE_PROTOCOL_ERROR)
  :unsupported    : WebSocket closed by client (CLOSE_UNSUPPORTED)
  :unknown        : WebSocket closed by client (unknown reason)

on-pingclj

(on-ping ch callback)
Sets handler (fn [data]) for notification of client WebSocket pings. The
data param represents application data and will by a byte[].

on-writableclj

(on-writable ch callback)
Register a one-shot `(fn [])` continuation for writable state.

If the channel is already writable it is scheduled immediately; otherwise
it is called once when writability is restored. Registration and state
observation are atomic, so the restore edge cannot be lost after a caller
observed `writable?` as false.

Runs on the IO thread: offer more data and return, do not block.

closeclj

(close ch)
Closes the channel. Idempotent: returns true if the channel was actually
closed, or false if it was already closed.

websocket?clj

(websocket? ch)
Returns true iff channel is a WebSocket.

open?clj

(open? ch)
Returns true iff channel is open.

queued-bytesclj

(queued-bytes ch)
Bytes accepted from the application but not yet written to the socket for
this channel. A gauge, for metrics; stale on return by construction.
source

IHttpServercljprotocol

-server-stop!clj

(-server-stop! http-server opts)

server-portclj

(server-port http-server)
Given an HttpServer, returns server's local port.

server-statusclj

(server-status http-server)
Given an HttpServer, returns server's status e/o #{:stopped :running :stopping}.
source

new-workerclj

(new-worker {:keys [queue-size n-min-threads n-max-threads prefix
                    allow-virtual?]
             :as opts})
Returns {:keys [n-cores type pool ...]} where `:pool` is a new
`java.util.concurrent.ExecutorService` for handling server requests.

When on JVM 21+, uses `newVirtualThreadPerTaskExecutor` by default.
Otherwise creates a standard `ThreadPoolExecutor` with default min and max
thread count auto-selected based on currently available processor count.
source

run-serverclj

(run-server handler
            &
            [{:keys [ip port max-body max-ws max-line websocket-compression?
                     websocket-max-message-size websocket-compression-threshold
                     proxy-protocol worker-pool error-logger warn-logger
                     event-logger event-names legacy-return-value?
                     legacy-unsafe-remote-addr? legacy-content-length?
                     server-header address-finder max-queued-bytes
                     queue-high-water-bytes queue-low-water-bytes
                     channel-factory ring-async?]
              :as opts
              :or {max-ws 4194304
                   ring-async? false
                   legacy-unsafe-remote-addr? true
                   max-body 8388608
                   max-line 8192
                   websocket-max-message-size 0
                   server-header "http-kit"
                   ip "0.0.0.0"
                   proxy-protocol :disable
                   websocket-compression-threshold 0
                   websocket-compression? false
                   port 8090
                   legacy-return-value? true
                   legacy-content-length? true}}])
Starts a mostly[1] Ring-compatible HttpServer with options:

  :ip                         ; Which IP to bind (default: 0.0.0.0)
  :port                       ; Which port to listen to for incoming requests

  :worker-pool                ; `java.util.concurrent.ExecutorService` or delay to use
                              ; for handling requests. Defaults to (:pool (new-worker {})).
                              ; See `new-worker` for details.

  :max-body                   ; Max HTTP body size in bytes (default: 8MB)
  :max-ws                     ; Max WebSocket message size in bytes (default: 4MB)
  :max-line                   ; Max HTTP header line size in bytes (default: 8KB)

  :websocket-compression?     ; Accept a client's RFC 7692 `permessage-deflate`
                              ; offer? (default: false)
  :websocket-max-message-size ; Max WebSocket message size in bytes AFTER
                              ; decompression (default: `:max-ws`)
  :websocket-compression-threshold ; Send messages smaller than this many bytes
                              ; uncompressed (default: 0, i.e. compress all).
                              ; See the wiki for when to raise it.

  :max-queued-bytes           ; Per-connection close threshold for queued write
                              ; bytes. Concurrent producers may overshoot before
                              ; the selector closes. DEFAULT 0 (OFF).
                              ; Off because a size threshold cannot yet tell a
                              ; stalled peer from a large response: http-kit
                              ; materialises a whole body into one buffer, so a
                              ; 100MB download to a healthy client arrives as one
                              ; 100MB enqueue. Enable it for servers whose
                              ; responses are small and incremental (WebSocket,
                              ; SSE). Worst case is this times max connections.
  :queue-high-water-bytes     ; Per-connection mark above which `writable?` is
                              ; false (default: 64KB, as Netty). <=0 disables.
  :queue-low-water-bytes      ; ...and below which it becomes true again
                              ; (default: 32KB). Two marks give hysteresis: with
                              ; one, a connection at the boundary flips on every
                              ; write. Must not exceed the high mark.

  :proxy-protocol             ; Proxy protocol e/o #{:disable :enable :optional}

  :server-header              ; The "Server" header, disabled if nil. Default: "http-kit".

  :legacy-unsafe-remote-addr? ; If true (default), populates :remote-addr from
                              ; X-Forwarded-For header if present. This is INSECURE as it
                              ; allows IP spoofing. If false, :remote-addr always contains
                              ; the immediate connection's IP (socket address), matching
                              ; Ring's standard behavior. The X-Forwarded-For header remains
                              ; available in :headers for parsing trusted proxies.
                              ; In some future version, this option will be defaulted to false

  :error-logger               ; (fn [msg ex])  -> log errors
  :warn-logger                ; (fn [msg ex])  -> log warnings
  :event-logger               ; (fn [ev-name]) -> log events
  :event-names                ; Map of http-kit event names to loggable event names

  :legacy-content-length? ; When true (default), calculates HEAD Content-Length from its body.
                          ; When false, a HEAD handler may provide Content-Length without a body.

  ;; These opts may be used for Unix Domain Socket (UDS) support, see README:
  :address-finder             ; (fn []) -> `java.net.SocketAddress` (ip/port ignored)
  :channel-factory            ; (fn [java.net.SocketAddress]) -> `java.nio.channels.SocketChannel`

If :legacy-return-value? is
  true  (default)             ; Returns a (fn stop-server [& {:keys [timeout] :or {timeout 100}}])
  false (recommended)         ; Returns the `HttpServer` which can be used with `server-port`,
                              ; `server-status`, `server-stop!`, `server-join`, etc.

The server also supports the following JVM properties:

   `org.http-kit.memmap-file-threshold`
     Files above this size (in MB) are mapped into memory for efficiency when served.
     Memory mapping could result to file locking. Defaults to 20 (MB).

[1] Ref. http://http-kit.org/migration.html for differences.
source

sec-websocket-acceptclj

(sec-websocket-accept sec-websocket-key)
source

send-checked-websocket-handshake!clj

(send-checked-websocket-handshake! ch sec-ws-accept)
(send-checked-websocket-handshake! ch sec-ws-accept ring-req)
Given an AsyncChannel and `sec-ws-accept` string, unconditionally
sends handshake to upgrade given AsyncChannel to a WebSocket.
See also `websocket-handshake-check`.
source

send-websocket-handshake!clj

(send-websocket-handshake! ch ring-req)
Returns true iff successfully upgraded a valid WebSocket request.
source

server-joinclj

(server-join server)
Joins given `HttpServer` server thread, blocking the current thread until
server is stopped.
source

server-stop!clj

(server-stop! http-server)
(server-stop! http-server opts)
Signals given `HttpServer` to stop.

If     already stopping: returns nil.
If not already stopping: returns a Promise that will be delivered once
server thread actually completes.

Options:
  :timeout ; Max msecs to allow existing requests to complete before attempting
           ; interrupt (default 100).
source

websocket-handshake-checkclj

(websocket-handshake-check ring-req)
Returns `sec-ws-accept` string iff given Ring request is a valid
WebSocket handshake.
source

with-channelcljmacrodeprecated

(with-channel ring-req ch-name & body)
DEPRECATED: this macro has potential race conditions, Ref. #318.
Prefer `as-channel` instead.
source

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