Haskell Webserver: maintaining application state

functional-programming, happstack, haskell

Solution

You probably want acid-state, which gives you that exactly: persistent state for Haskell data types. The documentation I linked even starts out with a request counter, just like you asked for.

Note that MVars are not persistent; the counter would get reset when the server is restarted. If that's actually the behavior you want I suggest you use a TVar instead; that way you can update the counter atomically without locks or the risk of deadlocks that go with them.

Problem

I'm trying to get more familiar with Haskell by developing web-app-ish services. Say I'm developing a web-server and I want to keep persistent state between requests; a counter, for instance. What is the Haskell way of doing things? I came across this discussion on my Google search. The proposed solution looks like a good example of what not to do. One idea I had was having the request handler take in an MVar: ``` requestHandler :: MVar State -> IO (Maybe Response) ``` When registering the handler, it could be curried with an MVar created in main. There must be a better way. I can't help but think I'm approaching this problem in a non-functional way. Thanks!

Original source