on master help sign in
Add examples for new EventSource API
commitb7a08aa85115e93078cc9420026185ffa519853f authorMitsutoshi Aoe <maoe@foldr.in> dateMon 13 Feb 2012, 18:41 (15 years ago) parenta172599
1 file changed+27−6
wai-eventsource/src/Main.hs+27−6
wai-eventsource/src/Main.hs+27−6
@@ -3,6 +3,7 @@ module Main where
33
44import Control.Monad
55import Control.Concurrent (forkIO, threadDelay)
6+import Control.Monad.Trans (liftIO)
67import Control.Concurrent.Chan
78import Network.Wai.Handler.Warp (run)
89import Network.Wai.Middleware.Gzip (gzip, def)
@@ -10,6 +11,7 @@ import Network.Wai
1011import Network.HTTP.Types (statusOK)
1112import Data.Time.Clock.POSIX
1213import Blaze.ByteString.Builder.Char.Utf8 (fromString)
14+import qualified Data.Conduit as C
1315
1416import Network.Wai.EventSource
1517
@@ -17,19 +19,38 @@ app :: Chan ServerEvent -> Application
1719app chan req =
1820 case pathInfo req of
1921 [] -> return $ ResponseFile statusOK [("Content-Type", "text/html")] "static/index.html" Nothing
20− ["es"] -> eventSourceApp chan req
22+ ["esold"] -> eventSourceApp chan req
23+ ["eschan"] -> eventSourceAppChan chan req
24+ ["esio"] -> eventSourceAppIO eventIO req
25+ ["essrc"] -> eventSourceAppSource eventSource req
2126 _ -> error "unexpected pathInfo"
2227
23−
24−source :: Chan ServerEvent -> IO ()
25−source chan = forever $ do
28+eventChan :: Chan ServerEvent -> IO ()
29+eventChan chan = forever $ do
2630 threadDelay 1000000
2731 time <- getPOSIXTime
2832 writeChan chan (ServerEvent Nothing Nothing [fromString . show $ time])
2933
34+eventIO :: IO ServerEvent
35+eventIO = do
36+ threadDelay 1000000
37+ time <- getPOSIXTime
38+ return $ ServerEvent (Just $ fromString "io")
39+ Nothing
40+ [fromString . show $ time]
41+
42+eventSource :: C.Source IO ServerEvent
43+eventSource = C.sourceState () (const pull)
44+ where
45+ pull = do
46+ time <- liftIO $ do
47+ threadDelay 1000000
48+ getPOSIXTime
49+ return $ C.StateOpen () $ ServerEvent (Just $ fromString "source")
50+ Nothing
51+ [fromString . show $ time]
3052
31−main :: IO ()
3253main = do
3354 chan <- newChan
34− _ <- forkIO . source $ chan
55+ _ <- forkIO . eventChan $ chan
3556 run 8000 (gzip def $ app chan)