如何在 compojure 请求中获取特定的 http header
How can I get a specific http header in a compojure request
我从这样的请求中得到 body 和 header:
(POST "/api/item" {body :body headers :headers} (create-item body headers))
body 被换行了,所以我得到了一个关键字映射,我可以轻松地从中获取值:
(def app
(-> (handler/api app-routes)
(middleware/wrap-json-body {:keywords? true})
(middleware/wrap-json-response)))
简单如:
(:item-name body)
如何使用 header 实现相同的效果,或者只是采用特定的 header 值?我必须先将 header 映射到 Clojure 数据结构吗?
如果我打印 headers 我会得到这样的结果:
({host localhost:3000, user-agent Mozilla/5.0})
headers 已经在 Clojure 数据结构中。如果您想更好地了解存在的数据类型,请使用 prn
而不是 println
,您会看到它是一个 hash-map,以字符串作为键。
(:foo x)
是 (get x :foo)
的快捷方式。对于带有字符串键的 hash-map ,您可以使用例如获得一个值。 (get headers "host")
。 clojure.walk
、clojure.walk/keywordize-keys
中有一个函数可以将数据结构的键转变成关键字,递归地通过嵌套结构。恕我直言,这有点傻,在大多数情况下最好使用 get
和字符串键。
我从这样的请求中得到 body 和 header:
(POST "/api/item" {body :body headers :headers} (create-item body headers))
body 被换行了,所以我得到了一个关键字映射,我可以轻松地从中获取值:
(def app
(-> (handler/api app-routes)
(middleware/wrap-json-body {:keywords? true})
(middleware/wrap-json-response)))
简单如:
(:item-name body)
如何使用 header 实现相同的效果,或者只是采用特定的 header 值?我必须先将 header 映射到 Clojure 数据结构吗?
如果我打印 headers 我会得到这样的结果:
({host localhost:3000, user-agent Mozilla/5.0})
headers 已经在 Clojure 数据结构中。如果您想更好地了解存在的数据类型,请使用 prn
而不是 println
,您会看到它是一个 hash-map,以字符串作为键。
(:foo x)
是 (get x :foo)
的快捷方式。对于带有字符串键的 hash-map ,您可以使用例如获得一个值。 (get headers "host")
。 clojure.walk
、clojure.walk/keywordize-keys
中有一个函数可以将数据结构的键转变成关键字,递归地通过嵌套结构。恕我直言,这有点傻,在大多数情况下最好使用 get
和字符串键。