【问题标题】:Intermittent error serving a binary file with Clojure/Ring使用 Clojure/Ring 提供二进制文件时出现间歇性错误
【发布时间】:2012-10-30 14:13:48
【问题描述】:

我正在为 Snowplow 构建一个 event collector in Clojure(使用 Ring/Compojure),并且在使用 Ring 提供透明像素时遇到了一些问题。这是我发送像素的代码:

(ns snowplow.clojure-collector.responses
  (:import (org.apache.commons.codec.binary Base64)
           (java.io ByteArrayInputStream)))

(def pixel-bytes (Base64/decodeBase64 (.getBytes "R0lGODlhAQABAPAAAAAAAAAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==")))
(def pixel (ByteArrayInputStream. pixel-bytes))

(defn send-pixel
   []
    {:status  200
     :headers {"Content-Type"   "image/gif"}
     :body    pixel})

当我启动服务器时,当我第一次点击send-pixel 的路径时,像素已成功传送到我的浏览器。但是第二次——以及之后的每一次——Ring 都没有发送任何正文(并且内容长度为 0)。重启服务器,还是一样的模式。

有些事情不是这样的:

  1. 我已使用 wget 复制了此内容,以确认间歇性不是浏览器缓存问题
  2. 我在命令行 (cat original.gif | base64) 生成了 "R01GOD..." base64 字符串,所以知道那里没有问题
  3. 像素发送成功后,我已验证其内容正确(diff original.gif received-pixel.gif

我是 Clojure 的新手——我猜我的代码中有一些令人尴尬的动态 gremlin,但我需要帮助来发现它!

【问题讨论】:

    标签: clojure ring


    【解决方案1】:

    我在发布后不久就发现了 REPL 中的问题:

    user=> (import (org.apache.commons.codec.binary Base64) (java.io ByteArrayInputStream))
    java.io.ByteArrayInputStream
    user=> (def pixel-bytes (Base64/decodeBase64 (.getBytes "R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==")))
    #'user/pixel-bytes
    user=> (def pixel (ByteArrayInputStream. pixel-bytes))
    #'user/pixel
    user=> (slurp pixel-bytes)
    "GIF89a!�\n,L;"
    user=> (slurp pixel-bytes)
    "GIF89a!�\n,L;"
    user=> (slurp pixel)
    "GIF89a!�\n,L;"
    user=> (slurp pixel)
    ""
    

    所以基本上问题是ByteArrayInputStream 在第一次通话后被清空了。可变数据结构!

    我通过为每个响应生成一个新的ByteArrayInputStream 来修复错误,其中:

        :body    (ByteArrayInputStream. pixel-bytes)}))
    

    【讨论】:

      【解决方案2】:

      问题是您的pixel 变量包含一个流。一旦读过,就不可能再读一遍。

      此外,您不需要处理编码问题。 Ring 也提供静态文件。只需返回:

      (file-response "/path/to/pixel.gif")
      

      它也处理不存在的文件。 See the docs 也。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-09-08
        • 1970-01-01
        • 1970-01-01
        • 2022-06-16
        • 2019-12-13
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多