on master help sign in
Switched response body to an enumerator
commit644bfda1e3d8e8524beb5675153761db1c7efad4 authorMichael Snoyman <michael@snoyman.com> dateMon 25 Jan 2010, 23:55 (17 years ago) parentdb319e8
3 files changed+18−7
Network/Wai.hs+7−2 Network/Wai/Handler/SimpleServer.hs+2−1 test.hs+9−4
Network/Wai.hs+7−2
@@ -1,4 +1,4 @@
1−{-# LANGUAGE ExistentialQuantification #-}
1+{-# LANGUAGE Rank2Types #-}
22module Network.Wai
33 ( -- * Data types
44 -- ** Request method
@@ -23,6 +23,8 @@ module Network.Wai
2323 , Status (..)
2424 , statusCode
2525 , statusMessage
26+ -- * Enumerator
27+ , Enumerator (..)
2628 -- * WAI interface
2729 , Request (..)
2830 , Response (..)
@@ -233,6 +235,9 @@ statusMessage Status405 = B8.pack "Method Not Allowed"
233235statusMessage Status500 = B8.pack "Internal Server Error"
234236statusMessage (Status _ m) = m
235237
238+data Enumerator = Enumerator (forall a.
239+ ((a -> B.ByteString -> IO (Either a a)) -> a -> IO a))
240+
236241data Request = Request
237242 { requestMethod :: Method
238243 , httpVersion :: HttpVersion
@@ -250,7 +255,7 @@ data Request = Request
250255data Response = Response
251256 { status :: Status
252257 , headers :: [(ResponseHeader, B.ByteString)]
253− , body :: Either FilePath ((B.ByteString -> IO ()) -> IO ())
258+ , body :: Either FilePath Enumerator
254259 }
255260
256261type Application = Request -> IO Response
Network/Wai/Handler/SimpleServer.hs+2−1
@@ -167,8 +167,9 @@ sendResponse h res = do
167167 BS.hPut h $ SL.pack "\r\n"
168168 case body res of
169169 Left fp -> unsafeSendFile h fp
170− Right enum -> enum $ BS.hPut h
170+ Right (Enumerator enum) -> enum myPut h >> return ()
171171 where
172+ myPut h bs = BS.hPut h bs >> return (Right h)
172173 putHeader (x, y) = do
173174 BS.hPut h $ responseHeaderToBS x
174175 BS.hPut h $ SL.pack ": "
test.hs+9−4
@@ -28,9 +28,14 @@ postResponse rb = return Response
2828index :: Either FilePath a
2929index = Left "index.html"
3030
31−postBody :: IO (Maybe B.ByteString) -> (B.ByteString -> IO ()) -> IO ()
32−postBody req res = do
31+postBody :: IO (Maybe B.ByteString) -> Enumerator
32+postBody req = Enumerator $ \f a -> helper f a where
33+ helper f a = do
3334 mbs <- req
3435 case mbs of
35− Nothing -> return ()
36− Just bs -> res bs >> postBody req res
36+ Nothing -> return a
37+ Just bs -> do
38+ res <- f a bs
39+ case res of
40+ Left a' -> return a'
41+ Right a' -> helper f a'