【发布时间】:2014-03-06 00:01:13
【问题描述】:
我有一些路线。
(defroutes some-routes
(GET "one" [] one)
(GET "two" [] two))
(defroutes other-routes
(GET "three" [] three)
(GET "four" [] four))
(defroutes more-routes
(GET "five" [] five)
(GET "six" [] six))
(def all-routes
(routes app-routes
(-> some-routes session/wrap-session my-interceptor)
(-> more-routes session/wrap-session my-other-interceptor)
other-routes))
我想拦截some-routes 但不是other-routes 并根据请求执行测试(检查会话中是否存在密钥以及其他一些内容)。我有不止一个。 my-other-interceptor 做同样的事情但不同。
所以我从这个开始:
(defn my-interceptor [handler]
(fn [request]
(prn (-> request :session :thing-key))
(let [thing (-> request :session :thing-key-id)]
(if (nil? thing)
(-> (response "Not authenticated"))
(handler request)))))
如果在会话中设置了:thing-key,这将允许访问处理程序。
不幸的是,这与拥有一组以上的路线并不能很好地配合。此检查应仅适用于 some-routes 而不适用于 other-routes。但是在我们执行处理程序之前,我们不知道路由是否匹配。并且此时处理程序已经执行。我可以重写它以执行handler,然后仅在响应为非零时执行检查,但这意味着我在检查身份验证之前已经执行了一个处理程序。
我关注了this example,出现了问题:
(defn add-app-version-header [handler]
(fn [request]
(let [resp (handler request)
headers (:headers resp)]
(assoc resp :headers
(assoc headers "X-APP-INFO" "MyTerifficApp Version 0.0.1-Alpha")))))
我该怎么做?我想要的是:
- 一种在处理请求之前检查响应(和一些其他逻辑)的方法
- 我可以将其应用于大量路由的处理程序
- 不适用于应用中的所有路由
- 我将有多个这样的处理程序对会话进行不同类型的检查
我该怎么做呢?
【问题讨论】: