Last active
December 10, 2015 19:18
-
-
Save jbpotonnier/4480058 to your computer and use it in GitHub Desktop.
EventSource streaming using Haskell and redis brpop.
Use redis-cli to push some data in the "val" list and see it appear in your browser.
It is not that hard... finally. There are some events not appearing at the beginning of the sequence, I don't know why, after that it works well.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!doctype html> | |
<html> | |
<head><title>Index</title> | |
</head> | |
<body> | |
<script type="text/javascript"> | |
var source = new EventSource('eventsource'); | |
source.onmessage = function (e) { | |
var newListItem = document.createElement("LI"); | |
newListItem.appendChild(document.createTextNode(e.data)); | |
document.getElementById("list").appendChild(newListItem); | |
}; | |
</script> | |
<ul id="list"> | |
</ul> | |
</body> | |
</html> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{-# LANGUAGE OverloadedStrings #-} | |
module Main where | |
import Control.Applicative | |
import Snap.Core | |
import Snap.Util.FileServe | |
import Snap.Http.Server | |
import Data.Monoid (mconcat) | |
import Blaze.ByteString.Builder.Char8 | |
import Blaze.ByteString.Builder | |
import Data.Enumerator.List (generateM) | |
import Database.Redis | |
getVal :: IO Builder | |
getVal = do | |
conn <- connect defaultConnectInfo | |
runRedis conn $ do | |
Right (Just (_, val)) <- brpop ["val"] 1000 | |
return $ fromByteString val | |
dataField :: Builder -> Builder | |
dataField b = mconcat [fromString "data: ", b, fromString "\n\n", flush] | |
eventHandler :: Snap () | |
eventHandler = do | |
modifyResponse $ | |
setContentType "text/event-stream" . | |
setResponseCode 200 . | |
setResponseBody (generateM $ fmap (Just . dataField) getVal) | |
main :: IO () | |
main = quickHttpServe $ | |
ifTop (serveFile "static/index.html") <|> | |
route [ ("eventsource", eventHandler) ] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment