module Network.Wai.Middleware.StreamFile
(streamFile) where
import qualified Data.ByteString.Char8 as S8
import Network.HTTP.Types (hContentLength)
import Network.Wai (Middleware, responseStream, responseToStream)
import Network.Wai.Internal
import System.Directory (getFileSize)
streamFile :: Middleware
streamFile :: Middleware
streamFile Application
app Request
env Response -> IO ResponseReceived
sendResponse = Application
app Request
env forall a b. (a -> b) -> a -> b
$ \Response
res ->
case Response
res of
ResponseFile Status
_ ResponseHeaders
_ FilePath
fp Maybe FilePart
_ -> forall {a}. (StreamingBody -> IO a) -> IO a
withBody StreamingBody -> IO ResponseReceived
sendBody
where
(Status
s, ResponseHeaders
hs, (StreamingBody -> IO a) -> IO a
withBody) = forall a.
Response
-> (Status, ResponseHeaders, (StreamingBody -> IO a) -> IO a)
responseToStream Response
res
sendBody :: StreamingBody -> IO ResponseReceived
sendBody :: StreamingBody -> IO ResponseReceived
sendBody StreamingBody
body = do
Integer
len <- FilePath -> IO Integer
getFileSize FilePath
fp
let hs' :: ResponseHeaders
hs' = (HeaderName
hContentLength, (FilePath -> ByteString
S8.pack (forall a. Show a => a -> FilePath
show Integer
len))) forall a. a -> [a] -> [a]
: ResponseHeaders
hs
Response -> IO ResponseReceived
sendResponse forall a b. (a -> b) -> a -> b
$ Status -> ResponseHeaders -> StreamingBody -> Response
responseStream Status
s ResponseHeaders
hs' StreamingBody
body
Response
_ -> Response -> IO ResponseReceived
sendResponse Response
res