alundy
alundy

Reputation: 857

How can I get a specific http header in a compojure request

I am getting the body and headers from the request like this:

(POST "/api/item" {body :body headers :headers} (create-item body headers))

The body is wrapped, so I get a keyword map and I can easily take values from the that:

(def app
    (-> (handler/api app-routes)
        (middleware/wrap-json-body {:keywords? true})
        (middleware/wrap-json-response)))

As simple as:

(:item-name body)

How can I achieve the same with the headers, or just simply take a specific header value? Do I have to map the headers into a Clojure data structure first?

If I print headers I get something like this:

({host localhost:3000, user-agent Mozilla/5.0})

Upvotes: 2

Views: 1284

Answers (1)

noisesmith
noisesmith

Reputation: 20194

The headers are already in a Clojure data structure. If you want a better idea of the data types present, use prn instead of println, and you will see that it is a a hash-map with strings as keys.

(:foo x) is a shortcut for (get x :foo). For a hash-map with string keys you can get a value with eg. (get headers "host"). There is a function in clojure.walk, clojure.walk/keywordize-keys that will turn keys of a data structure into keywords, recursively through a nested structure. IMHO this is a bit silly, and one is better off using get and the string keys in most cases.

Upvotes: 3

Related Questions