1
{-# LANGUAGE OverloadedStrings #-}
3
A WAI adapter to the HTML5 Server-Sent Events API.
5
module Network.Wai.EventSource (
11
import Blaze.ByteString.Builder (Builder)
12
import Data.Function (fix)
13
import Control.Concurrent.Chan (Chan, dupChan, readChan)
14
import Control.Monad.IO.Class (liftIO)
15
import Network.HTTP.Types (status200)
16
import Network.Wai (Application, Response, responseStream)
18
import Network.Wai.EventSource.EventStream
20
-- | Make a new WAI EventSource application reading events from
22
eventSourceAppChan :: Chan ServerEvent -> Application
23
eventSourceAppChan chan req sendResponse = do
24
chan' <- liftIO $ dupChan chan
25
eventSourceAppIO (readChan chan') req sendResponse
27
-- | Make a new WAI EventSource application reading events from
28
-- the given IO action.
29
eventSourceAppIO :: IO ServerEvent -> Application
30
eventSourceAppIO src _ sendResponse =
31
sendResponse $ responseStream
33
[("Content-Type", "text/event-stream")]
34
$ \sendChunk flush -> fix $ \loop -> do
36
case eventToBuilder se of
38
Just b -> sendChunk b >> flush >> loop