scotty-0.22: Haskell web framework inspired by Ruby's Sinatra, using WAI and Warp

Safe Haskell | None
Language | Haskell2010

Web.Scotty.Trans

Contents

- Running `scotty` servers
  - scotty-to-WAI
- Defining Middleware and Routes
  - Route Patterns
  - Accessing the Request and its fields
  - Accessing Path, Form and Query Parameters
    - Files
  - Modifying the Response and Redirecting
  - Setting Response Body
  - Accessing the fields of the Response
  - Exceptions
- Parsing Parameters
- Types
- Monad Transformers

Description

It should be noted that most of the code snippets below depend on the OverloadedStrings language pragma.

The functions in this module allow an arbitrary monad to be embedded in Scotty's monad transformer stack, e.g. for complex endpoint configuration, interacting with databases etc.

Scotty is set up by default for development mode. For production servers, you will likely want to modify `settings` and the `defaultHandler`. See the comments on each of these functions for more information.

Please refer to the `examples` directory and the `spec` test suite for concrete use cases, e.g. constructing responses, exception handling and useful implementation details.

Synopsis

- scottyT :: (Monad m, MonadIO n) => Port -> (m Response -> IO Response) -> ScottyT m () -> n ()
- scottyOptsT :: (Monad m, MonadIO n) => Options -> (m Response -> IO Response) -> ScottyT m () -> n ()
- scottySocketT :: (Monad m, MonadIO n) => Options -> Socket -> (m Response -> IO Response) -> ScottyT m () -> n ()
- data Options = Options {
  - verbose :: Int
  - settings :: Settings
  }
- defaultOptions :: Options
- scottyAppT :: (Monad m, Monad n) => Options -> (m Response -> IO Response) -> ScottyT m () -> n Application
- middleware :: forall (m :: Type -> Type). Middleware -> ScottyT m ()
- get :: forall (m :: Type -> Type). MonadUnliftIO m => RoutePattern -> ActionT m () -> ScottyT m ()
- post :: forall (m :: Type -> Type). MonadUnliftIO m => RoutePattern -> ActionT m () -> ScottyT m ()
- put :: forall (m :: Type -> Type). MonadUnliftIO m => RoutePattern -> ActionT m () -> ScottyT m ()
- delete :: forall (m :: Type -> Type). MonadUnliftIO m => RoutePattern -> ActionT m () -> ScottyT m ()
- patch :: forall (m :: Type -> Type). MonadUnliftIO m => RoutePattern -> ActionT m () -> ScottyT m ()
- options :: forall (m :: Type -> Type). MonadUnliftIO m => RoutePattern -> ActionT m () -> ScottyT m ()
- addroute :: forall (m :: Type -> Type). MonadUnliftIO m => StdMethod -> RoutePattern -> ActionT m () -> ScottyT m ()
- matchAny :: forall (m :: Type -> Type). MonadUnliftIO m => RoutePattern -> ActionT m () -> ScottyT m ()
- notFound :: forall (m :: Type -> Type). MonadUnliftIO m => ActionT m () -> ScottyT m ()
- setMaxRequestBodySize :: forall (m :: Type -> Type). Kilobytes -> ScottyT m ()
- capture :: String -> RoutePattern
- regex :: String -> RoutePattern
- function :: (Request -> Maybe [Param]) -> RoutePattern
- literal :: String -> RoutePattern
- request :: forall (m :: Type -> Type). Monad m => ActionT m Request
- header :: forall (m :: Type -> Type). Monad m => Text -> ActionT m (Maybe Text)
- headers :: forall (m :: Type -> Type). Monad m => ActionT m [(Text, Text)]
- body :: forall (m :: Type -> Type). MonadIO m => ActionT m ByteString
- bodyReader :: forall (m :: Type -> Type). Monad m => ActionT m (IO ByteString)
- jsonData :: forall a (m :: Type -> Type). (FromJSON a, MonadIO m) => ActionT m a
- param :: forall a (m :: Type -> Type). (Parsable a, MonadIO m) => Text -> ActionT m a
- params :: forall (m :: Type -> Type). Monad m => ActionT m [Param]
- pathParam :: forall a (m :: Type -> Type). (Parsable a, MonadIO m) => Text -> ActionT m a
- captureParam :: forall a (m :: Type -> Type). (Parsable a, MonadIO m) => Text -> ActionT m a
- formParam :: forall (m :: Type -> Type) b. (MonadUnliftIO m, Parsable b) => Text -> ActionT m b
- queryParam :: forall a (m :: Type -> Type). (Parsable a, MonadIO m) => Text -> ActionT m a
- pathParamMaybe :: forall a (m :: Type -> Type). (Parsable a, Monad m) => Text -> ActionT m (Maybe a)
- captureParamMaybe :: forall a (m :: Type -> Type). (Parsable a, Monad m) => Text -> ActionT m (Maybe a)
- formParamMaybe :: forall (m :: Type -> Type) a. (MonadUnliftIO m, Parsable a) => Text -> ActionT m (Maybe a)
- queryParamMaybe :: forall a (m :: Type -> Type). (Parsable a, Monad m) => Text -> ActionT m (Maybe a)
- pathParams :: forall (m :: Type -> Type). Monad m => ActionT m [Param]
- captureParams :: forall (m :: Type -> Type). Monad m => ActionT m [Param]
- formParams :: forall (m :: Type -> Type). MonadUnliftIO m => ActionT m [Param]
- queryParams :: forall (m :: Type -> Type). Monad m => ActionT m [Param]
- files :: forall (m :: Type -> Type). MonadUnliftIO m => ActionT m [File ByteString]
- filesOpts :: forall (m :: Type -> Type) a. MonadUnliftIO m => ParseRequestBodyOptions -> ([Param] -> [File FilePath] -> ActionT m a) -> ActionT m a
- data ParseRequestBodyOptions
- status :: forall (m :: Type -> Type). MonadIO m => Status -> ActionT m ()
- addHeader :: forall (m :: Type -> Type). MonadIO m => Text -> Text -> ActionT m ()
- setHeader :: forall (m :: Type -> Type). MonadIO m => Text -> Text -> ActionT m ()
- redirect :: forall (m :: Type -> Type) a. Monad m => Text -> ActionT m a
- text :: forall (m :: Type -> Type). MonadIO m => Text -> ActionT m ()
- html :: forall (m :: Type -> Type). MonadIO m => Text -> ActionT m ()
- file :: forall (m :: Type -> Type). MonadIO m => FilePath -> ActionT m ()
- json :: forall a (m :: Type -> Type). (ToJSON a, MonadIO m) => a -> ActionT m ()
- stream :: forall (m :: Type -> Type). MonadIO m => StreamingBody -> ActionT m ()
- raw :: forall (m :: Type -> Type). MonadIO m => ByteString -> ActionT m ()
- nested :: forall (m :: Type -> Type). MonadIO m => Application -> ActionT m ()
- getResponseHeaders :: forall (m :: Type -> Type). MonadIO m => ActionT m ResponseHeaders
- getResponseStatus :: forall (m :: Type -> Type). MonadIO m => ActionT m Status
- getResponseContent :: forall (m :: Type -> Type). MonadIO m => ActionT m Content
- raise :: forall (m :: Type -> Type) a. MonadIO m => Text -> ActionT m a
- raiseStatus :: forall (m :: Type -> Type) a. Monad m => Status -> Text -> ActionT m a
- throw :: forall (m :: Type -> Type) e a. (MonadIO m, Exception e) => e -> ActionT m a
- rescue :: forall (m :: Type -> Type) e a. (MonadUnliftIO m, Exception e) => ActionT m a -> (e -> ActionT m a) -> ActionT m a
- next :: forall (m :: Type -> Type) a. Monad m => ActionT m a
- finish :: forall (m :: Type -> Type) a. Monad m => ActionT m a
- defaultHandler :: forall (m :: Type -> Type). Monad m => ErrorHandler m -> ScottyT m ()
- liftAndCatchIO :: forall (m :: Type -> Type) a. MonadIO m => IO a -> ActionT m a
- liftIO :: MonadIO m => IO a -> m a
- catch :: (MonadUnliftIO m, Exception e) => m a -> (e -> m a) -> m a
- data StatusError = StatusError Status Text
- data ScottyException
  - = RequestTooLarge
  - | MalformedJSON ByteString Text
  - | FailedToParseJSON ByteString Text
  - | PathParameterNotFound Text
  - | QueryParameterNotFound Text
  - | FormFieldNotFound Text
  - | FailedToParseParameter Text Text Text
  - | WarpRequestException InvalidRequest
  - | WaiRequestParseException RequestParseException
  - | ResourceTException InvalidAccess
