ring

2025-08-27T17:49:52.014409Z

I would like to return a temporary file as the :body of a Ring response but have the file deleted once the response has been streamed to the client. The closest I’ve come is to create an implementation of InputStream that wraps a FileInputStream and deletes the file when the stream is closed, but I’m wondering, is there a more idiomatic way of doing this?

2025-08-27T17:58:16.975789Z

you return the inputstream as the body, and copy your file into the output stream and delete it afterwards

2025-08-27T18:34:08.672269Z

Oh that’s cool! Thanks I’ll give that a try.

weavejester 2025-08-27T20:08:21.735289Z

Rather than using piped-input-stream, a more efficient route would be to use the StreamableResponseBody protocol. This allows you to write directly to the output stream. However, the way I'd do it is to open the a file stream and then immediately delete the file. On Unix-like systems (like Linux or MacOS), a file is only deleted once all file handles are gone. This means that even if the file is removed from the directory tree, its contents won't be overwritten as long as there are processes with active file handles holding it open.

weavejester 2025-08-27T20:15:17.360809Z

(fn handler [request]
  (let [f  (File/createTempFile "temp" ".tmp")
        in (FileInputStream. f)]
    (.delete f)
    {:status 200
     :headers {}
     :body in}))

💯 1
2025-08-27T22:49:06.750029Z

Perfect, thanks!

Bingen Galartza Iparragirre 2026-04-16T07:17:05.001029Z

In your example @weavejester , is it necessary to take care of explicitly closing the stream? or will it be handled automatically?

Bingen Galartza Iparragirre 2026-04-16T11:00:10.576609Z

Great, thanks!