on master help sign in
Add examples for new EventSource API
b7a08aaMitsutoshi Aoe
wai-eventsource/src/Main.hs+27−6
@@ -3,6 +3,7 @@ module Main where
3
3
4import Control.Monad
4import Control.Monad
5import Control.Concurrent (forkIO, threadDelay)
5import Control.Concurrent (forkIO, threadDelay)
6+import Control.Monad.Trans (liftIO)
6import Control.Concurrent.Chan
7import Control.Concurrent.Chan
7import Network.Wai.Handler.Warp (run)
8import Network.Wai.Handler.Warp (run)
8import Network.Wai.Middleware.Gzip (gzip, def)
9import Network.Wai.Middleware.Gzip (gzip, def)
@@ -10,6 +11,7 @@ import Network.Wai
10import Network.HTTP.Types (statusOK)
11import Network.HTTP.Types (statusOK)
11import Data.Time.Clock.POSIX
12import Data.Time.Clock.POSIX
12import Blaze.ByteString.Builder.Char.Utf8 (fromString)
13import Blaze.ByteString.Builder.Char.Utf8 (fromString)
14+import qualified Data.Conduit as C
13
15
14import Network.Wai.EventSource
16import Network.Wai.EventSource
15
17
@@ -17,19 +19,38 @@ app :: Chan ServerEvent -> Application
17app chan req =
19app chan req =
18 case pathInfo req of
20 case pathInfo req of
19 [] -> return $ ResponseFile statusOK [("Content-Type", "text/html")] "static/index.html" Nothing
21 [] -> 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
21 _ -> error "unexpected pathInfo"
26 _ -> error "unexpected pathInfo"
22
27
23−
24−source :: Chan ServerEvent -> IO ()
28+eventChan :: Chan ServerEvent -> IO ()
25−source chan = forever $ do
29+eventChan chan = forever $ do
26 threadDelay 1000000
30 threadDelay 1000000
27 time <- getPOSIXTime
31 time <- getPOSIXTime
28 writeChan chan (ServerEvent Nothing Nothing [fromString . show $ time])
32 writeChan chan (ServerEvent Nothing Nothing [fromString . show $ time])
29
33
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]
30
52
31−main :: IO ()
32main = do
53main = do
33 chan <- newChan
54 chan <- newChan
34− _ <- forkIO . source $ chan
55+ _ <- forkIO . eventChan $ chan
35 run 8000 (gzip def $ app chan)
56 run 8000 (gzip def $ app chan)