- type Param = (Text, Text)
- class Parsable a where
  - parseParam :: Text -> Either Text a
  - parseParamList :: Text -> Either Text [a]
- readEither :: Read a => Text -> Either Text a
- data RoutePattern
- type File t = (Text, FileInfo t)
- data Content
  - = ContentBuilder Builder
  - | ContentFile FilePath
  - | ContentStream StreamingBody
  - | ContentResponse Response
- type Kilobytes = Int
- type ErrorHandler (m :: Type -> Type) = Handler (ActionT m) ()
- data Handler (m :: Type -> Type) a = Exception e => Handler (e -> m a)
- data ScottyT (m :: Type -> Type) a
- data ActionT (m :: Type -> Type) a
- data ScottyState (m :: Type -> Type)
- defaultScottyState :: forall (m :: Type -> Type). ScottyState m

# Running `scotty` servers

scottyT Source #

Arguments

:: (Monad m, MonadIO n) |
=> Port |
-> (m Response -> IO Response) | Run monad `m` into `IO`, called at each action.
-> ScottyT m () |
-> n () |

Run a scotty application using the warp server. NB: scotty p === scottyT p id

scottyOptsT Source #

Arguments

:: (Monad m, MonadIO n) |
=> Options |
-> (m Response -> IO Response) | Run monad `m` into `IO`, called at each action.
-> ScottyT m () |
-> n () |

Run a scotty application using the warp server, passing extra options. NB: scottyOpts opts === scottyOptsT opts id

scottySocketT :: (Monad m, MonadIO n) => Options -> Socket -> (m Response -> IO Response) -> ScottyT m () -> n () Source #

Run a scotty application using the warp server, passing extra options, and listening on the provided socket. NB: scottySocket opts sock === scottySocketT opts sock id

data Options Source #

Constructors

Options |

Fields

- verbose :: Int

  0 = silent, 1(def) = startup banner

- settings :: Settings

  Warp `Settings` Note: to work around an issue in warp, the default FD cache duration is set to 0 so changes to static files are always picked up. This likely has performance implications, so you may want to modify this for production servers using `setFdCacheDuration`.

#### Instances

Instances details

Default Options Source # |
Instance details Defined in Web.Scotty.Internal.Types Methods def :: Options #

defaultOptions :: Options Source #

## scotty-to-WAI

scottyAppT Source #

Arguments

:: (Monad m, Monad n) |
=> Options |
-> (m Response -> IO Response) | Run monad `m` into `IO`, called at each action.
-> ScottyT m () |
-> n Application |

