-- Hoogle documentation, generated by Haddock -- See Hoogle, http://www.haskell.org/hoogle/ -- | A family of combinators for defining webservices APIs and serving them -- -- A family of combinators for defining webservices APIs and serving them -- . You can learn about the basics in the tutorial. . Here -- is a runnable example, with comments, that defines a dummy API and -- implements a webserver that serves this API, using this package. . -- CHANGELOG @package servant-server @version 0.20.2 module Servant.Server.Internal.Context -- | Contexts are used to pass values to combinators. (They are -- not meant to be used to pass parameters to your handlers, i.e. -- they should not replace any custom ReaderT-monad-stack that -- you're using with hoistServer.) If you don't use combinators -- that require any context entries, you can just use serve as -- always. -- -- If you are using combinators that require a non-empty Context -- you have to use serveWithContext and pass it a Context -- that contains all the values your combinators need. A Context -- is essentially a heterogeneous list and accessing the elements is -- being done by type (see getContextEntry). The parameter of the -- type Context is a type-level list reflecting the types of the -- contained context entries. To create a Context with entries, -- use the operator (:.): -- --
--   >>> :type True :. () :. EmptyContext
--   True :. () :. EmptyContext :: Context '[Bool, ()]
--   
data Context contextTypes [EmptyContext] :: Context '[] [:.] :: x -> Context xs -> Context (x ': xs) infixr 5 :. -- | Append two type-level lists. -- -- Hint: import it as -- --
--   import Servant.Server (type (.++))
--   
type family (.++) (l1 :: [Type]) (l2 :: [Type]) -- | Append two contexts. (.++) :: Context l1 -> Context l2 -> Context (l1 .++ l2) -- | This class is used to access context entries in Contexts. -- getContextEntry returns the first value where the type matches: -- --
--   >>> getContextEntry (True :. False :. EmptyContext) :: Bool
--   True
--   
-- -- If the Context does not contain an entry of the requested type, -- you'll get an error: -- --
--   >>> getContextEntry (True :. False :. EmptyContext) :: String
--   ...
--   ...No instance for ...HasContextEntry '[] [Char]...
--   ...
--   
class HasContextEntry (context :: [Type]) (val :: Type) getContextEntry :: HasContextEntry context val => Context context -> val -- | Normally context entries are accessed by their types. In case you need -- to have multiple values of the same type in your Context and -- need to access them, we provide NamedContext. You can think of -- it as sub-namespaces for Contexts. data NamedContext (name :: Symbol) (subContext :: [Type]) NamedContext :: Context subContext -> NamedContext (name :: Symbol) (subContext :: [Type]) -- | descendIntoNamedContext allows you to access -- NamedContexts. Usually you won't have to use it yourself but -- instead use a combinator like WithNamedContext. -- -- This is how descendIntoNamedContext works: -- --
--   >>> :set -XFlexibleContexts
--   
--   >>> let subContext = True :. EmptyContext
--   
--   >>> :type subContext
--   subContext :: Context '[Bool]
--   
--   >>> let parentContext = False :. (NamedContext subContext :: NamedContext "subContext" '[Bool]) :. EmptyContext
--   
--   >>> :type parentContext
--   parentContext :: Context '[Bool, NamedContext "subContext" '[Bool]]
--   
--   >>> descendIntoNamedContext (Proxy :: Proxy "subContext") parentContext :: Context '[Bool]
--   True :. EmptyContext
--   
descendIntoNamedContext :: forall context name subContext. HasContextEntry context (NamedContext name subContext) => Proxy (name :: Symbol) -> Context context -> Context subContext instance Servant.Server.Internal.Context.HasContextEntry xs val => Servant.Server.Internal.Context.HasContextEntry (notIt : xs) val instance Servant.Server.Internal.Context.HasContextEntry (val : xs) val instance GHC.Show.Show (Servant.Server.Internal.Context.Context '[]) instance (GHC.Show.Show a, GHC.Show.Show (Servant.Server.Internal.Context.Context as)) => GHC.Show.Show (Servant.Server.Internal.Context.Context (a : as)) instance GHC.Classes.Eq (Servant.Server.Internal.Context.Context '[]) instance (GHC.Classes.Eq a, GHC.Classes.Eq (Servant.Server.Internal.Context.Context as)) => GHC.Classes.Eq (Servant.Server.Internal.Context.Context (a : as)) module Servant.Server.Internal.ServerError data ServerError ServerError :: Int -> String -> ByteString -> [Header] -> ServerError [$sel:errHTTPCode:ServerError] :: ServerError -> Int [$sel:errReasonPhrase:ServerError] :: ServerError -> String [$sel:errBody:ServerError] :: ServerError -> ByteString [$sel:errHeaders:ServerError] :: ServerError -> [Header] responseServerError :: ServerError -> Response -- | err300 Multiple Choices -- -- Example: -- --
--   failingHandler :: Handler ()
--   failingHandler = throwError $ err300 { errBody = "I can't choose." }
--   
err300 :: ServerError -- | err301 Moved Permanently -- -- Example: -- --
--   failingHandler :: Handler ()
--   failingHandler = throwError err301
--   
err301 :: ServerError -- | err302 Found -- -- Example: -- --
--   failingHandler :: Handler ()
--   failingHandler = throwError err302
--   
err302 :: ServerError -- | err303 See Other -- -- Example: -- --
--   failingHandler :: Handler ()
--   failingHandler = throwError err303
--   
err303 :: ServerError -- | err304 Not Modified -- -- Example: -- --
--   failingHandler :: Handler ()
--   failingHandler = throwError err304
--   
err304 :: ServerError -- | err305 Use Proxy -- -- Example: -- --
--   failingHandler :: Handler ()
--   failingHandler = throwError err305
--   
err305 :: ServerError -- | err307 Temporary Redirect -- -- Example: -- --
--   failingHandler :: Handler ()
--   failingHandler = throwError err307
--   
err307 :: ServerError -- | err400 Bad Request -- -- Example: -- --
--   failingHandler :: Handler ()
--   failingHandler = throwError $ err400 { errBody = "Your request makes no sense to me." }
--   
err400 :: ServerError -- | err401 Unauthorized -- -- Example: -- --
--   failingHandler :: Handler ()
--   failingHandler = throwError $ err401 { errBody = "Your credentials are invalid." }
--   
err401 :: ServerError -- | err402 Payment Required -- -- Example: -- --
--   failingHandler :: Handler ()
--   failingHandler = throwError $ err402 { errBody = "You have 0 credits. Please give me $$$." }
--   
err402 :: ServerError -- | err403 Forbidden -- -- Example: -- --
--   failingHandler :: Handler ()
--   failingHandler = throwError $ err403 { errBody = "Please login first." }
--   
err403 :: ServerError -- | err404 Not Found -- -- Example: -- --
--   failingHandler :: Handler ()
--   failingHandler = throwError $ err404 { errBody = "Are you lost?" }
--   
err404 :: ServerError -- | err405 Method Not Allowed -- -- Example: -- --
--   failingHandler :: Handler ()
--   failingHandler = throwError $ err405 { errBody = "Your account privileges does not allow for this.  Please pay $$$." }
--   
err405 :: ServerError -- | err406 Not Acceptable -- -- Example: -- --
--   failingHandler :: Handler ()
--   failingHandler = throwError err406
--   
err406 :: ServerError -- | err407 Proxy Authentication Required -- -- Example: -- --
--   failingHandler :: Handler ()
--   failingHandler = throwError err407
--   
err407 :: ServerError -- | err409 Conflict -- -- Example: -- --
--   failingHandler :: Handler ()
--   failingHandler = throwError $ err409 { errBody = "Transaction conflicts with 59879cb56c7c159231eeacdd503d755f7e835f74" }
--   
err409 :: ServerError -- | err410 Gone -- -- Example: -- --
--   failingHandler :: Handler ()
--   failingHandler = throwError $ err410 { errBody = "I know it was here at some point, but.. I blame bad luck." }
--   
err410 :: ServerError -- | err411 Length Required -- -- Example: -- --
--   failingHandler :: Handler ()
--   failingHandler = throwError err411
--   
err411 :: ServerError -- | err412 Precondition Failed -- -- Example: -- --
--   failingHandler :: Handler ()
--   failingHandler = throwError $ err412 { errBody = "Precondition fail: x < 42 && y > 57" }
--   
err412 :: ServerError -- | err413 Request Entity Too Large -- -- Example: -- --
--   failingHandler :: Handler ()
--   failingHandler = throwError $ err413 { errBody = "Request exceeded 64k." }
--   
err413 :: ServerError -- | err414 Request-URI Too Large -- -- Example: -- --
--   failingHandler :: Handler ()
--   failingHandler = throwError $ err414 { errBody = "Maximum length is 64." }
--   
err414 :: ServerError -- | err415 Unsupported Media Type -- -- Example: -- --
--   failingHandler :: Handler ()
--   failingHandler = throwError $ err415 { errBody = "Supported media types:  gif, png" }
--   
err415 :: ServerError -- | err416 Request range not satisfiable -- -- Example: -- --
--   failingHandler :: Handler ()
--   failingHandler = throwError $ err416 { errBody = "Valid range is [0, 424242]." }
--   
err416 :: ServerError -- | err417 Expectation Failed -- -- Example: -- --
--   failingHandler :: Handler ()
--   failingHandler = throwError $ err417 { errBody = "I found a quux in the request.  This isn't going to work." }
--   
err417 :: ServerError -- | err418 Expectation Failed -- -- Example: -- --
--   failingHandler :: Handler ()
--   failingHandler = throwError $ err418 { errBody = "Apologies, this is not a webserver but a teapot." }
--   
err418 :: ServerError -- | err422 Unprocessable Entity -- -- Example: -- --
--   failingHandler :: Handler ()
--   failingHandler = throwError $ err422 { errBody = "I understood your request, but can't process it." }
--   
err422 :: ServerError -- | err429 Too Many Requests -- -- Example: -- --
--   failingHandler :: Handler ()
--   failingHandler = throwError $ err429 { errBody = "You have sent too many requests in a short period of time." }
--   
err429 :: ServerError -- | err500 Internal Server Error -- -- Example: -- --
--   failingHandler :: Handler ()
--   failingHandler = throwError $ err500 { errBody = "Exception in module A.B.C:55.  Have a great day!" }
--   
err500 :: ServerError -- | err501 Not Implemented -- -- Example: -- --
--   failingHandler :: Handler ()
--   failingHandler = throwError $ err501 { errBody = "/v1/foo is not supported with quux in the request." }
--   
err501 :: ServerError -- | err502 Bad Gateway -- -- Example: -- --
--   failingHandler :: Handler ()
--   failingHandler = throwError $ err502 { errBody = "Tried gateway foo, bar, and baz.  None responded." }
--   
err502 :: ServerError -- | err503 Service Unavailable -- -- Example: -- --
--   failingHandler :: Handler ()
--   failingHandler = throwError $ err503 { errBody = "We're rewriting in PHP." }
--   
err503 :: ServerError -- | err504 Gateway Time-out -- -- Example: -- --
--   failingHandler :: Handler ()
--   failingHandler = throwError $ err504 { errBody = "Backend foobar did not respond in 5 seconds." }
--   
err504 :: ServerError -- | err505 HTTP Version not supported -- -- Example usage: -- --
--   failingHandler :: Handler ()
--   failingHandler = throwError $ err505 { errBody = "I support HTTP/4.0 only." }
--   
err505 :: ServerError instance GHC.Read.Read Servant.Server.Internal.ServerError.ServerError instance GHC.Classes.Eq Servant.Server.Internal.ServerError.ServerError instance GHC.Show.Show Servant.Server.Internal.ServerError.ServerError instance GHC.Exception.Type.Exception Servant.Server.Internal.ServerError.ServerError module Servant.Server.Internal.RouteResult -- | The result of matching against a path in the route tree. data RouteResult a -- | Keep trying other paths. The ServantError should only be 404, -- 405 or 406. Fail :: ServerError -> RouteResult a -- | Don't try other paths. FailFatal :: !ServerError -> RouteResult a Route :: !a -> RouteResult a newtype RouteResultT m a RouteResultT :: m (RouteResult a) -> RouteResultT m a [$sel:runRouteResultT:RouteResultT] :: RouteResultT m a -> m (RouteResult a) instance GHC.Base.Functor Servant.Server.Internal.RouteResult.RouteResult instance GHC.Read.Read a => GHC.Read.Read (Servant.Server.Internal.RouteResult.RouteResult a) instance GHC.Show.Show a => GHC.Show.Show (Servant.Server.Internal.RouteResult.RouteResult a) instance GHC.Classes.Eq a => GHC.Classes.Eq (Servant.Server.Internal.RouteResult.RouteResult a) instance GHC.Base.Functor m => GHC.Base.Functor (Servant.Server.Internal.RouteResult.RouteResultT m) instance Control.Monad.Trans.Class.MonadTrans Servant.Server.Internal.RouteResult.RouteResultT instance (GHC.Base.Functor m, GHC.Base.Monad m) => GHC.Base.Applicative (Servant.Server.Internal.RouteResult.RouteResultT m) instance GHC.Base.Monad m => GHC.Base.Monad (Servant.Server.Internal.RouteResult.RouteResultT m) instance Control.Monad.IO.Class.MonadIO m => Control.Monad.IO.Class.MonadIO (Servant.Server.Internal.RouteResult.RouteResultT m) instance Control.Monad.Base.MonadBase b m => Control.Monad.Base.MonadBase b (Servant.Server.Internal.RouteResult.RouteResultT m) instance Control.Monad.Trans.Control.MonadBaseControl b m => Control.Monad.Trans.Control.MonadBaseControl b (Servant.Server.Internal.RouteResult.RouteResultT m) instance Control.Monad.Trans.Control.MonadTransControl Servant.Server.Internal.RouteResult.RouteResultT instance Control.Monad.Catch.MonadThrow m => Control.Monad.Catch.MonadThrow (Servant.Server.Internal.RouteResult.RouteResultT m) instance GHC.Base.Applicative Servant.Server.Internal.RouteResult.RouteResult instance GHC.Base.Monad Servant.Server.Internal.RouteResult.RouteResult module Servant.Server.Internal.RoutingApplication type RoutingApplication = -- | the request, the field 'pathInfo' may be modified by url routing Request -> (RouteResult Response -> IO ResponseReceived) -> IO ResponseReceived toApplication :: RoutingApplication -> Application module Servant.Server.Internal.Handler newtype Handler a Handler :: ExceptT ServerError IO a -> Handler a [$sel:runHandler':Handler] :: Handler a -> ExceptT ServerError IO a runHandler :: Handler a -> IO (Either ServerError a) -- | Pattern synonym that matches directly on the inner IO action. -- -- To lift IO actions that don't carry a ServerError, use -- liftIO instead. pattern MkHandler :: IO (Either ServerError a) -> Handler a instance Control.Monad.Catch.MonadMask Servant.Server.Internal.Handler.Handler instance Control.Monad.Catch.MonadCatch Servant.Server.Internal.Handler.Handler instance Control.Monad.Catch.MonadThrow Servant.Server.Internal.Handler.Handler instance Control.Monad.Error.Class.MonadError Servant.Server.Internal.ServerError.ServerError Servant.Server.Internal.Handler.Handler instance Control.Monad.IO.Class.MonadIO Servant.Server.Internal.Handler.Handler instance GHC.Base.Monad Servant.Server.Internal.Handler.Handler instance GHC.Base.Applicative Servant.Server.Internal.Handler.Handler instance GHC.Base.Functor Servant.Server.Internal.Handler.Handler instance GHC.Generics.Generic (Servant.Server.Internal.Handler.Handler a) instance Control.Monad.Fail.MonadFail Servant.Server.Internal.Handler.Handler instance Control.Monad.Base.MonadBase GHC.Types.IO Servant.Server.Internal.Handler.Handler instance Control.Monad.Trans.Control.MonadBaseControl GHC.Types.IO Servant.Server.Internal.Handler.Handler module Servant.Server.Internal.ErrorFormatter -- | A collection of error formatters for different situations. -- -- If you need to override one of them, use defaultErrorFormatters -- with record update syntax. data ErrorFormatters ErrorFormatters :: ErrorFormatter -> ErrorFormatter -> ErrorFormatter -> NotFoundErrorFormatter -> ErrorFormatters -- | Format error from parsing the request body. [$sel:bodyParserErrorFormatter:ErrorFormatters] :: ErrorFormatters -> ErrorFormatter -- | Format error from parsing url parts or query parameters. [$sel:urlParseErrorFormatter:ErrorFormatters] :: ErrorFormatters -> ErrorFormatter -- | Format error from parsing request headers. [$sel:headerParseErrorFormatter:ErrorFormatters] :: ErrorFormatters -> ErrorFormatter -- | Format error for not found URLs. [$sel:notFoundErrorFormatter:ErrorFormatters] :: ErrorFormatters -> NotFoundErrorFormatter -- | A custom formatter for errors produced by parsing combinators like -- ReqBody or Capture. -- -- A TypeRep argument described the concrete combinator that -- raised the error, allowing formatter to customize the message for -- different combinators. -- -- A full Request is also passed so that the formatter can react -- to Accept header, for example. type ErrorFormatter = TypeRep -> Request -> String -> ServerError -- | This formatter does not get neither TypeRep nor error message. type NotFoundErrorFormatter = Request -> ServerError -- | Context that contains default error formatters. type DefaultErrorFormatters = '[ErrorFormatters] -- | Default formatters will just return HTTP 400 status code with error -- message as response body. defaultErrorFormatters :: ErrorFormatters type MkContextWithErrorFormatter (ctx :: [Type]) = ctx .++ DefaultErrorFormatters mkContextWithErrorFormatter :: forall (ctx :: [Type]). Context ctx -> Context (MkContextWithErrorFormatter ctx) module Servant.Server.Internal.Router type Router env = Router' env RoutingApplication -- | Holds information about pieces of url that are captured as variables. data CaptureHint CaptureHint :: Text -> TypeRep -> CaptureHint -- | Holds the name of the captured variable [$sel:captureName:CaptureHint] :: CaptureHint -> Text -- | Holds the type of the captured variable [$sel:captureType:CaptureHint] :: CaptureHint -> TypeRep toCaptureTag :: CaptureHint -> Text toCaptureTags :: [CaptureHint] -> Text -- | Internal representation of a router. -- -- The first argument describes an environment type that is expected as -- extra input by the routers at the leaves. The environment is filled -- while running the router, with path components that can be used to -- process captures. data Router' env a -- | the map contains routers for subpaths (first path component used for -- lookup and removed afterwards), the list contains handlers for the -- empty path, to be tried in order StaticRouter :: Map Text (Router' env a) -> [env -> a] -> Router' env a -- | first path component is passed to the child router in its environment -- and removed afterwards. The first argument is a list of hints for all -- variables that can be captured by the router. The fact that it is a -- list is counter-intuitive, because the Capture combinator -- only allows to capture a single varible, with a single name and a -- single type. However, the choice smart constructor may merge -- two Capture combinators with different hints, thus forcing -- the type to be '[CaptureHint]'. Because CaptureRouter is built -- from a Capture combinator, the list of hints should always be -- non-empty. CaptureRouter :: [CaptureHint] -> Router' (Text, env) a -> Router' env a -- | all path components are passed to the child router in its environment -- and are removed afterwards The first argument is a hint for the list -- of variables that can be captured by the router. Note that the -- $sel:captureType:CaptureHint field of the hint should always be -- '[a]' for some a. CaptureAllRouter :: [CaptureHint] -> Router' ([Text], env) a -> Router' env a -- | to be used for routes we do not know anything about RawRouter :: (env -> a) -> Router' env a -- | left-biased choice between two routers Choice :: Router' env a -> Router' env a -> Router' env a -- | Smart constructor for a single static path component. pathRouter :: Text -> Router' env a -> Router' env a -- | Smart constructor for a leaf, i.e., a router that expects the empty -- path. leafRouter :: (env -> a) -> Router' env a -- | Smart constructor for the choice between routers. We currently -- optimize the following cases: -- -- choice :: Router' env a -> Router' env a -> Router' env a -- | Datatype used for representing and debugging the structure of a -- router. Abstracts from the handlers at the leaves. -- -- Two Routers can be structurally compared by computing their -- RouterStructure using routerStructure and then testing -- for equality, see sameStructure. data RouterStructure StaticRouterStructure :: Map Text RouterStructure -> Int -> RouterStructure -- | The first argument holds information about variables that are captured -- by the router. There may be several hints if several routers have been -- aggregated by the choice smart constructor. CaptureRouterStructure :: [CaptureHint] -> RouterStructure -> RouterStructure RawRouterStructure :: RouterStructure ChoiceStructure :: RouterStructure -> RouterStructure -> RouterStructure -- | Compute the structure of a router. -- -- Assumes that the request or text being passed in WithRequest -- or CaptureRouter does not affect the structure of the -- underlying tree. routerStructure :: Router' env a -> RouterStructure -- | Compare the structure of two routers. sameStructure :: Router' env a -> Router' env b -> Bool -- | Provide a textual representation of the structure of a router. routerLayout :: Router' env a -> Text -- | Apply a transformation to the response of a Router. tweakResponse :: (RouteResult Response -> RouteResult Response) -> Router env -> Router env -- | Interpret a router as an application. runRouter :: NotFoundErrorFormatter -> Router () -> RoutingApplication runRouterEnv :: NotFoundErrorFormatter -> Router env -> env -> RoutingApplication -- | Try a list of routing applications in order. We stop as soon as one -- fails fatally or succeeds. If all fail normally, we pick the "best" -- error. runChoice :: NotFoundErrorFormatter -> [env -> RoutingApplication] -> env -> RoutingApplication worseHTTPCode :: Int -> Int -> Bool instance GHC.Classes.Eq Servant.Server.Internal.Router.CaptureHint instance GHC.Show.Show Servant.Server.Internal.Router.CaptureHint instance GHC.Base.Functor (Servant.Server.Internal.Router.Router' env) instance GHC.Show.Show Servant.Server.Internal.Router.RouterStructure instance GHC.Classes.Eq Servant.Server.Internal.Router.RouterStructure module Servant.Server.Internal.DelayedIO -- | Computations used in a Delayed can depend on the incoming -- Request, may perform IO, and result in a -- RouteResult, meaning they can either succeed, fail (with the -- possibility to recover), or fail fatally. newtype DelayedIO a DelayedIO :: ReaderT Request (ResourceT (RouteResultT IO)) a -> DelayedIO a [$sel:runDelayedIO':DelayedIO] :: DelayedIO a -> ReaderT Request (ResourceT (RouteResultT IO)) a liftRouteResult :: RouteResult a -> DelayedIO a runDelayedIO :: DelayedIO a -> Request -> ResourceT IO (RouteResult a) -- | Fail with the option to recover. delayedFail :: ServerError -> DelayedIO a -- | Fail fatally, i.e., without any option to recover. delayedFailFatal :: ServerError -> DelayedIO a -- | Gain access to the incoming request. withRequest :: (Request -> DelayedIO a) -> DelayedIO a instance Control.Monad.Trans.Resource.Internal.MonadResource Servant.Server.Internal.DelayedIO.DelayedIO instance Control.Monad.Catch.MonadThrow Servant.Server.Internal.DelayedIO.DelayedIO instance Control.Monad.Reader.Class.MonadReader Network.Wai.Internal.Request Servant.Server.Internal.DelayedIO.DelayedIO instance Control.Monad.IO.Class.MonadIO Servant.Server.Internal.DelayedIO.DelayedIO instance GHC.Base.Monad Servant.Server.Internal.DelayedIO.DelayedIO instance GHC.Base.Applicative Servant.Server.Internal.DelayedIO.DelayedIO instance GHC.Base.Functor Servant.Server.Internal.DelayedIO.DelayedIO instance Control.Monad.Base.MonadBase GHC.Types.IO Servant.Server.Internal.DelayedIO.DelayedIO instance Control.Monad.Trans.Control.MonadBaseControl GHC.Types.IO Servant.Server.Internal.DelayedIO.DelayedIO module Servant.Server.Internal.Delayed -- | A Delayed is a representation of a handler with scheduled -- delayed checks that can trigger errors. -- -- Why would we want to delay checks? -- -- There are two reasons: -- --
    --
  1. In a straight-forward implementation, the order in which we -- perform checks will determine the error we generate. This is because -- once an error occurs, we would abort and not perform any subsequent -- checks, but rather return the current error.
  2. --
-- -- This is not a necessity: we could continue doing other checks, and -- choose the preferred error. However, that would in general mean more -- checking, which leads us to the other reason. -- --
    --
  1. We really want to avoid doing certain checks too early. For -- example, captures involve parsing, and are much more costly than -- static route matches. In particular, if several paths contain the -- "same" capture, we'd like as much as possible to avoid trying the same -- parse many times. Also tricky is the request body. Again, this -- involves parsing, but also, WAI makes obtaining the request body a -- side-effecting operation. We could/can work around this by manually -- caching the request body, but we'd rather keep the number of times we -- actually try to decode the request body to an absolute minimum.
  2. --
-- -- We prefer to have the following relative priorities of error codes: -- --
--   404
--   405 (bad method)
--   401 (unauthorized)
--   415 (unsupported media type)
--   406 (not acceptable)
--   400 (bad request)
--   
-- -- Therefore, while routing, we delay most checks so that they will -- ultimately occur in the right order. -- -- A Delayed contains many delayed blocks of tests, and the actual -- handler: -- --
    --
  1. Delayed captures. These can actually cause 404, and while they're -- costly, they should be done first among the delayed checks (at least -- as long as we do not decouple the check order from the error -- reporting, see above). Delayed captures can provide inputs to the -- actual handler.
  2. --
  3. Method check(s). This can cause a 405. On success, it does not -- provide an input for the handler. Method checks are comparatively -- cheap.
  4. --
  5. Authentication checks. This can cause 401.
  6. --
  7. Accept and content type header checks. These checks can cause 415 -- and 406 errors.
  8. --
  9. Query parameter checks. They require parsing and can cause 400 if -- the parsing fails. Query parameter checks provide inputs to the -- handler
  10. --
  11. Header Checks. They also require parsing and can cause 400 if -- parsing fails.
  12. --
  13. Body check. The request body check can cause 400.
  14. --
data Delayed env c [Delayed] :: (env -> DelayedIO captures) -> DelayedIO () -> DelayedIO auth -> DelayedIO () -> DelayedIO contentType -> DelayedIO params -> DelayedIO headers -> (contentType -> DelayedIO body) -> (captures -> params -> headers -> auth -> body -> Request -> RouteResult c) -> Delayed env c -- | A Delayed without any stored checks. emptyDelayed :: RouteResult a -> Delayed env a -- | Add a capture to the end of the capture block. addCapture :: Delayed env (a -> b) -> (captured -> DelayedIO a) -> Delayed (captured, env) b -- | Add a parameter check to the end of the params block addParameterCheck :: Delayed env (a -> b) -> DelayedIO a -> Delayed env b -- | Add a parameter check to the end of the params block addHeaderCheck :: Delayed env (a -> b) -> DelayedIO a -> Delayed env b -- | Add a method check to the end of the method block. addMethodCheck :: Delayed env a -> DelayedIO () -> Delayed env a -- | Add an auth check to the end of the auth block. addAuthCheck :: Delayed env (a -> b) -> DelayedIO a -> Delayed env b -- | Add a content type and body checks around parameter checks. -- -- We'll report failed content type check (415), before trying to parse -- query parameters (400). Which, in turn, happens before request body -- parsing. addBodyCheck :: Delayed env (a -> b) -> DelayedIO c -> (c -> DelayedIO a) -> Delayed env b -- | Add an accept header check before handling parameters. In principle, -- we'd like to take a bad body (400) response take precedence over a -- failed accept check (406). BUT to allow streaming the body, we cannot -- run the body check and then still backtrack. We therefore do the -- accept check before the body check, when we can still backtrack. There -- are other solutions to this, but they'd be more complicated (such as -- delaying the body check further so that it can still be run in a -- situation where we'd otherwise report 406). addAcceptCheck :: Delayed env a -> DelayedIO () -> Delayed env a -- | Many combinators extract information that is passed to the handler -- without the possibility of failure. In such a case, -- passToServer can be used. passToServer :: Delayed env (a -> b) -> (Request -> a) -> Delayed env b -- | Run a delayed server. Performs all scheduled operations in order, and -- passes the results from the capture and body blocks on to the actual -- handler. -- -- This should only be called once per request; otherwise the guarantees -- about effect and HTTP error ordering break down. runDelayed :: Delayed env a -> env -> Request -> ResourceT IO (RouteResult a) -- | Runs a delayed server and the resulting action. Takes a continuation -- that lets us send a response. Also takes a continuation for how to -- turn the result of the delayed server into a response. runAction :: Delayed env (Handler a) -> env -> Request -> (RouteResult Response -> IO r) -> (a -> RouteResult Response) -> IO r instance GHC.Base.Functor (Servant.Server.Internal.Delayed.Delayed env) module Servant.Server.Internal.BasicAuth -- | servant-server's current implementation of basic authentication is not -- immune to certain kinds of timing attacks. Decoding payloads does not -- take a fixed amount of time. -- -- The result of authentication/authorization data BasicAuthResult usr Unauthorized :: BasicAuthResult usr BadPassword :: BasicAuthResult usr NoSuchUser :: BasicAuthResult usr Authorized :: usr -> BasicAuthResult usr -- | Datatype wrapping a function used to check authentication. newtype BasicAuthCheck usr BasicAuthCheck :: (BasicAuthData -> IO (BasicAuthResult usr)) -> BasicAuthCheck usr [$sel:unBasicAuthCheck:BasicAuthCheck] :: BasicAuthCheck usr -> BasicAuthData -> IO (BasicAuthResult usr) -- | Internal method to make a basic-auth challenge mkBAChallengerHdr :: ByteString -> Header -- | Find and decode an Authorization header from the request as -- Basic Auth decodeBAHdr :: Request -> Maybe BasicAuthData -- | Run and check basic authentication, returning the appropriate http -- error per the spec. runBasicAuth :: Request -> ByteString -> BasicAuthCheck usr -> DelayedIO usr instance GHC.Base.Functor Servant.Server.Internal.BasicAuth.BasicAuthResult instance GHC.Generics.Generic (Servant.Server.Internal.BasicAuth.BasicAuthResult usr) instance GHC.Read.Read usr => GHC.Read.Read (Servant.Server.Internal.BasicAuth.BasicAuthResult usr) instance GHC.Show.Show usr => GHC.Show.Show (Servant.Server.Internal.BasicAuth.BasicAuthResult usr) instance GHC.Classes.Eq usr => GHC.Classes.Eq (Servant.Server.Internal.BasicAuth.BasicAuthResult usr) instance GHC.Base.Functor Servant.Server.Internal.BasicAuth.BasicAuthCheck instance GHC.Generics.Generic (Servant.Server.Internal.BasicAuth.BasicAuthCheck usr) module Servant.Server.Internal type Server api = ServerT api Handler class HasServer api context where { -- | The type of a server for this API, given a monad to run effects in. -- -- Note that the result kind is *, so it is not a monad -- transformer, unlike what the T in the name might suggest. type ServerT api (m :: Type -> Type) :: Type; } route :: HasServer api context => Proxy api -> Context context -> Delayed env (Server api) -> Router env hoistServerWithContext :: HasServer api context => Proxy api -> Proxy context -> (forall x. m x -> n x) -> ServerT api m -> ServerT api n -- | Singleton type representing a server that serves an empty API. data EmptyServer EmptyServer :: EmptyServer -- | A type that specifies that an API record contains a server -- implementation. data AsServerT (m :: Type -> Type) type AsServer = AsServerT Handler type HasServerArrowTypeError a b = 'Text "No instance HasServer (a -> b)." ':$$: 'Text "Maybe you have used '->' instead of ':>' between " ':$$: 'ShowType a ':$$: 'Text "and" ':$$: 'ShowType b -- | Set of constraints required to convert to / from vanilla server types. type GServerConstraints api m = (ToServant api (AsServerT m) ~ ServerT (ToServantApi api) m, GServantProduct (Rep (api (AsServerT m)))) -- | This class is a necessary evil: in the implementation of -- HasServer for NamedRoutes api, we essentially -- need the quantified constraint forall m. GServerConstraints -- m to hold. -- -- We cannot require do that directly as the definition of -- GServerConstraints contains type family applications -- (Rep and ServerT). The trick is to hide those type -- family applications behind a typeclass providing evidence for -- GServerConstraints api m in the form of a dictionary, -- and require that forall m. GServer api m instead. -- -- Users shouldn't have to worry about this class, as the only possible -- instance is provided in this module for all record APIs. class GServer (api :: Type -> Type) (m :: Type -> Type) gServerProof :: GServer api m => Dict (GServerConstraints api m) -- | Server for EmptyAPI emptyServer :: ServerT EmptyAPI m getAcceptHeader :: Request -> AcceptHeader acceptCheck :: AllMime list => Proxy list -> AcceptHeader -> DelayedIO () allowedMethodHead :: Method -> Request -> Bool methodCheck :: Method -> Request -> DelayedIO () allowedMethod :: Method -> Request -> Bool methodRouter :: AllCTRender ctypes a => (b -> ([(HeaderName, ByteString)], a)) -> Method -> Proxy ctypes -> Status -> Delayed env (Handler b) -> Router env noContentRouter :: Method -> Status -> Delayed env (Handler b) -> Router env streamRouter :: forall ctype a c chunk env framing. (MimeRender ctype chunk, FramingRender framing, ToSourceIO chunk a) => (c -> ([(HeaderName, ByteString)], a)) -> Method -> Status -> Proxy framing -> Proxy ctype -> Delayed env (Handler c) -> Router env parseDeepParam :: (Text, Maybe Text) -> Either String ([Text], Maybe Text) ct_wildcard :: ByteString instance GHC.Enum.Enum Servant.Server.Internal.EmptyServer instance GHC.Enum.Bounded Servant.Server.Internal.EmptyServer instance GHC.Show.Show Servant.Server.Internal.EmptyServer instance GHC.Classes.Eq Servant.Server.Internal.EmptyServer instance (Servant.API.Generic.ToServant api (Servant.Server.Internal.AsServerT m) GHC.Types.~ Servant.Server.Internal.ServerT (Servant.API.Generic.ToServantApi api) m, Servant.API.Generic.GServantProduct (GHC.Generics.Rep (api (Servant.Server.Internal.AsServerT m)))) => Servant.Server.Internal.GServer api m instance (Servant.Server.Internal.HasServer (Servant.API.Generic.ToServantApi api) context, forall (m :: GHC.Types.Type -> GHC.Types.Type). GHC.Generics.Generic (api (Servant.Server.Internal.AsServerT m)), forall (m :: GHC.Types.Type -> GHC.Types.Type). Servant.Server.Internal.GServer api m, Servant.API.TypeErrors.ErrorIfNoGeneric api) => Servant.Server.Internal.HasServer (Servant.API.NamedRoutes.NamedRoutes api) context instance Servant.API.Generic.GenericMode (Servant.Server.Internal.AsServerT m) instance (TypeError ...) => Servant.Server.Internal.HasServer (a -> b) context instance Servant.Server.Internal.HasServer Servant.API.Empty.EmptyAPI context instance (Servant.Server.Internal.HasServer a context, Servant.Server.Internal.HasServer b context) => Servant.Server.Internal.HasServer (a Servant.API.Alternative.:<|> b) context instance (GHC.TypeLits.KnownSymbol capture, Web.Internal.HttpApiData.FromHttpApiData a, Data.Typeable.Internal.Typeable a, Servant.Server.Internal.HasServer api context, Data.Singletons.Bool.SBoolI (Servant.API.Modifiers.FoldLenient mods), Servant.Server.Internal.Context.HasContextEntry (Servant.Server.Internal.ErrorFormatter.MkContextWithErrorFormatter context) Servant.Server.Internal.ErrorFormatter.ErrorFormatters) => Servant.Server.Internal.HasServer (Servant.API.Capture.Capture' mods capture a Servant.API.Sub.:> api) context instance (GHC.TypeLits.KnownSymbol capture, Web.Internal.HttpApiData.FromHttpApiData a, Data.Typeable.Internal.Typeable a, Servant.Server.Internal.HasServer api context, Servant.Server.Internal.Context.HasContextEntry (Servant.Server.Internal.ErrorFormatter.MkContextWithErrorFormatter context) Servant.Server.Internal.ErrorFormatter.ErrorFormatters) => Servant.Server.Internal.HasServer (Servant.API.Capture.CaptureAll capture a Servant.API.Sub.:> api) context instance (Servant.Server.Internal.HasServer api ctx, Servant.Server.Internal.Context.HasContextEntry ctx (Data.Acquire.Internal.Acquire a)) => Servant.Server.Internal.HasServer (Servant.API.WithResource.WithResource a Servant.API.Sub.:> api) ctx instance forall k1 (ctypes :: [GHC.Types.Type]) a (method :: k1) (status :: GHC.TypeNats.Nat) (context :: [GHC.Types.Type]). (Servant.API.ContentTypes.AllCTRender ctypes a, Servant.API.Verbs.ReflectMethod method, GHC.TypeNats.KnownNat status) => Servant.Server.Internal.HasServer (Servant.API.Verbs.Verb method status ctypes a) context instance forall k1 (ctypes :: [GHC.Types.Type]) a (method :: k1) (status :: GHC.TypeNats.Nat) (h :: [GHC.Types.Type]) (context :: [GHC.Types.Type]). (Servant.API.ContentTypes.AllCTRender ctypes a, Servant.API.Verbs.ReflectMethod method, GHC.TypeNats.KnownNat status, Servant.API.ResponseHeaders.GetHeaders (Servant.API.ResponseHeaders.Headers h a)) => Servant.Server.Internal.HasServer (Servant.API.Verbs.Verb method status ctypes (Servant.API.ResponseHeaders.Headers h a)) context instance forall k1 (method :: k1) (context :: [GHC.Types.Type]). Servant.API.Verbs.ReflectMethod method => Servant.Server.Internal.HasServer (Servant.API.Verbs.NoContentVerb method) context instance forall k1 ctype chunk (method :: k1) (status :: GHC.TypeNats.Nat) framing a (context :: [GHC.Types.Type]). (Servant.API.ContentTypes.MimeRender ctype chunk, Servant.API.Verbs.ReflectMethod method, GHC.TypeNats.KnownNat status, Servant.API.Stream.FramingRender framing, Servant.API.Stream.ToSourceIO chunk a) => Servant.Server.Internal.HasServer (Servant.API.Stream.Stream method status framing ctype a) context instance forall k1 ctype chunk (method :: k1) (status :: GHC.TypeNats.Nat) framing a (h :: [GHC.Types.Type]) (context :: [GHC.Types.Type]). (Servant.API.ContentTypes.MimeRender ctype chunk, Servant.API.Verbs.ReflectMethod method, GHC.TypeNats.KnownNat status, Servant.API.Stream.FramingRender framing, Servant.API.Stream.ToSourceIO chunk a, Servant.API.ResponseHeaders.GetHeaders (Servant.API.ResponseHeaders.Headers h a)) => Servant.Server.Internal.HasServer (Servant.API.Stream.Stream method status framing ctype (Servant.API.ResponseHeaders.Headers h a)) context instance (GHC.TypeLits.KnownSymbol sym, Web.Internal.HttpApiData.FromHttpApiData a, Servant.Server.Internal.HasServer api context, Data.Singletons.Bool.SBoolI (Servant.API.Modifiers.FoldRequired mods), Data.Singletons.Bool.SBoolI (Servant.API.Modifiers.FoldLenient mods), Servant.Server.Internal.Context.HasContextEntry (Servant.Server.Internal.ErrorFormatter.MkContextWithErrorFormatter context) Servant.Server.Internal.ErrorFormatter.ErrorFormatters) => Servant.Server.Internal.HasServer (Servant.API.Header.Header' mods sym a Servant.API.Sub.:> api) context instance (GHC.TypeLits.KnownSymbol sym, Web.Internal.HttpApiData.FromHttpApiData a, Servant.Server.Internal.HasServer api context, Data.Singletons.Bool.SBoolI (Servant.API.Modifiers.FoldRequired mods), Data.Singletons.Bool.SBoolI (Servant.API.Modifiers.FoldLenient mods), Servant.Server.Internal.Context.HasContextEntry (Servant.Server.Internal.ErrorFormatter.MkContextWithErrorFormatter context) Servant.Server.Internal.ErrorFormatter.ErrorFormatters) => Servant.Server.Internal.HasServer (Servant.API.QueryParam.QueryParam' mods sym a Servant.API.Sub.:> api) context instance (GHC.TypeLits.KnownSymbol sym, Web.Internal.HttpApiData.FromHttpApiData a, Servant.Server.Internal.HasServer api context, Servant.Server.Internal.Context.HasContextEntry (Servant.Server.Internal.ErrorFormatter.MkContextWithErrorFormatter context) Servant.Server.Internal.ErrorFormatter.ErrorFormatters) => Servant.Server.Internal.HasServer (Servant.API.QueryParam.QueryParams sym a Servant.API.Sub.:> api) context instance (GHC.TypeLits.KnownSymbol sym, Servant.Server.Internal.HasServer api context) => Servant.Server.Internal.HasServer (Servant.API.QueryParam.QueryFlag sym Servant.API.Sub.:> api) context instance Servant.Server.Internal.HasServer api context => Servant.Server.Internal.HasServer (Servant.API.QueryString.QueryString Servant.API.Sub.:> api) context instance (GHC.TypeLits.KnownSymbol sym, Servant.API.QueryString.FromDeepQuery a, Servant.Server.Internal.HasServer api context, Servant.Server.Internal.Context.HasContextEntry (Servant.Server.Internal.ErrorFormatter.MkContextWithErrorFormatter context) Servant.Server.Internal.ErrorFormatter.ErrorFormatters) => Servant.Server.Internal.HasServer (Servant.API.QueryString.DeepQuery sym a Servant.API.Sub.:> api) context instance Servant.Server.Internal.HasServer Servant.API.Raw.Raw context instance Servant.Server.Internal.HasServer Servant.API.Raw.RawM context instance (Servant.API.ContentTypes.AllCTUnrender list a, Servant.Server.Internal.HasServer api context, Data.Singletons.Bool.SBoolI (Servant.API.Modifiers.FoldLenient mods), Servant.Server.Internal.Context.HasContextEntry (Servant.Server.Internal.ErrorFormatter.MkContextWithErrorFormatter context) Servant.Server.Internal.ErrorFormatter.ErrorFormatters) => Servant.Server.Internal.HasServer (Servant.API.ReqBody.ReqBody' mods list a Servant.API.Sub.:> api) context instance (Servant.API.Stream.FramingUnrender framing, Servant.API.Stream.FromSourceIO chunk a, Servant.API.ContentTypes.MimeUnrender ctype chunk, Servant.Server.Internal.HasServer api context) => Servant.Server.Internal.HasServer (Servant.API.Stream.StreamBody' mods framing ctype a Servant.API.Sub.:> api) context instance (GHC.TypeLits.KnownSymbol path, Servant.Server.Internal.HasServer api context) => Servant.Server.Internal.HasServer (path Servant.API.Sub.:> api) context instance Servant.Server.Internal.HasServer api context => Servant.Server.Internal.HasServer (Servant.API.RemoteHost.RemoteHost Servant.API.Sub.:> api) context instance Servant.Server.Internal.HasServer api context => Servant.Server.Internal.HasServer (Servant.API.IsSecure.IsSecure Servant.API.Sub.:> api) context instance Servant.Server.Internal.HasServer api context => Servant.Server.Internal.HasServer (Data.Vault.Lazy.Vault Servant.API.Sub.:> api) context instance Servant.Server.Internal.HasServer api context => Servant.Server.Internal.HasServer (Network.HTTP.Types.Version.HttpVersion Servant.API.Sub.:> api) context instance Servant.Server.Internal.HasServer api ctx => Servant.Server.Internal.HasServer (Servant.API.Description.Summary desc Servant.API.Sub.:> api) ctx instance Servant.Server.Internal.HasServer api ctx => Servant.Server.Internal.HasServer (Servant.API.Description.Description desc Servant.API.Sub.:> api) ctx instance Servant.Server.Internal.HasServer api context => Servant.Server.Internal.HasServer (Servant.API.Empty.EmptyAPI Servant.API.Sub.:> api) context instance (GHC.TypeLits.KnownSymbol realm, Servant.Server.Internal.HasServer api context, Servant.Server.Internal.Context.HasContextEntry context (Servant.Server.Internal.BasicAuth.BasicAuthCheck usr)) => Servant.Server.Internal.HasServer (Servant.API.BasicAuth.BasicAuth realm usr Servant.API.Sub.:> api) context instance forall k (context :: [GHC.Types.Type]) (name :: GHC.Types.Symbol) (subContext :: [GHC.Types.Type]) (subApi :: k). (Servant.Server.Internal.Context.HasContextEntry context (Servant.Server.Internal.Context.NamedContext name subContext), Servant.Server.Internal.HasServer subApi subContext) => Servant.Server.Internal.HasServer (Servant.API.WithNamedContext.WithNamedContext name subContext subApi) context instance forall a b (arr :: a -> b) sub (context :: [GHC.Types.Type]). (TypeError ...) => Servant.Server.Internal.HasServer (arr Servant.API.Sub.:> sub) context instance forall k (ty :: k) sub (context :: [GHC.Types.Type]). (TypeError ...) => Servant.Server.Internal.HasServer (ty Servant.API.Sub.:> sub) context instance forall k (api :: k) (context :: [GHC.Types.Type]). (TypeError ...) => Servant.Server.Internal.HasServer api context instance (Servant.API.TypeLevel.AtMostOneFragment api, Servant.API.TypeLevel.FragmentUnique (Servant.API.Fragment.Fragment a1 Servant.API.Sub.:> api), Servant.Server.Internal.HasServer api context) => Servant.Server.Internal.HasServer (Servant.API.Fragment.Fragment a1 Servant.API.Sub.:> api) context module Servant.Server.UVerb -- | return for UVerb handlers. Takes a value of any of the -- members of the open union, and will construct a union value in an -- Applicative (eg. Server). respond :: forall (x :: Type) (xs :: [Type]) (f :: Type -> Type). (Applicative f, HasStatus x, IsMember x xs) => x -> f (Union xs) class IsServerResource (cts :: [Type]) a instance (Servant.API.Verbs.ReflectMethod method, Servant.API.ContentTypes.AllMime contentTypes, Data.SOP.Constraint.All (Servant.Server.UVerb.IsServerResourceWithStatus contentTypes) as, Servant.API.UVerb.Union.Unique (Servant.API.UVerb.Statuses as)) => Servant.Server.Internal.HasServer (Servant.API.UVerb.UVerb method contentTypes as) context instance Servant.API.ContentTypes.AllCTRender cts a => Servant.Server.UVerb.IsServerResource cts a instance (Servant.Server.UVerb.IsServerResource cts a, Servant.API.ResponseHeaders.GetHeaders (Servant.API.ResponseHeaders.Headers h a)) => Servant.Server.UVerb.IsServerResource cts (Servant.API.ResponseHeaders.Headers h a) instance Servant.Server.UVerb.IsServerResource cts a => Servant.Server.UVerb.IsServerResource cts (Servant.API.UVerb.WithStatus n a) -- | This module lets you implement Servers for defined APIs. You'll -- most likely just need serve. module Servant.Server -- | serve allows you to implement an API and produce a wai -- Application. -- -- Example: -- --
--   type MyApi = "books" :> Get '[JSON] [Book] -- GET /books
--           :<|> "books" :> ReqBody '[JSON] Book :> Post '[JSON] Book -- POST /books
--   
--   server :: Server MyApi
--   server = listAllBooks :<|> postBook
--     where listAllBooks = ...
--           postBook book = ...
--   
--   myApi :: Proxy MyApi
--   myApi = Proxy
--   
--   app :: Application
--   app = serve myApi server
--   
--   main :: IO ()
--   main = Network.Wai.Handler.Warp.run 8080 app
--   
serve :: HasServer api '[] => Proxy api -> Server api -> Application -- | Like serve, but allows you to pass custom context. -- -- defaultErrorFormatters will always be appended to the end of -- the passed context, but if you pass your own formatter, it will -- override the default one. serveWithContext :: (HasServer api context, ServerContext context) => Proxy api -> Context context -> Server api -> Application -- | A general serve function that allows you to pass a custom -- context and hoisting function to apply on all routes. serveWithContextT :: forall api context m. (HasServer api context, ServerContext context) => Proxy api -> Context context -> (forall x. m x -> Handler x) -> ServerT api m -> Application -- | Constraints that need to be satisfied on a context for it to be passed -- to serveWithContext. -- -- Typically, this will add default context entries to the context. You -- shouldn't typically need to worry about these constraints, but if you -- write a helper function that wraps serveWithContext, you might -- need to include this constraint. type ServerContext context = (HasContextEntry (context .++ DefaultErrorFormatters) ErrorFormatters) toApplication :: RoutingApplication -> Application class HasServer api context where { -- | The type of a server for this API, given a monad to run effects in. -- -- Note that the result kind is *, so it is not a monad -- transformer, unlike what the T in the name might suggest. type ServerT api (m :: Type -> Type) :: Type; } route :: HasServer api context => Proxy api -> Context context -> Delayed env (Server api) -> Router env hoistServerWithContext :: HasServer api context => Proxy api -> Proxy context -> (forall x. m x -> n x) -> ServerT api m -> ServerT api n type Server api = ServerT api Handler -- | Singleton type representing a server that serves an empty API. data EmptyServer -- | Server for EmptyAPI emptyServer :: ServerT EmptyAPI m newtype Handler a Handler :: ExceptT ServerError IO a -> Handler a [$sel:runHandler':Handler] :: Handler a -> ExceptT ServerError IO a runHandler :: Handler a -> IO (Either ServerError a) -- | Pattern synonym that matches directly on the inner IO action. -- -- To lift IO actions that don't carry a ServerError, use -- liftIO instead. pattern MkHandler :: IO (Either ServerError a) -> Handler a -- | The function layout produces a textual description of the -- internal router layout for debugging purposes. Note that the router -- layout is determined just by the API, not by the handlers. -- -- Example: -- -- For the following API -- --
--   type API =
--          "a" :> "d" :> Get '[JSON] NoContent
--     :<|> "b" :> Capture "x" Int :> Get '[JSON] Bool
--     :<|> "c" :> Put '[JSON] Bool
--     :<|> "a" :> "e" :> Get '[JSON] Int
--     :<|> "b" :> Capture "x" Int :> Put '[JSON] Bool
--     :<|> Raw
--   
-- -- we get the following output: -- --
--   /
--   ├─ a/
--   │  ├─ d/
--   │  │  └─•
--   │  └─ e/
--   │     └─•
--   ├─ b/
--   │  └─ <x::Int>/
--   │     ├─•
--   │     ┆
--   │     └─•
--   ├─ c/
--   │  └─•
--   ┆
--   └─ <raw>
--   
-- -- Explanation of symbols: -- -- layout :: HasServer api '[] => Proxy api -> Text -- | Variant of layout that takes an additional Context. layoutWithContext :: HasServer api context => Proxy api -> Context context -> Text -- | Hoist server implementation. -- -- Sometimes our cherished Handler monad isn't quite the type -- you'd like for your handlers. Maybe you want to thread some -- configuration in a Reader monad. Or have your types ensure -- that your handlers don't do any IO. Use hoistServer (a -- successor of now deprecated enter). -- -- With hoistServer, you can provide a function, to convert any -- number of endpoints from one type constructor to another. For example -- -- Note: Server Raw can also be entered. It will -- be retagged. -- --
--   >>> import Control.Monad.Reader
--   
--   >>> type ReaderAPI = "ep1" :> Get '[JSON] Int :<|> "ep2" :> Get '[JSON] String :<|> Raw :<|> EmptyAPI
--   
--   >>> let readerApi = Proxy :: Proxy ReaderAPI
--   
--   >>> let readerServer = return 1797 :<|> ask :<|> Tagged (error "raw server") :<|> emptyServer :: ServerT ReaderAPI (Reader String)
--   
--   >>> let nt x = return (runReader x "hi")
--   
--   >>> let mainServer = hoistServer readerApi nt readerServer :: Server ReaderAPI
--   
hoistServer :: HasServer api '[] => Proxy api -> (forall x. m x -> n x) -> ServerT api m -> ServerT api n -- | Apply a transformation to the response of a Router. tweakResponse :: (RouteResult Response -> RouteResult Response) -> Router env -> Router env -- | Contexts are used to pass values to combinators. (They are -- not meant to be used to pass parameters to your handlers, i.e. -- they should not replace any custom ReaderT-monad-stack that -- you're using with hoistServer.) If you don't use combinators -- that require any context entries, you can just use serve as -- always. -- -- If you are using combinators that require a non-empty Context -- you have to use serveWithContext and pass it a Context -- that contains all the values your combinators need. A Context -- is essentially a heterogeneous list and accessing the elements is -- being done by type (see getContextEntry). The parameter of the -- type Context is a type-level list reflecting the types of the -- contained context entries. To create a Context with entries, -- use the operator (:.): -- --
--   >>> :type True :. () :. EmptyContext
--   True :. () :. EmptyContext :: Context '[Bool, ()]
--   
data Context contextTypes [EmptyContext] :: Context '[] [:.] :: x -> Context xs -> Context (x ': xs) infixr 5 :. -- | This class is used to access context entries in Contexts. -- getContextEntry returns the first value where the type matches: -- --
--   >>> getContextEntry (True :. False :. EmptyContext) :: Bool
--   True
--   
-- -- If the Context does not contain an entry of the requested type, -- you'll get an error: -- --
--   >>> getContextEntry (True :. False :. EmptyContext) :: String
--   ...
--   ...No instance for ...HasContextEntry '[] [Char]...
--   ...
--   
class HasContextEntry (context :: [Type]) (val :: Type) getContextEntry :: HasContextEntry context val => Context context -> val -- | Append two type-level lists. -- -- Hint: import it as -- --
--   import Servant.Server (type (.++))
--   
type family (.++) (l1 :: [Type]) (l2 :: [Type]) -- | Append two contexts. (.++) :: Context l1 -> Context l2 -> Context (l1 .++ l2) -- | Normally context entries are accessed by their types. In case you need -- to have multiple values of the same type in your Context and -- need to access them, we provide NamedContext. You can think of -- it as sub-namespaces for Contexts. data NamedContext (name :: Symbol) (subContext :: [Type]) NamedContext :: Context subContext -> NamedContext (name :: Symbol) (subContext :: [Type]) -- | descendIntoNamedContext allows you to access -- NamedContexts. Usually you won't have to use it yourself but -- instead use a combinator like WithNamedContext. -- -- This is how descendIntoNamedContext works: -- --
--   >>> :set -XFlexibleContexts
--   
--   >>> let subContext = True :. EmptyContext
--   
--   >>> :type subContext
--   subContext :: Context '[Bool]
--   
--   >>> let parentContext = False :. (NamedContext subContext :: NamedContext "subContext" '[Bool]) :. EmptyContext
--   
--   >>> :type parentContext
--   parentContext :: Context '[Bool, NamedContext "subContext" '[Bool]]
--   
--   >>> descendIntoNamedContext (Proxy :: Proxy "subContext") parentContext :: Context '[Bool]
--   True :. EmptyContext
--   
descendIntoNamedContext :: forall context name subContext. HasContextEntry context (NamedContext name subContext) => Proxy (name :: Symbol) -> Context context -> Context subContext -- | Datatype wrapping a function used to check authentication. newtype BasicAuthCheck usr BasicAuthCheck :: (BasicAuthData -> IO (BasicAuthResult usr)) -> BasicAuthCheck usr [$sel:unBasicAuthCheck:BasicAuthCheck] :: BasicAuthCheck usr -> BasicAuthData -> IO (BasicAuthResult usr) -- | servant-server's current implementation of basic authentication is not -- immune to certain kinds of timing attacks. Decoding payloads does not -- take a fixed amount of time. -- -- The result of authentication/authorization data BasicAuthResult usr Unauthorized :: BasicAuthResult usr BadPassword :: BasicAuthResult usr NoSuchUser :: BasicAuthResult usr Authorized :: usr -> BasicAuthResult usr data ServerError ServerError :: Int -> String -> ByteString -> [Header] -> ServerError [$sel:errHTTPCode:ServerError] :: ServerError -> Int [$sel:errReasonPhrase:ServerError] :: ServerError -> String [$sel:errBody:ServerError] :: ServerError -> ByteString [$sel:errHeaders:ServerError] :: ServerError -> [Header] -- | err300 Multiple Choices -- -- Example: -- --
--   failingHandler :: Handler ()
--   failingHandler = throwError $ err300 { errBody = "I can't choose." }
--   
err300 :: ServerError -- | err301 Moved Permanently -- -- Example: -- --
--   failingHandler :: Handler ()
--   failingHandler = throwError err301
--   
err301 :: ServerError -- | err302 Found -- -- Example: -- --
--   failingHandler :: Handler ()
--   failingHandler = throwError err302
--   
err302 :: ServerError -- | err303 See Other -- -- Example: -- --
--   failingHandler :: Handler ()
--   failingHandler = throwError err303
--   
err303 :: ServerError -- | err304 Not Modified -- -- Example: -- --
--   failingHandler :: Handler ()
--   failingHandler = throwError err304
--   
err304 :: ServerError -- | err305 Use Proxy -- -- Example: -- --
--   failingHandler :: Handler ()
--   failingHandler = throwError err305
--   
err305 :: ServerError -- | err307 Temporary Redirect -- -- Example: -- --
--   failingHandler :: Handler ()
--   failingHandler = throwError err307
--   
err307 :: ServerError -- | err400 Bad Request -- -- Example: -- --
--   failingHandler :: Handler ()
--   failingHandler = throwError $ err400 { errBody = "Your request makes no sense to me." }
--   
err400 :: ServerError -- | err401 Unauthorized -- -- Example: -- --
--   failingHandler :: Handler ()
--   failingHandler = throwError $ err401 { errBody = "Your credentials are invalid." }
--   
err401 :: ServerError -- | err402 Payment Required -- -- Example: -- --
--   failingHandler :: Handler ()
--   failingHandler = throwError $ err402 { errBody = "You have 0 credits. Please give me $$$." }
--   
err402 :: ServerError -- | err403 Forbidden -- -- Example: -- --
--   failingHandler :: Handler ()
--   failingHandler = throwError $ err403 { errBody = "Please login first." }
--   
err403 :: ServerError -- | err404 Not Found -- -- Example: -- --
--   failingHandler :: Handler ()
--   failingHandler = throwError $ err404 { errBody = "Are you lost?" }
--   
err404 :: ServerError -- | err405 Method Not Allowed -- -- Example: -- --
--   failingHandler :: Handler ()
--   failingHandler = throwError $ err405 { errBody = "Your account privileges does not allow for this.  Please pay $$$." }
--   
err405 :: ServerError -- | err406 Not Acceptable -- -- Example: -- --
--   failingHandler :: Handler ()
--   failingHandler = throwError err406
--   
err406 :: ServerError -- | err407 Proxy Authentication Required -- -- Example: -- --
--   failingHandler :: Handler ()
--   failingHandler = throwError err407
--   
err407 :: ServerError -- | err409 Conflict -- -- Example: -- --
--   failingHandler :: Handler ()
--   failingHandler = throwError $ err409 { errBody = "Transaction conflicts with 59879cb56c7c159231eeacdd503d755f7e835f74" }
--   
err409 :: ServerError -- | err410 Gone -- -- Example: -- --
--   failingHandler :: Handler ()
--   failingHandler = throwError $ err410 { errBody = "I know it was here at some point, but.. I blame bad luck." }
--   
err410 :: ServerError -- | err411 Length Required -- -- Example: -- --
--   failingHandler :: Handler ()
--   failingHandler = throwError err411
--   
err411 :: ServerError -- | err412 Precondition Failed -- -- Example: -- --
--   failingHandler :: Handler ()
--   failingHandler = throwError $ err412 { errBody = "Precondition fail: x < 42 && y > 57" }
--   
err412 :: ServerError -- | err413 Request Entity Too Large -- -- Example: -- --
--   failingHandler :: Handler ()
--   failingHandler = throwError $ err413 { errBody = "Request exceeded 64k." }
--   
err413 :: ServerError -- | err414 Request-URI Too Large -- -- Example: -- --
--   failingHandler :: Handler ()
--   failingHandler = throwError $ err414 { errBody = "Maximum length is 64." }
--   
err414 :: ServerError -- | err415 Unsupported Media Type -- -- Example: -- --
--   failingHandler :: Handler ()
--   failingHandler = throwError $ err415 { errBody = "Supported media types:  gif, png" }
--   
err415 :: ServerError -- | err416 Request range not satisfiable -- -- Example: -- --
--   failingHandler :: Handler ()
--   failingHandler = throwError $ err416 { errBody = "Valid range is [0, 424242]." }
--   
err416 :: ServerError -- | err417 Expectation Failed -- -- Example: -- --
--   failingHandler :: Handler ()
--   failingHandler = throwError $ err417 { errBody = "I found a quux in the request.  This isn't going to work." }
--   
err417 :: ServerError -- | err418 Expectation Failed -- -- Example: -- --
--   failingHandler :: Handler ()
--   failingHandler = throwError $ err418 { errBody = "Apologies, this is not a webserver but a teapot." }
--   
err418 :: ServerError -- | err422 Unprocessable Entity -- -- Example: -- --
--   failingHandler :: Handler ()
--   failingHandler = throwError $ err422 { errBody = "I understood your request, but can't process it." }
--   
err422 :: ServerError -- | err429 Too Many Requests -- -- Example: -- --
--   failingHandler :: Handler ()
--   failingHandler = throwError $ err429 { errBody = "You have sent too many requests in a short period of time." }
--   
err429 :: ServerError -- | err500 Internal Server Error -- -- Example: -- --
--   failingHandler :: Handler ()
--   failingHandler = throwError $ err500 { errBody = "Exception in module A.B.C:55.  Have a great day!" }
--   
err500 :: ServerError -- | err501 Not Implemented -- -- Example: -- --
--   failingHandler :: Handler ()
--   failingHandler = throwError $ err501 { errBody = "/v1/foo is not supported with quux in the request." }
--   
err501 :: ServerError -- | err502 Bad Gateway -- -- Example: -- --
--   failingHandler :: Handler ()
--   failingHandler = throwError $ err502 { errBody = "Tried gateway foo, bar, and baz.  None responded." }
--   
err502 :: ServerError -- | err503 Service Unavailable -- -- Example: -- --
--   failingHandler :: Handler ()
--   failingHandler = throwError $ err503 { errBody = "We're rewriting in PHP." }
--   
err503 :: ServerError -- | err504 Gateway Time-out -- -- Example: -- --
--   failingHandler :: Handler ()
--   failingHandler = throwError $ err504 { errBody = "Backend foobar did not respond in 5 seconds." }
--   
err504 :: ServerError -- | err505 HTTP Version not supported -- -- Example usage: -- --
--   failingHandler :: Handler ()
--   failingHandler = throwError $ err505 { errBody = "I support HTTP/4.0 only." }
--   
err505 :: ServerError -- | A custom formatter for errors produced by parsing combinators like -- ReqBody or Capture. -- -- A TypeRep argument described the concrete combinator that -- raised the error, allowing formatter to customize the message for -- different combinators. -- -- A full Request is also passed so that the formatter can react -- to Accept header, for example. type ErrorFormatter = TypeRep -> Request -> String -> ServerError -- | This formatter does not get neither TypeRep nor error message. type NotFoundErrorFormatter = Request -> ServerError -- | A collection of error formatters for different situations. -- -- If you need to override one of them, use defaultErrorFormatters -- with record update syntax. data ErrorFormatters -- | Format error from parsing the request body. ($sel:bodyParserErrorFormatter:ErrorFormatters) :: ErrorFormatters -> ErrorFormatter -- | Format error from parsing url parts or query parameters. ($sel:urlParseErrorFormatter:ErrorFormatters) :: ErrorFormatters -> ErrorFormatter -- | Format error from parsing request headers. ($sel:headerParseErrorFormatter:ErrorFormatters) :: ErrorFormatters -> ErrorFormatter -- | Format error for not found URLs. ($sel:notFoundErrorFormatter:ErrorFormatters) :: ErrorFormatters -> NotFoundErrorFormatter -- | Context that contains default error formatters. type DefaultErrorFormatters = '[ErrorFormatters] -- | Default formatters will just return HTTP 400 status code with error -- message as response body. defaultErrorFormatters :: ErrorFormatters getAcceptHeader :: Request -> AcceptHeader -- | The WAI application. -- -- Note that, since WAI 3.0, this type is structured in continuation -- passing style to allow for proper safe resource handling. This was -- handled in the past via other means (e.g., ResourceT). As a -- demonstration: -- --
--   app :: Application
--   app req respond = bracket_
--       (putStrLn "Allocating scarce resource")
--       (putStrLn "Cleaning up")
--       (respond $ responseLBS status200 [] "Hello World")
--   
type Application = Request -> Response -> IO ResponseReceived -> IO ResponseReceived -- | A Tagged s b value is a value b with an -- attached phantom type s. This can be used in place of the -- more traditional but less safe idiom of passing in an undefined value -- with the type, because unlike an (s -> b), a -- Tagged s b can't try to use the argument s as -- a real value. -- -- Moreover, you don't have to rely on the compiler to inline away the -- extra argument, because the newtype is "free" -- -- Tagged has kind k -> * -> * if the compiler -- supports PolyKinds, therefore there is an extra k -- showing in the instance haddocks that may cause confusion. newtype () => Tagged (s :: k) b Tagged :: b -> Tagged (s :: k) b [unTagged] :: Tagged (s :: k) b -> b -- | This module defines server-side handlers that lets you serve static -- files. -- -- The most common needs for a web application are covered by -- serveDirectoryWebApp, but the other variants allow you to use -- different StaticSettings and serveDirectoryWith even -- allows you to specify arbitrary StaticSettings to be used for -- serving static files. module Servant.Server.StaticFiles -- | Serve anything under the specified directory as a Raw endpoint. -- --
--   type MyApi = "static" :> Raw
--   
--   server :: Server MyApi
--   server = serveDirectoryWebApp "/var/www"
--   
-- -- would capture any request to /static/<something> and -- look for <something> under /var/www. -- -- It will do its best to guess the MIME type for that file, based on the -- extension, and send an appropriate Content-Type header if -- possible. -- -- If your goal is to serve HTML, CSS and Javascript files that use the -- rest of the API as a webapp backend, you will most likely not want the -- static files to be hidden behind a /static/ prefix. In that -- case, remember to put the serveDirectoryWebApp handler in the -- last position, because servant will try to match the handlers -- in order. -- -- Corresponds to the defaultWebAppSettings StaticSettings -- value. serveDirectoryWebApp :: FilePath -> ServerT Raw m -- | Same as serveDirectoryWebApp, but uses -- webAppSettingsWithLookup. serveDirectoryWebAppLookup :: ETagLookup -> FilePath -> ServerT Raw m -- | Same as serveDirectoryWebApp, but uses -- defaultFileServerSettings. serveDirectoryFileServer :: FilePath -> ServerT Raw m -- | Uses embeddedSettings. serveDirectoryEmbedded :: [(FilePath, ByteString)] -> ServerT Raw m -- | Alias for staticApp. Lets you serve a directory with arbitrary -- StaticSettings. Useful when you want particular settings not -- covered by the four other variants. This is the most flexible method. serveDirectoryWith :: StaticSettings -> ServerT Raw m -- | Same as serveDirectoryFileServer. It used to be the only file -- serving function in servant pre-0.10 and will be kept around for a few -- versions, but is deprecated. -- | Deprecated: Use serveDirectoryFileServer instead serveDirectory :: FilePath -> ServerT Raw m module Servant.Server.Generic -- | A type that specifies that an API record contains a server -- implementation. data AsServerT (m :: Type -> Type) type AsServer = AsServerT Handler -- | Transform a record of routes into a WAI Application. genericServe :: forall routes. (HasServer (ToServantApi routes) '[], GenericServant routes AsServer, Server (ToServantApi routes) ~ ToServant routes AsServer) => routes AsServer -> Application -- | Transform a record of routes with custom monad into a WAI -- Application, by providing a transformation to bring each -- handler back in the Handler monad. genericServeT :: forall (routes :: Type -> Type) (m :: Type -> Type). (GenericServant routes (AsServerT m), GenericServant routes AsApi, HasServer (ToServantApi routes) '[], ServerT (ToServantApi routes) m ~ ToServant routes (AsServerT m)) => (forall a. m a -> Handler a) -> routes (AsServerT m) -> Application -- | Transform a record of routes with custom monad into a WAI -- Application, while using the given Context to serve the -- application (contexts are typically used by auth-related combinators -- in servant, e.g to hold auth checks) and the given transformation to -- map all the handlers back to the Handler monad. genericServeTWithContext :: forall (routes :: Type -> Type) (m :: Type -> Type) (ctx :: [Type]). (GenericServant routes (AsServerT m), GenericServant routes AsApi, HasServer (ToServantApi routes) ctx, HasContextEntry (ctx .++ DefaultErrorFormatters) ErrorFormatters, ServerT (ToServantApi routes) m ~ ToServant routes (AsServerT m)) => (forall a. m a -> Handler a) -> routes (AsServerT m) -> Context ctx -> Application -- | Transform a record of endpoints into a Server. genericServer :: GenericServant routes AsServer => routes AsServer -> ToServant routes AsServer -- | Transform a record of endpoints into a ServerT m. -- -- You can see an example usage of this function in the Servant -- Cookbook. genericServerT :: GenericServant routes (AsServerT m) => routes (AsServerT m) -> ToServant routes (AsServerT m) module Servant -- | Proxy is a type that holds no data, but has a phantom parameter -- of arbitrary type (or even kind). Its use is to provide type -- information, even though there is no value available of that type (or -- it may be too costly to create one). -- -- Historically, Proxy :: Proxy a is a safer -- alternative to the undefined :: a idiom. -- --
--   >>> Proxy :: Proxy (Void, Int -> Int)
--   Proxy
--   
-- -- Proxy can even hold types of higher kinds, -- --
--   >>> Proxy :: Proxy Either
--   Proxy
--   
-- --
--   >>> Proxy :: Proxy Functor
--   Proxy
--   
-- --
--   >>> Proxy :: Proxy complicatedStructure
--   Proxy
--   
data () => Proxy (t :: k) Proxy :: Proxy (t :: k) -- | Is used within a monadic computation to begin exception processing. throwError :: MonadError e m => e -> m a module Servant.Server.Experimental.Auth -- | Specify the type of data returned after we've authenticated a request. -- quite often this is some User datatype. -- -- NOTE: THIS API IS EXPERIMENTAL AND SUBJECT TO CHANGE type family AuthServerData a :: Type -- | Handlers for AuthProtected resources -- -- NOTE: THIS API IS EXPERIMENTAL AND SUBJECT TO CHANGE newtype AuthHandler r usr AuthHandler :: (r -> Handler usr) -> AuthHandler r usr [$sel:unAuthHandler:AuthHandler] :: AuthHandler r usr -> r -> Handler usr -- | NOTE: THIS API IS EXPERIMENTAL AND SUBJECT TO CHANGE mkAuthHandler :: (r -> Handler usr) -> AuthHandler r usr instance GHC.Generics.Generic (Servant.Server.Experimental.Auth.AuthHandler r usr) instance GHC.Base.Functor (Servant.Server.Experimental.Auth.AuthHandler r) instance forall k api (context :: [GHC.Types.Type]) (tag :: k). (Servant.Server.Internal.HasServer api context, Servant.Server.Internal.Context.HasContextEntry context (Servant.Server.Experimental.Auth.AuthHandler Network.Wai.Internal.Request (Servant.Server.Experimental.Auth.AuthServerData (Servant.API.Experimental.Auth.AuthProtect tag)))) => Servant.Server.Internal.HasServer (Servant.API.Experimental.Auth.AuthProtect tag Servant.API.Sub.:> api) context -- | Deprecated: Use Servant.Server.StaticFiles. module Servant.Utils.StaticFiles