by Luke VanderHart and Adam Bard
Read from the :headers
key in a Ring request map, or assoc
values
onto the response map before returning from a Ring handler function.
To follow along with this recipe, clone the https://github.com/clojure-cookbook/ringtest repository and overwrite src/ringtest.clj:
(ns ringtest
(:require
[ring.adapter.jetty :as jetty]))
(defn user-agent-as-json
"A handler that returns the User-Agent header as a JSON
response with an appropriate Content-Type"
[req]
{:body (str "{\"user-agent\": \"" (get-in req [:headers "user-agent"]) "\"}")
:headers {"Content-Type" "application/json"}
:status 200})
(defn -main []
;; Run the server on port 3000
(jetty/run-jetty user-agent-as-json {:port 3000}))
This example defines a Ring handler that returns the incoming
User-Agent
header as a JSON response. It gets the User-Agent
from
the request header map, and uses a Content-Type
header in the response
to indicate to the client that it should be parsed as JSON.
Ring passes request headers as a :headers
parameter in the request
map, and accepts a :headers
parameter in response maps as well. The
keys and values of the headers map should both be strings. Clojure
keywords are not supported.
You can use Ring to set any header that is valid in HTTP.
According to RFC-2616, header
names are not case sensitive. To make it easier to consistently
get
values from the request map, no matter what their case, Ring
passes in all header values as lowercase, regardless of what the
client sent. You may wish to send headers using the actual
capitalization used in the specification, though, just in case the
client you’re communicating with is not compliant (following the
classic robustness principle: "Be conservative in what you send; be
liberal in what you accept").
-
Ring’s concepts documentation