Skip to content

Instantly share code, notes, and snippets.

@techno-tanoC
Last active August 29, 2015 14:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save techno-tanoC/920414b1fca26f07f4a1 to your computer and use it in GitHub Desktop.
Save techno-tanoC/920414b1fca26f07f4a1 to your computer and use it in GitHub Desktop.
Scotty+STMで状態を持ったサーバ
{-# LANGUAGE OverloadedStrings #-}
module Main where
import Control.Concurrent
import Control.Concurrent.STM
import Control.Monad.IO.Class
import Data.Text.Lazy
import Web.Scotty
import Data.Aeson.Types
newtype Counter = Counter (TVar Int)
getCounter :: Counter -> IO Int
getCounter (Counter c) = atomically . readTVar $ c
newCounter :: IO Counter
newCounter = fmap Counter (newTVarIO 0)
incCounter :: Counter -> IO ()
incCounter (Counter c) = atomically $ modifyTVar c succ
delay :: Int -> IO ()
delay = threadDelay . (* 1000)
act :: Counter -> IO ThreadId
act c =
forkIO $ do
delay 10000
incCounter c
delay 10000
incCounter c
putStrLn "finish!"
main :: IO ()
main = do
c <- newCounter
scotty 3000 $ do
get "/get" $ do
liftIO . putStrLn $ "get!"
liftIO (getCounter c) >>= json
get "/inc" $ do
liftIO . putStrLn $ "inc!"
liftIO $ incCounter c
liftIO (getCounter c) >>= json
get "/act" $ do
liftIO . putStrLn $ "act!"
_ <- liftIO . act $ c
return ()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment