0

我正在尝试创建一个服务器,该服务器根据用户之前是否访问过它,从路由返回两个不同的值。我有以下代码:

{-# LANGUAGE OverloadedStrings #-}
module Main where

import Web.Scotty

main = do
    putStrLn "Starting Server..."
    scotty 3000 $ do
        get "/" $ do
            -- if first time 
            text "hello!"
            -- if second time
            text "hello, again!"

我有两个问题: 1. 如何检查用户之前是否请求过路由?2. 我可以在哪里以及如何持久化应用程序状态?

4

1 回答 1

3

您可以使用STM在内存中保留可变变量:

import Control.Concurrent.STM.TVar

main = do
    putStrLn "Starting Server..."
    state <- newTVarIO :: IO VisitorsData
    scotty 3000 $ do
        get "/" $ do
            visitorsData <- readTVarIO state
            -- if the visitor's ID/cookie is in visitorsData
            text "hello!"
            -- if new visitor, add them to visitorsData
            atomically $ modifyTVar state $ insertVisitor visitorId visitorsData
            -- if second time
            text "hello, again!"

(如果您希望将其扩展到复杂的服务器,您需要以ReaderT 模式的形式传递 TVar )

于 2019-06-24T13:16:27.417 回答