Turn a scotty application into a WAI `Application`, which can be run with any WAI handler. NB: scottyApp === scottyAppT id

# Defining Middleware and Routes

`Middleware` and routes are run in the order in which they are defined. All middleware is run first, followed by the first route that matches. If no route matches, a 404 response is given.

middleware :: forall (m :: Type -> Type). Middleware -> ScottyT m () Source #

Use given middleware. Middleware is nested such that the first declared is the outermost middleware (it has first dibs on the request and last action on the response). Every middleware is run on each request.

get :: forall (m :: Type -> Type). MonadUnliftIO m => RoutePattern -> ActionT m () -> ScottyT m () Source #

get = `addroute` `GET`

post :: forall (m :: Type -> Type). MonadUnliftIO m => RoutePattern -> ActionT m () -> ScottyT m () Source #

post = `addroute` `POST`

put :: forall (m :: Type -> Type). MonadUnliftIO m => RoutePattern -> ActionT m () -> ScottyT m () Source #

put = `addroute` `PUT`

delete :: forall (m :: Type -> Type). MonadUnliftIO m => RoutePattern -> ActionT m () -> ScottyT m () Source #

delete = `addroute` `DELETE`

patch :: forall (m :: Type -> Type). MonadUnliftIO m => RoutePattern -> ActionT m () -> ScottyT m () Source #

patch = `addroute` `PATCH`

options :: forall (m :: Type -> Type). MonadUnliftIO m => RoutePattern -> ActionT m () -> ScottyT m () Source #

options = `addroute` `OPTIONS`

addroute :: forall (m :: Type -> Type). MonadUnliftIO m => StdMethod -> RoutePattern -> ActionT m () -> ScottyT m () Source #

Define a route with a `StdMethod`, a route pattern representing the path spec, and an `Action` which may modify the response.

    get "/" $ text "beam me up!"

The path spec can include values starting with a colon, which are interpreted as captures. These are parameters that can be looked up with `pathParam`.

    >>> :{
    let server = S.get "/foo/:bar" (S.pathParam "bar" >>= S.text)
     in do
          withScotty server $ curl "http://localhost:3000/foo/something"
    :}
    "something"

matchAny :: forall (m :: Type -> Type). MonadUnliftIO m => RoutePattern -> ActionT m () -> ScottyT m () Source #

Add a route that matches regardless of the HTTP verb.

notFound :: forall (m :: Type -> Type). MonadUnliftIO m => ActionT m () -> ScottyT m () Source #

Specify an action to take if nothing else is found. Note: this _always_ matches, so should generally be the last route specified.

setMaxRequestBodySize Source #

Arguments

:: forall (m :: Type -> Type). Kilobytes | Request size limit
-> ScottyT m () |

Set global size limit for the request body. Requests with body size exceeding the limit will not be processed and an HTTP response 413 will be returned to the client. Size limit needs to be greater than 0, otherwise the application will terminate on start.

## Route Patterns

capture :: String -> RoutePattern Source #

Standard Sinatra-style route. Named captures are prepended with colons. This is the default route type generated by OverloadedString routes. i.e.

    get (capture "/foo/:bar") $ ...

