如何在 compojure 中绑定(bind)动态变量?请参阅下面的示例,这里的 request-id 是为每个 api 请求生成的唯一 uuid。我希望能够在后续的日志记录等方法中访问此 request-id。我已尝试使用绑定(bind)功能,但仍然无法在 some- 中访问 request-id页面/某些方法
。
处理程序.clj
(ns some_app.handler
(:require
[compojure.api.sweet :refer :all]
[compojure.route :as route]
[some_api.some_page :as some-page]))
(def ^:dynamic *request-id*
nil)
(defn ^:private generate-request-id []
(str (java.util.UUID/randomUUID)))
(def app
(binding [*request-id* (generate-request-id)]
(api
(context "/api" [] (GET "/some-page" [] (some-page/some-method))))))
一些页面.clj
(ns some_app.some_page
(:require
[clojure.tools.logging :as log]))
(def some-method []
(log/info {:request-id *request-id*}))
最佳答案
此处对绑定(bind)的调用位置错误。绑定(bind)应该在处理请求时生效,而不是在构建 app/api 时生效。
您需要一些中间件来执行此操作:
(defn with-request-id
[f]
(fn [request]
(binding [*request-id* (generate-request-id)]
(f request)))
(def app
(with-request-id
(api ... ))
另请参阅Ring Concepts
关于clojure - 如何绑定(bind)动态变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48064434/