module Network.Wai.Middleware.StreamFile
(streamFile) where
import Network.Wai (responseStream)
import Network.Wai.Internal
import Network.Wai (Middleware, responseToStream)
import qualified Data.ByteString.Char8 as S8
import System.PosixCompat (getFileStatus, fileSize, FileOffset)
import Network.HTTP.Types (hContentLength)
streamFile :: Middleware
streamFile app env sendResponse = app env $ \res ->
case res of
ResponseFile _ _ fp _ -> withBody sendBody
where
(s, hs, withBody) = responseToStream res
sendBody :: StreamingBody -> IO ResponseReceived
sendBody body = do
len <- getFileSize fp
let hs' = (hContentLength, (S8.pack (show len))) : hs
sendResponse $ responseStream s hs' body
_ -> sendResponse res
getFileSize :: FilePath -> IO FileOffset
getFileSize path = do
stat <- getFileStatus path
return (fileSize stat)