and

    {-# LANGUAGE OverloadedStrings #-}
    ...
    get "/foo/:bar" $ ...

are equivalent.

regex :: String -> RoutePattern Source #

Match requests using a regular expression. Named captures are not yet supported.

    >>> :{
    let server = S.get (S.regex "^/f(.*)r$") $ do
                    cap <- S.pathParam "1"
                    S.text cap
     in do
          withScotty server $ curl "http://localhost:3000/foo/bar"
    :}
    "oo/ba"

function :: (Request -> Maybe [Param]) -> RoutePattern Source #

Build a route based on a function which can match using the entire `Request` object. `Nothing` indicates the route does not match. A `Just` value indicates a successful match, optionally returning a list of key-value pairs accessible by `param`.

    >>> :{
    let server = S.get (function $ \req -> Just [("version", T.pack $ show $ W.httpVersion req)]) $ do
                    v <- S.pathParam "version"
                    S.text v
     in do
          withScotty server $ curl "http://localhost:3000/"
    :}
    "HTTP/1.1"

literal :: String -> RoutePattern Source #

Build a route that requires the requested path match exactly, without captures.

## Accessing the Request and its fields

request :: forall (m :: Type -> Type). Monad m => ActionT m Request Source #

Get the `Request` object.

header :: forall (m :: Type -> Type). Monad m => Text -> ActionT m (Maybe Text) Source #

Get a request header. Header name is case-insensitive.

headers :: forall (m :: Type -> Type). Monad m => ActionT m [(Text, Text)] Source #

Get all the request headers. Header names are case-insensitive.

body :: forall (m :: Type -> Type). MonadIO m => ActionT m ByteString Source #

Get the request body.

NB This loads the whole request body in memory at once.

bodyReader :: forall (m :: Type -> Type). Monad m => ActionT m (IO ByteString) Source #

Get an IO action that reads body chunks

- This is incompatible with `body` since `body` consumes all chunks.

jsonData :: forall a (m :: Type -> Type). (FromJSON a, MonadIO m) => ActionT m a Source #

Parse the request body as a JSON object and return it.

If the JSON object is malformed, this sets the status to 400 Bad Request, and throws an exception.

If the JSON fails to parse, this sets the status to 422 Unprocessable Entity.

These status codes are as per https://www.restapitutorial.com/httpstatuscodes.html.

NB : Internally this uses `body`.

## Accessing Path, Form and Query Parameters

param :: forall a (m :: Type -> Type). (Parsable a, MonadIO m) => Text -> ActionT m a Source #

Deprecated: (#204) Not a good idea to treat all parameters identically. Use captureParam, formParam and queryParam instead.

Get a parameter. First looks in captures, then form data, then query parameters.

- Raises an exception which can be caught by `catch` if parameter is not found.
- If parameter is found, but `parseParam` fails to parse to the correct type, `next` is called. This means captures are somewhat typed, in that a route won't match if a correctly typed capture cannot be parsed.

params :: forall (m :: Type -> Type). Monad m => ActionT m [Param] Source #

Deprecated: (#204) Not a good idea to treat all parameters identically. Use pathParams, formParams and queryParams instead.

Get all parameters from path, form and query (in that order).

pathParam :: forall a (m :: Type -> Type). (Parsable a, MonadIO m) => Text -> ActionT m a Source #

Look up a path parameter.

- Raises an exception which can be caught by `catch` if parameter is not found. If the exception is not caught, scotty will return a HTTP error code 500 ("Internal Server Error") to the client.
- If the parameter is found, but `parseParam` fails to parse to the correct type, `next` is called.

Since: 0.20

captureParam :: forall a (m :: Type -> Type). (Parsable a, MonadIO m) => Text -> ActionT m a Source #

Synonym for `pathParam`

formParam :: forall (m :: Type -> Type) b. (MonadUnliftIO m, Parsable b) => Text -> ActionT m b Source #

Look up a form parameter.

- Raises an exception which can be caught by `catch` if parameter is not found. If the exception is not caught, scotty will return a HTTP error code 400 ("Bad Request") to the client.
- This function raises a code 400 also if the parameter is found, but `parseParam` fails to parse to the correct type.

Since: 0.20

queryParam :: forall a (m :: Type -> Type). (Parsable a, MonadIO m) => Text -> ActionT m a Source #

Look up a query parameter.

- Raises an exception which can be caught by `catch` if parameter is not found. If the exception is not caught, scotty will return a HTTP error code 400 ("Bad Request") to the client.
- This function raises a code 400 also if the parameter is found, but `parseParam` fails to parse to the correct type.

Since: 0.20

pathParamMaybe :: forall a (m :: Type -> Type). (Parsable a, Monad m) => Text -> ActionT m (Maybe a) Source #

Look up a path parameter. Returns `Nothing` if the parameter is not found or cannot be parsed at the right type.

NB : Doesn't throw exceptions. In particular, route pattern matching will not continue, so developers must `raiseStatus` or `throw` to signal something went wrong.

Since: 0.21

captureParamMaybe :: forall a (m :: Type -> Type). (Parsable a, Monad m) => Text -> ActionT m (Maybe a) Source #

Look up a capture parameter. Returns `Nothing` if the parameter is not found or cannot be parsed at the right type.

NB : Doesn't throw exceptions. In particular, route pattern matching will not continue, so developers must `raiseStatus` or `throw` to signal something went wrong.

Since: 0.21

formParamMaybe :: forall (m :: Type -> Type) a. (MonadUnliftIO m, Parsable a) => Text -> ActionT m (Maybe a) Source #

Look up a form parameter. Returns `Nothing` if the parameter is not found or cannot be parsed at the right type.

NB : Doesn't throw exceptions, so developers must `raiseStatus` or `throw` to signal something went wrong.

Since: 0.21

queryParamMaybe :: forall a (m :: Type -> Type). (Parsable a, Monad m) => Text -> ActionT m (Maybe a) Source #

Look up a query parameter. Returns `Nothing` if the parameter is not found or cannot be parsed at the right type.

NB : Doesn't throw exceptions, so developers must `raiseStatus` or `throw` to signal something went wrong.

Since: 0.21

pathParams :: forall (m :: Type -> Type). Monad m => ActionT m [Param] Source #

Get path parameters

captureParams :: forall (m :: Type -> Type). Monad m => ActionT m [Param] Source #

Get path parameters

formParams :: forall (m :: Type -> Type). MonadUnliftIO m => ActionT m [Param] Source #

Get form parameters

queryParams :: forall (m :: Type -> Type). Monad m => ActionT m [Param] Source #

Get query parameters

### Files

files :: forall (m :: Type -> Type). MonadUnliftIO m => ActionT m [File ByteString] Source #

Get list of uploaded files.

NB: Loads all file contents in memory with options `defaultParseRequestBodyOptions`

filesOpts Source #

Arguments

:: forall (m :: Type -> Type) a. MonadUnliftIO m |
=> ParseRequestBodyOptions |
-> ([Param] -> [File FilePath] -> ActionT m a) | temp files validation, storage etc
-> ActionT m a |

Get list of uploaded temp files and form parameters decoded from multipart payloads.

NB the temp files are deleted when the continuation exits.

data ParseRequestBodyOptions Source #

A data structure that describes the behavior of the parseRequestBodyEx function.

Since: wai-extra-3.0.16.0

## Modifying the Response and Redirecting

status :: forall (m :: Type -> Type). MonadIO m => Status -> ActionT m () Source #

Set the HTTP response status.

addHeader :: forall (m :: Type -> Type). MonadIO m => Text -> Text -> ActionT m () Source #

Add to the response headers. Header names are case-insensitive.

setHeader :: forall (m :: Type -> Type). MonadIO m => Text -> Text -> ActionT m () Source #

Set one of the response headers. Will override any previously set value for that header. Header names are case-insensitive.

redirect :: forall (m :: Type -> Type) a. Monad m => Text -> ActionT m a Source #

Redirect to given URL. Like throwing an uncatchable exception. Any code after the call to redirect will not be run.

    redirect "http://www.google.com"

OR

    redirect "/foo/bar"

## Setting Response Body

Note: only one of these should be present in any given route definition, as they completely replace the current `Response` body.

text :: forall (m :: Type -> Type). MonadIO m => Text -> ActionT m () Source #

html :: forall (m :: Type -> Type). MonadIO m => Text -> ActionT m () Source #

file :: forall (m :: Type -> Type). MonadIO m => FilePath -> ActionT m () Source #

Send a file as the response. Doesn't set the "Content-Type" header, so you probably want to do that on your own with `setHeader`. Setting a status code will have no effect because Warp will overwrite that to 200 (see `sendResponse`).

json :: forall a (m :: Type -> Type). (ToJSON a, MonadIO m) => a -> ActionT m () Source #

Set the body of the response to the JSON encoding of the given value. Also sets "Content-Type" header to "application/json; charset=utf-8" if it has not already been set.

stream :: forall (m :: Type -> Type). MonadIO m => StreamingBody -> ActionT m () Source #

Set the body of the response to a Source. Doesn't set the "Content-Type" header, so you probably want to do that on your own with `setHeader`.

raw :: forall (m :: Type -> Type). MonadIO m => ByteString -> ActionT m () Source #

Set the body of the response to the given `ByteString` value. Doesn't set the "Content-Type" header, so you probably want to do that on your own with `setHeader`.

nested :: forall (m :: Type -> Type). MonadIO m => Application -> ActionT m () Source #

Nest a whole WAI application inside a Scotty handler. See Web.Scotty for further documentation

## Accessing the fields of the Response

getResponseHeaders :: forall (m :: Type -> Type). MonadIO m => ActionT m ResponseHeaders Source #

Access the HTTP headers of the Response

SINCE 0.21

getResponseStatus :: forall (m :: Type -> Type). MonadIO m => ActionT m Status Source #

Access the HTTP `Status` of the Response

SINCE 0.21

getResponseContent :: forall (m :: Type -> Type). MonadIO m => ActionT m Content Source #

Access the content of the Response

SINCE 0.21

## Exceptions

raise Source #

Arguments

:: forall (m :: Type -> Type) a. MonadIO m |
=> Text | Error text
-> ActionT m a |

Deprecated: Throw an exception instead

Throw a "500 Server Error" `StatusError`, which can be caught with `rescue`.

Uncaught exceptions turn into HTTP 500 responses.

raiseStatus :: forall (m :: Type -> Type) a. Monad m => Status -> Text -> ActionT m a Source #

Deprecated: Use status, text, and finish instead

Throw a `StatusError` exception that has an associated HTTP error code and can be caught with `rescue`.

Uncaught exceptions turn into HTTP responses corresponding to the given status.

throw :: forall (m :: Type -> Type) e a. (MonadIO m, Exception e) => e -> ActionT m a Source #

Throw an exception which can be caught within the scope of the current Action with `catch`.

If the exception is not caught locally, another option is to implement a global `Handler` (with `defaultHandler`) that defines its interpretation and a translation to HTTP error codes.

Uncaught exceptions turn into HTTP 500 responses.

rescue :: forall (m :: Type -> Type) e a. (MonadUnliftIO m, Exception e) => ActionT m a -> (e -> ActionT m a) -> ActionT m a Source #

Deprecated: Use catch instead

Catch an exception e.g. a `StatusError` or a user-defined exception.

    raise JustKidding `catch` (\msg -> text msg)

next :: forall (m :: Type -> Type) a. Monad m => ActionT m a Source #

Abort execution of this action and continue pattern matching routes. Like an exception, any code after `next` is not executed.

NB : Internally, this is implemented with an exception that can only be caught by the library, but not by the user.

As an example, these two routes overlap. The only way the second one will ever run is if the first one calls `next`.

    get "/foo/:bar" $ do
      w :: Text <- pathParam "bar"
      unless (w == "special") next
      text "You made a request to /foo/special"

    get "/foo/:baz" $ do
      w <- pathParam "baz"
      text $ "You made a request to: " <> w

finish :: forall (m :: Type -> Type) a. Monad m => ActionT m a Source #

Finish the execution of the current action. Like throwing an uncatchable exception. Any code after the call to finish will not be run.

Since: 0.10.3

defaultHandler :: forall (m :: Type -> Type). Monad m => ErrorHandler m -> ScottyT m () Source #

Global handler for user-defined exceptions.

liftAndCatchIO :: forall (m :: Type -> Type) a. MonadIO m => IO a -> ActionT m a Source #

Deprecated: Use liftIO instead

Catch any synchronous IO exceptions

liftIO :: MonadIO m => IO a -> m a Source #

Lift a computation from the `IO` monad. This allows us to run IO computations in any monadic stack, so long as it supports these kinds of operations (i.e. `IO` is the base monad for the stack).

### Example

Expand

    import Control.Monad.Trans.State -- from the "transformers" library

    printState :: Show s => StateT s IO ()
    printState = do
      state <- get
      liftIO $ print state

Had we omitted ``liftIO``, we would have ended up with this error:

    • Couldn't match type ‘IO’ with ‘StateT s IO’
     Expected type: StateT s IO ()
       Actual type: IO ()

The important part here is the mismatch between `StateT s IO ()` and ``IO` ()`.

Luckily, we know of a function that takes an ``IO` a` and returns an `(m a)`: ``liftIO``, enabling us to run the program and see the expected results:

    > evalStateT printState "hello"
    "hello"

    > evalStateT printState 3
    3

catch Source #

Arguments

:: (MonadUnliftIO m, Exception e) |
=> m a | action
-> (e -> m a) | handler
-> m a |

Catch a synchronous (but not asynchronous) exception and recover from it.

This is parameterized on the exception type. To catch all synchronous exceptions, use `catchAny`.

Since: unliftio-0.1.0.0

data StatusError Source #

Deprecated: If it is supposed to be caught, a proper exception type should be defined

E.g. when a parameter is not found in a query string (400 Bad Request) or when parsing a JSON body fails (422 Unprocessable Entity)

Constructors

StatusError Status Text | Deprecated: If it is supposed to be caught, a proper exception type should be defined

#### Instances

Instances details

Exception StatusError Source # |
Instance details Defined in Web.Scotty.Internal.Types Methods toException :: StatusError -> SomeException Source # fromException :: SomeException -> Maybe StatusError Source # displayException :: StatusError -> String Source # backtraceDesired :: StatusError -> Bool Source #
Show StatusError Source # |
Instance details Defined in Web.Scotty.Internal.Types Methods showsPrec :: Int -> StatusError -> ShowS Source # show :: StatusError -> String Source # showList :: [StatusError] -> ShowS Source #
MonadUnliftIO m => MonadError StatusError (ActionT m) Source # | Models the invariant that only `StatusError`s can be thrown and caught.
Instance details Defined in Web.Scotty.Internal.Types Methods throwError :: StatusError -> ActionT m a Source # catchError :: ActionT m a -> (StatusError -> ActionT m a) -> ActionT m a Source #

data ScottyException Source #

Thrown e.g. when a request is too large

Constructors

RequestTooLarge |
MalformedJSON ByteString Text |
FailedToParseJSON ByteString Text |
PathParameterNotFound Text |
QueryParameterNotFound Text |
FormFieldNotFound Text |
FailedToParseParameter Text Text Text |
WarpRequestException InvalidRequest |
WaiRequestParseException RequestParseException |
ResourceTException InvalidAccess |

#### Instances

Instances details

Exception ScottyException Source # |
Instance details Defined in Web.Scotty.Internal.Types Methods toException :: ScottyException -> SomeException Source # fromException :: SomeException -> Maybe ScottyException Source # displayException :: ScottyException -> String Source # backtraceDesired :: ScottyException -> Bool Source #
Show ScottyException Source # |
Instance details Defined in Web.Scotty.Internal.Types Methods showsPrec :: Int -> ScottyException -> ShowS Source # show :: ScottyException -> String Source # showList :: [ScottyException] -> ShowS Source #

# Parsing Parameters

type Param = (Text, Text) Source #

class Parsable a where Source #

Minimum implemention: `parseParam`

Minimal complete definition

parseParam

Methods

parseParam :: Text -> Either Text a Source #

Take a `Text` value and parse it as `a`, or fail with a message.

parseParamList :: Text -> Either Text [a] Source #

Default implementation parses comma-delimited lists.

    parseParamList t = mapM parseParam (T.split (== ',') t)

#### Instances

Instances details

Parsable ByteString Source # |
Instance details Defined in Web.Scotty.Action Methods parseParam :: Text -> Either Text ByteString Source # parseParamList :: Text -> Either Text [ByteString] Source #
Parsable ByteString Source # |
Instance details Defined in Web.Scotty.Action Methods parseParam :: Text -> Either Text ByteString Source # parseParamList :: Text -> Either Text [ByteString] Source #
Parsable Int16 Source # |
Instance details Defined in Web.Scotty.Action Methods parseParam :: Text -> Either Text Int16 Source # parseParamList :: Text -> Either Text [Int16] Source #
Parsable Int32 Source # |
Instance details Defined in Web.Scotty.Action Methods parseParam :: Text -> Either Text Int32 Source # parseParamList :: Text -> Either Text [Int32] Source #
Parsable Int64 Source # |
Instance details Defined in Web.Scotty.Action Methods parseParam :: Text -> Either Text Int64 Source # parseParamList :: Text -> Either Text [Int64] Source #
Parsable Int8 Source # |
Instance details Defined in Web.Scotty.Action Methods parseParam :: Text -> Either Text Int8 Source # parseParamList :: Text -> Either Text [Int8] Source #
Parsable Word16 Source # |
Instance details Defined in Web.Scotty.Action Methods parseParam :: Text -> Either Text Word16 Source # parseParamList :: Text -> Either Text [Word16] Source #
Parsable Word32 Source # |
Instance details Defined in Web.Scotty.Action Methods parseParam :: Text -> Either Text Word32 Source # parseParamList :: Text -> Either Text [Word32] Source #
Parsable Word64 Source # |
Instance details Defined in Web.Scotty.Action Methods parseParam :: Text -> Either Text Word64 Source # parseParamList :: Text -> Either Text [Word64] Source #
Parsable Word8 Source # |
Instance details Defined in Web.Scotty.Action Methods parseParam :: Text -> Either Text Word8 Source # parseParamList :: Text -> Either Text [Word8] Source #
Parsable Text Source # |
Instance details Defined in Web.Scotty.Action Methods parseParam :: Text -> Either Text Text Source # parseParamList :: Text -> Either Text [Text] Source #
Parsable Text Source # |
Instance details Defined in Web.Scotty.Action Methods parseParam :: Text -> Either Text Text Source # parseParamList :: Text -> Either Text [Text] Source #
Parsable UTCTime Source # | parse a UTCTime timestamp formatted as a ISO 8601 timestamp: `yyyy-mm-ddThh:mm:ssZ` , where the seconds can have a decimal part with up to 12 digits and no trailing zeros.
Instance details Defined in Web.Scotty.Action Methods parseParam :: Text -> Either Text UTCTime Source # parseParamList :: Text -> Either Text [UTCTime] Source #
Parsable Integer Source # |
Instance details Defined in Web.Scotty.Action Methods parseParam :: Text -> Either Text Integer Source # parseParamList :: Text -> Either Text [Integer] Source #
Parsable Natural Source # |
Instance details Defined in Web.Scotty.Action Methods parseParam :: Text -> Either Text Natural Source # parseParamList :: Text -> Either Text [Natural] Source #
Parsable () Source # | Checks if parameter is present and is null-valued, not a literal `()`. If the URI requested is: '/foo?bar=()&baz' then `baz` will parse as (), where `bar` will not.
Instance details Defined in Web.Scotty.Action Methods parseParam :: Text -> Either Text () Source # parseParamList :: Text -> Either Text [()] Source #
Parsable Bool Source # |
Instance details Defined in Web.Scotty.Action Methods parseParam :: Text -> Either Text Bool Source # parseParamList :: Text -> Either Text [Bool] Source #
Parsable Char Source # | Overrides default `parseParamList` to parse String.
Instance details Defined in Web.Scotty.Action Methods parseParam :: Text -> Either Text Char Source # parseParamList :: Text -> Either Text [Char] Source #
Parsable Double Source # |
Instance details Defined in Web.Scotty.Action Methods parseParam :: Text -> Either Text Double Source # parseParamList :: Text -> Either Text [Double] Source #
Parsable Float Source # |
Instance details Defined in Web.Scotty.Action Methods parseParam :: Text -> Either Text Float Source # parseParamList :: Text -> Either Text [Float] Source #
Parsable Int Source # |
Instance details Defined in Web.Scotty.Action Methods parseParam :: Text -> Either Text Int Source # parseParamList :: Text -> Either Text [Int] Source #
Parsable Word Source # |
Instance details Defined in Web.Scotty.Action Methods parseParam :: Text -> Either Text Word Source # parseParamList :: Text -> Either Text [Word] Source #
Parsable a => Parsable [a] Source # |
Instance details Defined in Web.Scotty.Action Methods parseParam :: Text -> Either Text [a] Source # parseParamList :: Text -> Either Text [[a]] Source #

readEither :: Read a => Text -> Either Text a Source #

Useful for creating `Parsable` instances for things that already implement `Read`. Ex:

    instance Parsable Int where parseParam = readEither

# Types

data RoutePattern Source #

#### Instances

Instances details

IsString RoutePattern Source # |
Instance details Defined in Web.Scotty.Internal.Types Methods fromString :: String -> RoutePattern Source #

type File t = (Text, FileInfo t) Source #

Type parameter `t` is the file content. Could be `()` when not needed or a `FilePath` for temp files instead.

data Content Source #

Constructors

ContentBuilder Builder |
ContentFile FilePath |
ContentStream StreamingBody |
ContentResponse Response |

type Kilobytes = Int Source #

type ErrorHandler (m :: Type -> Type) = Handler (ActionT m) () Source #

Specializes a `Handler` to the `ActionT` monad

data Handler (m :: Type -> Type) a Source #

Generalized version of `Handler`

Constructors

Exception e => Handler (e -> m a) |

#### Instances

Instances details

Monad m => Functor (Handler m) |
Instance details Defined in Control.Monad.Catch Methods fmap :: (a -> b) -> Handler m a -> Handler m b Source # (<$) :: a -> Handler m b -> Handler m a Source #

# Monad Transformers

data ScottyT (m :: Type -> Type) a Source #

#### Instances

Instances details

Applicative (ScottyT m) Source # |
Instance details Defined in Web.Scotty.Internal.Types Methods pure :: a -> ScottyT m a Source # (<*>) :: ScottyT m (a -> b) -> ScottyT m a -> ScottyT m b Source # liftA2 :: (a -> b -> c) -> ScottyT m a -> ScottyT m b -> ScottyT m c Source # (*>) :: ScottyT m a -> ScottyT m b -> ScottyT m b Source # (<*) :: ScottyT m a -> ScottyT m b -> ScottyT m a Source #
Functor (ScottyT m) Source # |
Instance details Defined in Web.Scotty.Internal.Types Methods fmap :: (a -> b) -> ScottyT m a -> ScottyT m b Source # (<$) :: a -> ScottyT m b -> ScottyT m a Source #
Monad (ScottyT m) Source # |
Instance details Defined in Web.Scotty.Internal.Types Methods (>>=) :: ScottyT m a -> (a -> ScottyT m b) -> ScottyT m b Source # (>>) :: ScottyT m a -> ScottyT m b -> ScottyT m b Source # return :: a -> ScottyT m a Source #
Monoid a => Monoid (ScottyT m a) Source # |
Instance details Defined in Web.Scotty.Internal.Types Methods mempty :: ScottyT m a Source # mappend :: ScottyT m a -> ScottyT m a -> ScottyT m a Source # mconcat :: [ScottyT m a] -> ScottyT m a Source #
Semigroup a => Semigroup (ScottyT m a) Source # |
Instance details Defined in Web.Scotty.Internal.Types Methods (<>) :: ScottyT m a -> ScottyT m a -> ScottyT m a Source # sconcat :: NonEmpty (ScottyT m a) -> ScottyT m a Source # stimes :: Integral b => b -> ScottyT m a -> ScottyT m a Source #

data ActionT (m :: Type -> Type) a Source #

#### Instances

Instances details

MonadTransControl ActionT Source # |

Instance details

Defined in Web.Scotty.Internal.Types

Associated Types

type StT ActionT a |
Instance details Defined in Web.Scotty.Internal.Types type StT ActionT a = StT (ReaderT ActionEnv) a

Methods

liftWith :: Monad m => (Run ActionT -> m a) -> ActionT m a Source #

restoreT :: Monad m => m (StT ActionT a) -> ActionT m a Source #

MonadTrans ActionT Source # |
Instance details Defined in Web.Scotty.Internal.Types Methods lift :: Monad m => m a -> ActionT m a Source #
MonadBaseControl b m => MonadBaseControl b (ActionT m) Source # |
Instance details Defined in Web.Scotty.Internal.Types Methods liftBaseWith :: (RunInBase (ActionT m) b -> b a) -> ActionT m a Source # restoreM :: StM (ActionT m) a -> ActionT m a Source #
MonadUnliftIO m => MonadError StatusError (ActionT m) Source # | Models the invariant that only `StatusError`s can be thrown and caught.
Instance details Defined in Web.Scotty.Internal.Types Methods throwError :: StatusError -> ActionT m a Source # catchError :: ActionT m a -> (StatusError -> ActionT m a) -> ActionT m a Source #
MonadReader r m => MonadReader r (ActionT m) Source # |
Instance details Defined in Web.Scotty.Internal.Types Methods ask :: ActionT m r Source # local :: (r -> r) -> ActionT m a -> ActionT m a Source # reader :: (r -> a) -> ActionT m a Source #
MonadBase b m => MonadBase b (ActionT m) Source # |
Instance details Defined in Web.Scotty.Internal.Types Methods liftBase :: b α -> ActionT m α Source #
MonadIO m => MonadIO (ActionT m) Source # |
Instance details Defined in Web.Scotty.Internal.Types Methods liftIO :: IO a -> ActionT m a Source #
MonadCatch m => MonadCatch (ActionT m) Source # |
Instance details Defined in Web.Scotty.Internal.Types Methods catch :: (HasCallStack, Exception e) => ActionT m a -> (e -> ActionT m a) -> ActionT m a Source #
MonadThrow m => MonadThrow (ActionT m) Source # |
Instance details Defined in Web.Scotty.Internal.Types Methods throwM :: (HasCallStack, Exception e) => e -> ActionT m a Source #
MonadUnliftIO m => Alternative (ActionT m) Source # | `empty` throws `ActionError` `AENext`, whereas `(<|>)` catches any `ActionError`s or `StatusError`s in the first action and proceeds to the second one.
Instance details Defined in Web.Scotty.Internal.Types Methods empty :: ActionT m a Source # (<|>) :: ActionT m a -> ActionT m a -> ActionT m a Source # some :: ActionT m a -> ActionT m [a] Source # many :: ActionT m a -> ActionT m [a] Source #
Applicative m => Applicative (ActionT m) Source # |
Instance details Defined in Web.Scotty.Internal.Types Methods pure :: a -> ActionT m a Source # (<*>) :: ActionT m (a -> b) -> ActionT m a -> ActionT m b Source # liftA2 :: (a -> b -> c) -> ActionT m a -> ActionT m b -> ActionT m c Source # (*>) :: ActionT m a -> ActionT m b -> ActionT m b Source # (<*) :: ActionT m a -> ActionT m b -> ActionT m a Source #
Functor m => Functor (ActionT m) Source # |
Instance details Defined in Web.Scotty.Internal.Types Methods fmap :: (a -> b) -> ActionT m a -> ActionT m b Source # (<$) :: a -> ActionT m b -> ActionT m a Source #
Monad m => Monad (ActionT m) Source # |
Instance details Defined in Web.Scotty.Internal.Types Methods (>>=) :: ActionT m a -> (a -> ActionT m b) -> ActionT m b Source # (>>) :: ActionT m a -> ActionT m b -> ActionT m b Source # return :: a -> ActionT m a Source #
MonadUnliftIO m => MonadPlus (ActionT m) Source # |
Instance details Defined in Web.Scotty.Internal.Types Methods mzero :: ActionT m a Source # mplus :: ActionT m a -> ActionT m a -> ActionT m a Source #
MonadIO m => MonadFail (ActionT m) Source # | Modeled after the behaviour in scotty < 0.20, `fail` throws a `StatusError` with code 500 ("Server Error"), which can be caught with `catch`.
Instance details Defined in Web.Scotty.Internal.Types Methods fail :: String -> ActionT m a Source #
MonadUnliftIO m => MonadUnliftIO (ActionT m) Source # |
Instance details Defined in Web.Scotty.Internal.Types Methods withRunInIO :: ((forall a. ActionT m a -> IO a) -> IO b) -> ActionT m b
(Monad m, Monoid a) => Monoid (ActionT m a) Source # |
Instance details Defined in Web.Scotty.Internal.Types Methods mempty :: ActionT m a Source # mappend :: ActionT m a -> ActionT m a -> ActionT m a Source # mconcat :: [ActionT m a] -> ActionT m a Source #
(Monad m, Semigroup a) => Semigroup (ActionT m a) Source # |
Instance details Defined in Web.Scotty.Internal.Types Methods (<>) :: ActionT m a -> ActionT m a -> ActionT m a Source # sconcat :: NonEmpty (ActionT m a) -> ActionT m a Source # stimes :: Integral b => b -> ActionT m a -> ActionT m a Source #
type StT ActionT a Source # |
Instance details Defined in Web.Scotty.Internal.Types type StT ActionT a = StT (ReaderT ActionEnv) a
type StM (ActionT m) a Source # |
Instance details Defined in Web.Scotty.Internal.Types type StM (ActionT m) a = StM (ReaderT ActionEnv m) a

data ScottyState (m :: Type -> Type) Source #

defaultScottyState :: forall (m :: Type -> Type). ScottyState m Source #