Use StateT within Web.Scotty

我是研究僧i 提交于 2019-12-03 13:46:20

The behaviour you are seeing is definitely the expected one: note the remark on the third argument in the documentation for scottyT:

-> (m Response -> IO Response) -- Run monad m into IO, called at each action.

What you could do is store the state external to the StateT monad so that you can reinstate it in the handler of every action. The most naïve way I can think of to do that would be something like this:

main :: IO ()
main = do
    let s0 = "message"
    let transform = flip evalStateT s0
    runner <- restartableStateT s0
    scottyT 3000 transform runner routes

restartableStateT :: s -> IO (StateT s IO a -> IO a)
restartableStateT s0 = do
    r <- newIORef s0
    return $ \act -> do
        s <- readIORef r
        (x, s') <- runStateT act s
        atomicModifyIORef' r $ const (s', x)

but this doesn't really address what should happen if two requests are coming in concurrently, it's just "last one to finish wins".

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!