ring-clojure / ring

Clojure HTTP server abstraction
MIT License
3.73k stars 518 forks source link

Callback after response transmission #459

Closed bandoos closed 2 years ago

bandoos commented 2 years ago

I was wondering is there is a way to execute a callback after an http response is successfully transmitted to the client.

My use case is the following:

Right now i simply schedule the deletion after a few minutes so i'm reasonably sure the response was transmitted, but maybe there is a way (maybe with the 3-arity handler contract?) in which I can do it immediately after response was delivered.

Thanks in advance.

weavejester commented 2 years ago

You can reify ring.core.protocols/StreamableResponseBody:

(require '[clojure.java.io :as io])
(require '[ring.core.protocols :as p])

(defn handler [request file callback]
  {:status 200
   :headers {}
   :body (reify p/StreamableResponseBody
           (write-body-to-stream [_ _ ^java.io.OutputStream os]
             (io/copy file os)
             (.close os)
             (callback request file)))})
bandoos commented 2 years ago

Amazing, thanks for the fast response!