我正在尝试用ring和compojure学习clojure web开发,我对compojure.route/resources
and 的用法有点不清楚ring.middleware.resource/wrap-resource
.
我已经看过了API文档,以及两者的来源compojure.route
和ring.middleware.resource
.但是,我仍然不清楚是否需要使用compojure.route/resources
路由和ring.middleware.resource/wrap-resource
中间件,或者是否compojure.route/resources
需要处理所有事情.
还是优化问题?在使用中,wrap-resource
避免使用组件路由开销?任何见解将不胜感激.
主要区别compojure.route/resources
仅在于提供来自特定路径的资源:
(let [root (:root options "public")] (resource-response (str root "/" resource-path))
但是ring.middleware.resource/wrap-resource
如果没有找到资源,则在处理程序上提供故障恢复机制:
(or (response/resource-response path {:root root-path}) (handler request))
当你从看到的resource-response
功能两种选择使用:
(defn resource-response "Returns a Ring response to serve a packaged resource, or nil if the resource does not exist. Options: :root - take the resource relative to this root"
nil
如果找不到请求的资源,则返回.
因此,wrap-resource
如果您已经有路线,则替代方案更适合链接,如:
(defroutes routes (GET "/" [] "<h1>Hello World</h1>") (route/not-found "<h1>Page not found</h1>")) (def app (-> routes (wrap-resource "public/resources"))
而且compojure.route/resources
您可以使用路线组成,如:
(defroutes resources-routes (route/resources "/")) (defroutes routes (GET "/" [] "<h1>Hello World</h1>") (route/not-found "<h1>Page not found</h1>")) (def app (compojure.core/routes resources-routes routes))