clojure - 如何绑定(bind)动态变量?

标签 clojure binding compojure compojure-api

如何在 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/

相关文章:

python - Python中的 "bind to variables"和 "bind to object"有什么区别

iis - IIS 在哪里存储有关每个绑定(bind)的 SSL 证书协议(protocol)映射的信息?

clojure - 您如何使用 Compojure/Ring 的 session ?

tomcat - Compojure 静态资源在开发中工作但在生产中不工作

unit-testing - 如何使用 with-redefs 模拟对同一函数的多次调用?

clojure - 函数调用->线程宏

http - 如何修复 ERR_INVALID_CHUNKED_ENCODING 错误?

WPF (MVVM) 数据绑定(bind)问题

model-view-controller - Clojure 模型- View - Controller (MVC) 设计

Clojure 规范 : checking map values directly?