Requests and responses
Handlers speak Ring: a handler is a function of a request map that answers a response map.
The request map
| key | value |
|---|---|
:request-method | lower-cased keyword: :get, :post, :purge |
:uri | the target up to the first ?, raw (not percent-decoded); an absolute-form target is reduced to its path |
:query-string | the text after the first ?, or nil without one |
:protocol | "HTTP/1.1" or "HTTP/1.0" |
:scheme | :http, or :https over TLS |
:headers | {lower-cased-name value}; repeated header lines are joined with "," (Cookie included, as ring-jetty does) |
:server-port, :server-name, :remote-addr | from the accepted socket and the Host header ("localhost" without one), or from proxy headers when the peer is trusted (below) |
:body | a java.io.ByteArrayInputStream over the raw bytes, empty when there is no body; a streamed body is an InputStream over the socket (below) |
So a handler reads a JSON body with (json/decode (slurp (:body req))). Plumeria doesn't parse query strings or forms. ring-core's middleware does that, see Ring middleware below.
The response map
A response is {:status :headers :body}. A header value may be a collection, which goes out as one line per element ("Set-Cookie" ["a=1" "b=2"]). The :body decides the framing:
:body | sent as |
|---|---|
nil, a String, a byte[] | Content-Length (Strings as UTF-8) |
java.io.File | Content-Length from .length, read on the disk pool in 64 KB slices; a file that can't be opened answers 500 |
java.io.InputStream | chunked (HTTP/1.1) or close-delimited (HTTP/1.0), read in 64 KB slices |
a seq, list or vector of Strings and byte[]s | chunked or close-delimited, one chunk per element |
| anything else | Content-Length, via str |
The server closes an InputStream body on every path, including HEAD, 204 and a failed write.
A HEAD request gets the headers a GET would get and no body. A handler that skips building the body can set Content-Length itself. A 1xx, 204 or 304 gets no body at all. A response header whose value holds a control character such as CR or LF, or whose name isn't a token, is dropped and reported to :on-error as :header-dropped.
Streaming and Server-Sent Events
Return :stream in place of :body to write a response as it's produced:
{:status 200
:headers {"Content-Type" "text/plain"}
:stream (fn [write!]
(write! "first\n")
(write! "second\n"))}
Each write! goes out as one chunk, and keep-alive is preserved. An HTTP/1.0 client has no chunked coding, so it gets the raw bytes with Connection: close, and the end of the body is the close. plumeria.response/sse is a thin Server-Sent Events helper on top.
Request bodies
By default a body is read whole, up to :max-body (10 MiB), before the handler runs. A Content-Length body and a Transfer-Encoding: chunked body both arrive as bytes in :body; a chunked body's trailers are checked and dropped. An HTTP/1.1 request with Expect: 100-continue gets its 100 Continue just before the body is read, and a body over the limit gets 413 without one.
The chunked decoder caps a chunk-size line at 4096 bytes, the chunk count at (max 16384 (quot max-body 64)), the wire bytes at max-body + 65536 and the trailers at 8192 bytes (431). A Transfer-Encoding with a Content-Length, on HTTP/1.0, or with chunked missing, repeated or not last is 400, and another coding before chunked is 501.
Streamed request bodies
Set :stream-body to true, or to a predicate on the request map without :body, and a request it picks gets a :body InputStream that reads from the socket as the handler consumes it. Content-Length and chunked bodies both work this way, so an upload is never held in memory.
(http/run-server handler {:port 18090
:stream-body (fn [req] (= "/upload" (:uri req)))})
| option | default | |
|---|---|---|
:max-stream-body | 1 GiB | a larger Content-Length gets 413 before the handler runs |
:body-read-ms | 30000 | how long one read may wait for bytes |
The 100 Continue goes out on the handler's first read, so a handler that answers without reading never invites the upload. A read that fails throws IOException. If the handler lets it escape, the server answers 408, 400, 413 or 431 as it would for a buffered body, and closes the connection. When the handler leaves part of the body unread, the server drains up to 64 KB of it before responding and keeps the connection only if that reaches the end. Don't return (:body req) as the response of a streamed request: the stream is finished when the handler returns.
Routing
plumeria.router dispatches on :request-method and :uri:
(require '[plumeria.router :as r])
(def app
(r/router
[(r/GET "/" (fn [_] {:status 200 :body "home"}))
(r/GET "/users/:id" (fn [req] {:status 200 :body (get-in req [:path-params :id])}))
(r/POST "/files/*path" upload-handler)]))
An exact match wins, then :name segments, then a final *name catch-all. :path-params are percent-decoded as UTF-8, and a bad escape answers 400 without calling a handler. HEAD falls back to the GET route, a path that has routes only for other methods answers 405 with Allow (204 for OPTIONS), and an unknown path is 404. The helpers are GET, POST, PUT, PATCH, DELETE, HEAD and OPTIONS. examples/routed_server.clj is a whole server.
Behind a proxy
When a reverse proxy terminates TLS, every request looks as if it came from the proxy over plain HTTP. Name the proxy's addresses and the server reads what it says about the client:
(http/run-server handler {:port 8080 :trusted-proxies ["127.0.0.1" "10.0.0.0/8"]})
:trusted-proxies takes IPv4 and IPv6 addresses and CIDR ranges, and a bad entry throws before the server binds. For a request whose peer is one of them, :remote-addr, :scheme, :server-name and :server-port come from its Forwarded header (RFC 7239) when it has one, else from X-Forwarded-For, -Proto, -Host and -Port. The client address is the rightmost entry in the chain that isn't a trusted proxy, so a client can't pose as another address by starting the chain itself. The scheme, host and port come from the value the nearest proxy wrote, and the port falls back to 443 or 80 by the forwarded scheme. A request from any other peer is left alone whatever it sends, and the headers stay in :headers either way.
Forwarded wins when present, so every trusted proxy must set or strip it. A proxy that only appends X-Forwarded-For and passes a client's own Forwarded header through lets that client choose its address.
Ring middleware
ring-core 1.15.3 runs on Jolt. wrap-params and wrap-keyword-params are tested against a real server in ring_compat_test. Plumeria doesn't depend on ring-core, so add it to your own deps.edn:
{:deps {ring/ring-core {:git/url "https://github.com/ring-clojure/ring"
:git/sha "fd08dd8d905bc8062866cfec938c8cbf65afc7b0"
:deps/root "ring-core"}
ring/ring-codec {:git/url "https://github.com/ring-clojure/ring-codec"
:git/sha "1b2bdf11bcd057720141124e5f33c6f3e2a46790"}}}
Cookies and sessions. ring.middleware.cookies and ring.middleware.session need java.util.Locale, which Jolt core doesn't have. jolt-lang/time provides one, so add it next to ring-core:
io.github.jolt-lang/time {:git/url "https://github.com/jolt-lang/time.git"
:git/sha "b6d64a9ea4a71c6d40f66d0c3c9c4fff28f1bf8c"}
With it, both work against a real server: :cookies is parsed from the request, each response cookie goes out as its own Set-Cookie line, :expires takes a java.time.ZonedDateTime (ring 1.15 doesn't take a java.util.Date, on the JVM either) and :max-age an int or a Duration, and the default memory session store keeps a session across connections. A client that sends several Cookie lines gets them joined with ",", which ring's parser splits back into separate cookies.
ring.util.response loads without jolt-lang/time, but file-response needs java.util.Locale when it's called, for its Last-Modified date. Returning a java.io.File as the :body needs nothing extra.
For uploads, Ring's wrap-multipart-params needs Apache commons-fileupload, which doesn't run on Jolt. Use plumeria.multipart instead.