Search code examples
haskellsession-statehaskell-snap-framework

How do I maintain a server-side state with Snap Framework?


Server-side sessions are not [yet] part of the Snap Framework. Is there a way to add some sort of server side state?

Let's pretend I want to increment a counter for each HTTP request. How would I do it?


Solution

  • Easiest way is to put the state behind an mvar:

    fooHandler :: MVar Int -> Snap ()
    fooHandler mvar = do
        x <- liftIO $ modifyMVar mvar $ \y -> let y'=y+1 in (y',y')
        writeBS $ S.pack $ "Incremented counter to: " ++ show x
    

    Initialize the mvar when the site is initialized. Hope this helps.