使用compojure.route/resources和ring.middleware.resource/wrap-resource

 直属17262676 发布于 2023-02-13 17:13

我正在尝试用ring和compojure学习clojure web开发,我对compojure.route/resourcesand 的用法有点不清楚ring.middleware.resource/wrap-resource.

我已经看过了API文档,以及两者的来源compojure.routering.middleware.resource.但是,我仍然不清楚是否需要使用compojure.route/resources路由和ring.middleware.resource/wrap-resource中间件,或者是否compojure.route/resources需要处理所有事情.

还是优化问题?在使用中,wrap-resource避免使用组件路由开销?任何见解将不胜感激.

1 个回答
  • 主要区别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))
    

    2023-02-13 17:16 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有