haskell - How to response with HTTP status in custom servant handler? -
i created custom servant handler
type serviceset = tvar (m.map string [microservice]) type localhandler = readert serviceset io
but failed find way response 404-not-found status code client in following function:
getservice :: string -> localhandler microservice getservice sn = tvar <- ask ms <- liftio $ sl <- atomically $ sm <- readtvar tvar return $ case m.lookup sn sm of nothing -> [] sl -> sl let n = length sl <- randomrio (0, n - 1) return $ if n == 0 nothing else . head . drop $ sl case ms of nothing -> ??? -- throwerror err404 ms' -> return ms'
how send 404 status code in ???
?
you need add exceptt
stack of monad transforms. right now, readert
, there no way encode notion of error being thrown.
{-# language datakinds #-} {-# language typeoperators #-} module lib 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 :> '[json] int type world = tvar (map string [int]) type effects = exceptt servanterr (readert world io) server :: world -> server api server world = enter (nat transform) transform :: effects -> exceptt servanterr io transform (exceptt foo) = exceptt $ runreadert foo world :: string -> effects int sn = tvar <- ask ms <- liftio $ sl <- atomically $ sm <- readtvar tvar return (frommaybe [] (lookup sn sm)) let n = length sl <- randomrio (0, n - 1) return $ if n == 0 nothing else . head . drop $ sl case ms of nothing -> throwerror err404 ms' -> return ms'
with exceptt servanterr . readert (tvar ...)
can throwerror err404
, servant catch , use return http 404. natural transformation exceptt servanterr . readert (tvar ...) :~> exceptt servanterr
have unwrap , rewrap in order discharge reader effect. in all, not terribly more code.
Comments
Post a Comment