Clojure 使用compojure为数据库中的二进制文件提供服务
我有以下路线定义:Clojure 使用compojure为数据库中的二进制文件提供服务,clojure,binary-data,compojure,Clojure,Binary Data,Compojure,我有以下路线定义: (require '[compojure.core :as ccore] '[ring.util.response :as response]) (def *main-routes* (ccore/defroutes avalanche-routes (ccore/GET "/" [] "Hello World 2") (ccore/GET "/images/:id" [id] (get-image-response
(require '[compojure.core :as ccore]
'[ring.util.response :as response])
(def *main-routes*
(ccore/defroutes avalanche-routes
(ccore/GET "/" [] "Hello World 2")
(ccore/GET "/images/:id" [id] (get-image-response id))))
在本例中,请求/
就像一个符咒,返回预期的Hello World 2
get images响应方法的定义如下:
(defn get-image-response
[id]
(let [record (db/get-image id false)]
(-> (response/response (:data record))
(response/content-type (:content-type record))
(response/header "Content-Length" (:size record)))))
不过我有一个404,所以二进制文件的服务还不能很好地工作。你知道为什么吗
编辑:
好的,这个问题与在/images/name.jpg
上请求图像有关。一旦我删除.jpg
处理程序就会被调用。因此,问题变成了除了扩展之外,我如何匹配任何东西?Compojure用于路由匹配。点字符在影响力路由中具有特殊意义。它表示标记分隔符,类似于斜杠字符。以下字符在法规判例法中都有这样的含义:/代码>
这意味着像“/images/:id”
这样的路由将不匹配形式为/images/name.jpg
的uri,因为images
、name
和jpg
在法规判例法中分别代表一个单独的标记
为了匹配它,您可以根据需要以多种不同的方式组合路线
如果您的所有图像都有.jpg
扩展名,最简单的方法是:
(GET "/images/:id.jpg" [id] ...)
如果扩展名不同,您可以执行以下操作:
(GET "/images/:name.:extension" [name extension] ...)
如果要限制扩展,可以向compojure/clout传递正则表达式:
(GET ["/images/:name.:ext", :ext #"(jpe?g|png|gif)"] [name ext] ...)
您还可以使用通配符,该通配符不太精确,并且将匹配以/images/
开头的任何uri:
(GET "/images/*" [*] ...)
本例中的真正答案是clojure couchdb库中有一个bug。该修补程序可用
它归结为将{:as:byte array}map参数和值添加到通过clj http发送到Coach api的请求中
我的代码中的另一个问题是,ring
在呈现字节数组时不知道如何处理它们。我没有修补环,而是将字节数组包装成java.io.ByteArrayInputStream
。以下是处理下载的完整代码:
(defn get-image-response
[id]
(let [record (db/get-image id false)]
(-> (response/response (new java.io.ByteArrayInputStream (:data record)))
(response/content-type (:content-type (:content-type record)))
(response/header "Content-Length" (:size record)))))
谢谢你提供的信息,我投票支持你,因为它是正确的,并且与我的问题相关。不幸的是,我真正的问题是clojure couchdb库中的一个bug,我已经修补了它。我会在一个单独的答案中包含所有细节,以便其他人可以参考。