책 한 챕터 다 읽었다. stm
패키지에서 제공하는 기능이 많지만 여기서는 TVar
만 쓸 줄 알면 돼서 분량이 많지 않네. 다음과 같은 형식으로 웹사이트 방문자 카운터를 구현할 수 있다.
countingServer :: IO ()
countingServer = do
hitCounter <- atomically (newTVar @Natural 0)
serve @IO HostAny "8000" \(s, _) -> do
count <- atomically (increment hitCounter)
sendResponse s (textOk (countHelloText count))
increment :: TVar Natural -> STM Natural
increment hitCounter = do
oldCount <- readTVar hitCounter
let newCount = oldCount + 1
writeTVar hitCounter newCount
return newCount