每个处理程序的 Scotty monad 转换器 Reader

Scotty monad transformer for per-handler Reader

在问题 Web, Scotty: connection pool as monad reader 中展示了如何使用 ScottyT 在堆栈中嵌入一个 Reader monad 以访问静态配置(在这种情况下,连接池) .

我有一个类似的问题,但更简单——或者至少我是这么认为的……

我想将 Reader 添加到单个处理程序(即 ActionT),而不是整个应用程序。

我从上面的问题开始修改程序,但我不知道如何将 ActionT Text (ReaderT String IO) 变成处理程序需要的 ActionT Text IO。在四处摸索并尝试使用打字孔希望看到如何构建它之后,我不得不暂时放弃并寻求帮助。我真的觉得这应该很简单,但不知道该怎么做。

这是程序,突出显示了我卡住的行:

{-# LANGUAGE OverloadedStrings #-}

import qualified Data.Text.Lazy as T
import           Data.Text.Lazy (Text)
import           Control.Monad.Reader
import           Web.Scotty.Trans

type ActionD = ActionT Text (ReaderT String IO)

main :: IO ()
main = do
  scottyT 3000 id id app

-- Application
app ::  ScottyT Text IO ()
app = do
  get "/foo" $ do
    h <- handler              -- ?
    runReaderT h "foo"        -- ?
--get "/bar" $ do
--  h <- handler
--  runReaderT h "bar"

-- Route action handler
handler ::  ActionD ()
handler = do
  config <- lift ask
  html $ T.pack $ show config

如果您想 运行 在单独的 reader 中执行每个操作,则根本不需要更复杂的 Scotty.Trans 界面。你可以用相反的方式构建你的 monad 堆栈,ReaderT 在上面。

import qualified Data.Text.Lazy as T
import           Control.Monad.Reader
import           Web.Scotty

type ActionD = ReaderT String ActionM

main :: IO ()
main = do
  scotty 3000 app

-- Application
app ::  ScottyM ()
app = do
  get "/foo" $ do
    runReaderT handler "foo"

-- Route action handler
handler ::  ActionD ()
handler = do
  config <- ask
  lift $ html $ T.pack $ show config