我目前正在使用 Compojure(以及 Ring 和相关中间件)在 Clojure 中编写 API。
我正在尝试根据路由应用不同的身份验证代码。考虑以下代码:
(defroutes public-routes
(GET "/public-endpoint" [] ("PUBLIC ENDPOINT")))
(defroutes user-routes
(GET "/user-endpoint1" [] ("USER ENDPOINT 1"))
(GET "/user-endpoint2" [] ("USER ENDPOINT 1")))
(defroutes admin-routes
(GET "/admin-endpoint" [] ("ADMIN ENDPOINT")))
(def app
(handler/api
(routes
public-routes
(-> user-routes
(wrap-basic-authentication user-auth?)))))
(-> admin-routes
(wrap-basic-authentication admin-auth?)))))
这不能按预期工作,因为wrap-basic-authentication
确实包装了路由,因此无论包装的路由如何,它都会被尝试。具体来说,如果请求需要被路由到admin-routes
,user-auth?
仍然会被尝试(并且失败)。
我求助于在公共基本路径context
下根植一些路由,但这是一个相当大的限制(下面的代码可能不起作用,它只是为了说明这个想法):
(defroutes user-routes
(GET "-endpoint1" [] ("USER ENDPOINT 1"))
(GET "-endpoint2" [] ("USER ENDPOINT 1")))
(defroutes admin-routes
(GET "-endpoint" [] ("ADMIN ENDPOINT")))
(def app
(handler/api
(routes
public-routes
(context "/user" []
(-> user-routes
(wrap-basic-authentication user-auth?)))
(context "/admin" []
(-> admin-routes
(wrap-basic-authentication admin-auth?))))))
我想知道我是否遗漏了某些东西,或者是否有任何方法可以在不受限制且不使用通用基本路径的情况下实现我想要defroutes
的(理想情况下,不会有)。