Compojure使用“中间件”来处理 HTTP 请求,您可以查看它的实现。Compojure 中的“处理程序”是一个接受请求并返回响应的函数。(请求和响应都是 Clojure 哈希映射。)“中间件”是一个接受处理函数并返回不同处理函数的函数。中间件可以更改请求、响应或两者;它可以调用它传递的处理程序(如果需要,可以重复)或短路并忽略处理程序等。您可以以这种方式以任何组合将处理程序包装在其他处理程序中。
由于函数是一流的对象,因此它非常轻量级且易于实现和使用。但是,它不会像从 Java 接口获得的那样在编译时强制执行任何操作;这完全是遵循约定和鸭式打字的问题。协议最终可能对这项任务有好处,但它们暂时不会可用(可能在 Clojure 2.0 中?)
不确定这是否是您想要的,但这是一个非常基本的版本:
;; Handler
(defn default [msg]
{:from "Server"
:to (:from msg)
:response "Hi there."})
;; Middleware
(defn logger [handler]
(fn [msg]
(println "LOGGING MESSAGE:" (pr-str msg))
(handler msg)))
(defn datestamper [handler]
(fn [msg]
(assoc (handler msg)
:datestamp (.getTime (java.util.Calendar/getInstance)))))
(defn short-circuit [handler]
(fn [msg]
{:from "Ninja"
:to (:from msg)
:response "I intercepted your message."}))
;; This would do something with a response (send it to a remote server etc.)
(defn do-something [response]
(println ">>>> Response:" (pr-str response)))
;; Given a message and maybe a handler, handle the message
(defn process-message
([msg] (process-message msg identity))
([msg handler]
(do-something ((-> default handler) msg))))
然后:
user> (def msg {:from "Chester" :to "Server" :message "Hello?"})
#'user/msg
user> (process-message msg)
>>>> Response: {:from "Server", :to "Chester", :response "Hi there."}
nil
user> (process-message msg logger)
LOGGING MESSAGE: {:from "Chester", :to "Server", :message "Hello?"}
>>>> Response: {:from "Server", :to "Chester", :response "Hi there."}
nil
user> (process-message msg (comp logger datestamper))
LOGGING MESSAGE: {:from "Chester", :to "Server", :message "Hello?"}
>>>> Response: {:datestamp #<Date Fri Nov 27 17:50:29 PST 2009>, :from "Server", :to "Chester", :response "Hi there."}
nil
user> (process-message msg (comp short-circuit logger datestamper))
>>>> Response: {:from "Ninja", :to "Chester", :response "I intercepted your message."}
nil