Safe Haskell | Safe-Inferred |
---|---|
Language | Haskell2010 |
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 in order that Scotty be combined with other DSLs.
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.
Synopsis
- scottyT :: (Monad m, MonadIO n) => Port -> (m Response -> IO Response) -> ScottyT m () -> n ()
- scottyAppT :: (Monad m, Monad n) => (m Response -> IO Response) -> ScottyT m () -> n Application
- 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 {}
- defaultOptions :: Options
- middleware :: Middleware -> ScottyT m ()
- get :: MonadUnliftIO m => RoutePattern -> ActionT m () -> ScottyT m ()
- post :: MonadUnliftIO m => RoutePattern -> ActionT m () -> ScottyT m ()
- put :: MonadUnliftIO m => RoutePattern -> ActionT m () -> ScottyT m ()
- delete :: MonadUnliftIO m => RoutePattern -> ActionT m () -> ScottyT m ()
- patch :: MonadUnliftIO m => RoutePattern -> ActionT m () -> ScottyT m ()
- options :: MonadUnliftIO m => RoutePattern -> ActionT m () -> ScottyT m ()
- addroute :: MonadUnliftIO m => StdMethod -> RoutePattern -> ActionT m () -> ScottyT m ()
- matchAny :: MonadUnliftIO m => RoutePattern -> ActionT m () -> ScottyT m ()
- notFound :: MonadUnliftIO m => ActionT m () -> ScottyT m ()
- setMaxRequestBodySize :: Kilobytes -> ScottyT m ()
- capture :: String -> RoutePattern
- regex :: String -> RoutePattern
- function :: (Request -> Maybe [Param]) -> RoutePattern
- literal :: String -> RoutePattern
- request :: Monad m => ActionT m Request
- header :: Monad m => Text -> ActionT m (Maybe Text)
- headers :: Monad m => ActionT m [(Text, Text)]
- body :: MonadIO m => ActionT m ByteString
- bodyReader :: Monad m => ActionT m (IO ByteString)
- param :: (Parsable a, MonadIO m) => Text -> ActionT m a
- params :: Monad m => ActionT m [Param]
- captureParam :: (Parsable a, Monad m) => Text -> ActionT m a
- formParam :: (Parsable a, Monad m) => Text -> ActionT m a
- queryParam :: (Parsable a, Monad m) => Text -> ActionT m a
- captureParams :: Monad m => ActionT m [Param]
- formParams :: Monad m => ActionT m [Param]
- queryParams :: Monad m => ActionT m [Param]
- jsonData :: (FromJSON a, MonadIO m) => ActionT m a
- files :: Monad m => ActionT m [File]
- status :: MonadIO m => Status -> ActionT m ()
- addHeader :: MonadIO m => Text -> Text -> ActionT m ()
- setHeader :: MonadIO m => Text -> Text -> ActionT m ()
- redirect :: Monad m => Text -> ActionT m a
- text :: MonadIO m => Text -> ActionT m ()
- html :: MonadIO m => Text -> ActionT m ()
- file :: MonadIO m => FilePath -> ActionT m ()
- json :: (ToJSON a, MonadIO m) => a -> ActionT m ()
- stream :: MonadIO m => StreamingBody -> ActionT m ()
- raw :: MonadIO m => ByteString -> ActionT m ()
- nested :: MonadIO m => Application -> ActionT m ()
- raise :: MonadIO m => Text -> ActionT m a
- raiseStatus :: Monad m => Status -> Text -> ActionT m a
- throw :: (MonadIO m, Exception e) => e -> ActionT m a
- rescue :: (MonadUnliftIO m, Exception e) => ActionT m a -> (e -> ActionT m a) -> ActionT m a
- next :: Monad m => ActionT m a
- finish :: Monad m => ActionT m a
- defaultHandler :: Monad m => ErrorHandler m -> ScottyT m ()
- liftAndCatchIO :: MonadIO m => IO a -> ActionT m a
- data StatusError = StatusError Status Text
- 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 = (Text, FileInfo ByteString)
- type Kilobytes = Int
- type ErrorHandler m = Handler (ActionT m) ()
- data Handler (m :: Type -> Type) a = Exception e => Handler (e -> m a)
- data ScottyT m a
- data ActionT m a
- data ScottyState m
- defaultScottyState :: ScottyState m
scotty-to-WAI
:: (Monad m, MonadIO n) | |
=> Port | |
-> (m Response -> IO Response) | Run monad |
-> ScottyT m () | |
-> n () |
Run a scotty application using the warp server. NB: scotty p === scottyT p id
:: (Monad m, Monad n) | |
=> (m Response -> IO Response) | Run monad |
-> ScottyT m () | |
-> n Application |
Turn a scotty application into a WAI Application
, which can be
run with any WAI handler.
NB: scottyApp === scottyAppT id
:: (Monad m, MonadIO n) | |
=> Options | |
-> (m Response -> IO Response) | Run monad |
-> 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
Options | |
|
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 :: 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 :: MonadUnliftIO m => RoutePattern -> ActionT m () -> ScottyT m () Source #
post :: MonadUnliftIO m => RoutePattern -> ActionT m () -> ScottyT m () Source #
put :: MonadUnliftIO m => RoutePattern -> ActionT m () -> ScottyT m () Source #
delete :: MonadUnliftIO m => RoutePattern -> ActionT m () -> ScottyT m () Source #
patch :: MonadUnliftIO m => RoutePattern -> ActionT m () -> ScottyT m () Source #
options :: MonadUnliftIO m => RoutePattern -> ActionT m () -> ScottyT m () Source #
addroute :: MonadUnliftIO m => StdMethod -> RoutePattern -> ActionT m () -> ScottyT m () Source #
Define a route with a StdMethod
, Text
value representing the path spec,
and a body (Action
) which modifies the response.
addroute GET "/" $ text "beam me up!"
The path spec can include values starting with a colon, which are interpreted
as captures. These are named wildcards that can be looked up with captureParam
.
addroute GET "/foo/:bar" $ do v <- captureParam "bar" text v
>>>
curl http://localhost:3000/foo/something
something
NB: the RouteOptions
and the exception handler of the newly-created route will be
copied from the previously-created routes.
matchAny :: MonadUnliftIO m => RoutePattern -> ActionT m () -> ScottyT m () Source #
Add a route that matches regardless of the HTTP verb.
notFound :: 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 #
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.
get (regex "^/f(.*)r$") $ do path <- param "0" cap <- param "1" text $ mconcat ["Path: ", path, "\nCapture: ", cap]
>>>
curl http://localhost:3000/foo/bar
Path: /foo/bar Capture: 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
.
get (function $ \req -> Just [("version", T.pack $ show $ httpVersion req)]) $ do v <- param "version" text v
>>>
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, Captures, and Query Parameters
header :: Monad m => Text -> ActionT m (Maybe Text) Source #
Get a request header. Header name is case-insensitive.
headers :: Monad m => ActionT m [(Text, Text)] Source #
Get all the request headers. Header names are case-insensitive.
bodyReader :: Monad m => ActionT m (IO ByteString) Source #
param :: (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
rescue
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 :: Monad m => ActionT m [Param] Source #
Deprecated: (#204) Not a good idea to treat all parameters identically. Use captureParams, formParams and queryParams instead.
Get all parameters from capture, form and query (in that order).
captureParam :: (Parsable a, Monad m) => Text -> ActionT m a Source #
Get a capture parameter.
- Raises an exception which can be caught by
rescue
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.
formParam :: (Parsable a, Monad m) => Text -> ActionT m a Source #
Get a form parameter.
- Raises an exception which can be caught by
rescue
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.
queryParam :: (Parsable a, Monad m) => Text -> ActionT m a Source #
Get a query parameter.
- Raises an exception which can be caught by
rescue
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.
jsonData :: (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.
Modifying the Response and Redirecting
addHeader :: MonadIO m => Text -> Text -> ActionT m () Source #
Add to the response headers. Header names are case-insensitive.
setHeader :: 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 :: 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 :: MonadIO m => Text -> ActionT m () Source #
Set the body of the response to the given Text
value. Also sets "Content-Type"
header to "text/plain; charset=utf-8" if it has not already been set.
html :: MonadIO m => Text -> ActionT m () Source #
Set the body of the response to the given Text
value. Also sets "Content-Type"
header to "text/html; charset=utf-8" if it has not already been set.
file :: 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 :: (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 :: 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 :: 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 :: MonadIO m => Application -> ActionT m () Source #
Nest a whole WAI application inside a Scotty handler. See Web.Scotty for further documentation
Exceptions
Throw a "500 Server Error" StatusError
, which can be caught with rescue
.
Uncaught exceptions turn into HTTP 500 responses.
raiseStatus :: Monad m => Status -> Text -> ActionT m a Source #
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 :: (MonadIO m, Exception e) => e -> ActionT m a Source #
Throw an exception which can be caught within the scope of the current Action with rescue
or 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 :: (MonadUnliftIO m, Exception e) => ActionT m a -> (e -> ActionT m a) -> ActionT m a Source #
Catch an exception e.g. a StatusError
or a user-defined exception.
raise JustKidding `rescue` (\msg -> text msg)
next :: 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 <- captureParam "bar" unless (w == "special") next text "You made a request to /foo/special" get "/foo/:baz" $ do w <- captureParam "baz" text $ "You made a request to: " <> w
finish :: 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 :: Monad m => ErrorHandler m -> ScottyT m () Source #
Global handler for user-defined exceptions.
data StatusError Source #
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)
Instances
Exception StatusError Source # | |
Defined in Web.Scotty.Internal.Types | |
Show StatusError Source # | |
Defined in Web.Scotty.Internal.Types showsPrec :: Int -> StatusError -> ShowS # show :: StatusError -> String # showList :: [StatusError] -> ShowS # | |
MonadUnliftIO m => MonadError StatusError (ActionT m) Source # | Models the invariant that only |
Defined in Web.Scotty.Internal.Types throwError :: StatusError -> ActionT m a # catchError :: ActionT m a -> (StatusError -> ActionT m a) -> ActionT m a # |
Parsing Parameters
class Parsable a where Source #
Minimum implemention: parseParam
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
Types
data RoutePattern Source #
Instances
IsString RoutePattern Source # | |
Defined in Web.Scotty.Internal.Types fromString :: String -> RoutePattern # |
Monad Transformers
Instances
data ScottyState m Source #
Instances
Default (ScottyState m) Source # | |
Defined in Web.Scotty.Internal.Types def :: ScottyState m # |