gpt4 book ai didi

haskell - 如何在自定义servant处理程序中响应HTTP状态?

转载 作者:行者123 更新时间:2023-12-02 21:01:06 24 4
gpt4 key购买 nike

我创建了一个自定义仆人处理程序

type ServiceSet = TVar (M.Map String [MicroService])
type LocalHandler = ReaderT ServiceSet IO

但我未能找到一种方法在以下函数中向客户端响应 404-not-found 状态代码:

getService :: String -> LocalHandler MicroService
getService sn = do
tvar <- ask
ms <- liftIO $ do
sl <- atomically $ do
sm <- readTVar tvar
return $ case M.lookup sn sm of
Nothing -> []
Just sl -> sl
let n = length sl
i <- randomRIO (0, n - 1)
return $ if n == 0
then Nothing
else Just . head . drop i $ sl
case ms of
Nothing -> ??? -- throwError err404
Just ms' -> return ms'

如何在中发送404状态码???

最佳答案

您需要将 ExceptT 添加到您的 monad 转换堆栈中。目前,仅使用 ReaderT,无法对抛出错误的概念进行编码。

{-# LANGUAGE DataKinds     #-}
{-# LANGUAGE TypeOperators #-}

module Lib where

import Control.Monad.Except
import Control.Monad.Reader
import Data.Maybe
import Data.Map
import GHC.Conc
import Prelude hiding (lookup)
import Servant.API
import Servant.Server
import System.Random

type API =
Capture "name" String :> Get '[JSON] Int

type World =
TVar (Map String [Int])

type Effects =
ExceptT ServantErr (ReaderT World IO)

server :: World -> Server API
server world =
enter (Nat transform) get
where
transform :: Effects a -> ExceptT ServantErr IO a
transform (ExceptT foo) =
ExceptT $ runReaderT foo world

get :: String -> Effects Int
get sn = do
tvar <- ask
ms <- liftIO $ do
sl <- atomically $ do
sm <- readTVar tvar
return (fromMaybe [] (lookup sn sm))
let n = length sl
i <- randomRIO (0, n - 1)
return $ if n == 0
then Nothing
else Just . head . drop i $ sl
case ms of
Nothing ->
throwError err404
Just ms' ->
return ms'

ExceptT ServantErr 。 ReaderT (TVar ...) 然后你可以throwError err404,Servant将捕获并使用它来返回HTTP 404。自然转换ExceptT ServantErr。 ReaderT (TVar ...) :~> exceptT ServantErr 然后必须展开并重新包装以释放阅读器效果。总而言之,代码并不多。

关于haskell - 如何在自定义servant处理程序中响应HTTP状态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38187271/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com