haskell - 用于 per-handler Reader 的 Scotty monad 转换器

标签 haskell monad-transformers scotty

在问题 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

最佳答案

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

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

关于haskell - 用于 per-handler Reader 的 Scotty monad 转换器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28361505/

相关文章:

haskell - 从哪里开始阅读 GHC 的源代码

haskell - 从 ErrorT 转换到 exceptT

haskell - ExceptT 死代码检测

haskell - 如何防止 scotty 为大文本输出占用内存?

haskell - 如果 f 是 a->b 类型的函数,(fmap f) 与 (f .) 相同吗?

haskell - 如何在 Docker 容器中运行堆栈构建?

haskell - 为什么 ContT 不能成为 MonadError 的实例?

haskell - 当 Haskell 持久库中预期为 `Int` 时,如何通过 `Key` 获取实体?

haskell - 关于 scotty Haskell Web 框架的简单问题

haskell - 括号中逗号分隔的名称是什么意思 - 作为绑定(bind)?