]> andersk Git - scripts-static-cat.git/commitdiff
Read byte ranges lazily, and close the file afterwards.
authorAnders Kaseorg <andersk@mit.edu>
Tue, 13 Jul 2010 01:41:15 +0000 (21:41 -0400)
committerAnders Kaseorg <andersk@mit.edu>
Tue, 13 Jul 2010 01:41:34 +0000 (21:41 -0400)
Signed-off-by: Anders Kaseorg <andersk@mit.edu>
StaticCat.hs

index 396403bcd6035adb4c73df6f7c661d3a09c03e66..df4a6e271395f695629ad515dcfcdb0290413334 100644 (file)
@@ -8,6 +8,7 @@ import Control.Monad.CatchIO
 import qualified Data.ByteString.Lazy as B
 import Data.Char
 import Data.Dynamic
+import Data.Int
 import qualified Data.Map as M
 import Data.Time.Clock.POSIX
 import Data.Time.Format
@@ -16,6 +17,7 @@ import Numeric
 import System.FilePath
 import System.IO
 import System.IO.Error (isDoesNotExistError, isPermissionError)
+import System.IO.Unsafe
 import System.Locale
 import System.Posix
 import System.Posix.Handle
@@ -145,6 +147,14 @@ outputAll h size = do
   setHeader "Content-Length" $ show size
   outputFPS =<< liftIO (B.hGetContents h)
 
+-- | Lazily read a given number of bytes from the handle into a
+-- 'ByteString', then close the handle.
+hGetClose :: Handle -> Int64 -> IO B.ByteString
+hGetClose h len = do
+  contents <- B.hGetContents h
+  end <- unsafeInterleaveIO (hClose h >> return B.empty)
+  return (B.append (B.take len contents) end)
+
 outputRange :: Handle -> FileOffset -> Maybe (FileOffset, FileOffset) -> CGI CGIResult
 outputRange h size Nothing = outputAll h size
 outputRange h size (Just (a, b)) = do
@@ -155,7 +165,7 @@ outputRange h size (Just (a, b)) = do
    "bytes " ++ show a ++ "-" ++ show b ++ "/" ++ show size
   setHeader "Content-Length" $ show len
   liftIO $ hSeek h AbsoluteSeek (fromIntegral a)
-  outputFPS =<< liftIO (B.hGet h (fromIntegral len))
+  outputFPS =<< liftIO (hGetClose h (fromIntegral len))
 
 serveFile :: FilePath -> CGI CGIResult
 serveFile file = (`catch` outputMyError) $ do
This page took 0.559931 seconds and 5 git commands to generate.