sendFile and delete file afterwards?

16 views
Skip to first unread message

jsch...@gmail.com

unread,
Apr 2, 2021, 4:20:09 AM4/2/21
to Yesod Web Framework

Hi all,

In a GET handler, I need to
  1. run an external command to generate a file
  2. send the file with sendFile
  3. delete the file afterwards
The problem is that sendFile is a short-circuit response, it skips the rest of the handler code.

How can I still delete the file afterwards? Or do I have to use an clean-up cronjob? I think the first option would be safer especially if the temporary files are stored on tmpfs.

Regards, Jakob

Michael Snoyman

unread,
Apr 2, 2021, 5:45:06 AM4/2/21
to yeso...@googlegroups.com
You can leverage the MonadResource instance to schedule a cleanup when the request handling is finished. Using allocate[1], for instance, to create a new temporary file and schedule its deletion, would work.

--
You received this message because you are subscribed to the Google Groups "Yesod Web Framework" group.
To unsubscribe from this group and stop receiving emails from it, send an email to yesodweb+u...@googlegroups.com.

jsch...@gmail.com

unread,
Apr 3, 2021, 11:55:43 AM4/3/21
to Yesod Web Framework
Thank you Michel! It works:

import Control.Monad.Trans.Resource (allocate)

createAndSendImage :: Handler TypedContent
createAndSendImage = do
  (_, (imageFile, tempDir)) <- allocate allocateResource freeResource
  putStrLn $ pack imageFile
  sendFile typePng imageFile
  where
    allocateResource :: IO (FilePath, FilePath)
    allocateResource = generateLilyPond >>= runLilyPond "/mnt/tmpfs" LyPng
    freeResource :: (FilePath, FilePath) -> IO ()
    freeResource (_, tempDir) = removeDirectoryRecursive tempDir


Reply all
Reply to author
Forward
0 new messages