Safe Haskell | None |
---|---|
Language | Haskell2010 |
It should be noted that most of the code snippets below depend on the OverloadedStrings language pragma.
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
- scotty :: Port -> ScottyM () -> IO ()
- scottyApp :: ScottyM () -> IO Application
- scottyOpts :: Options -> ScottyM () -> IO ()
- scottySocket :: Options -> Socket -> ScottyM () -> IO ()
- data Options = Options {}
- middleware :: Middleware -> ScottyM ()
- get :: RoutePattern -> ActionM () -> ScottyM ()
- post :: RoutePattern -> ActionM () -> ScottyM ()
- put :: RoutePattern -> ActionM () -> ScottyM ()
- delete :: RoutePattern -> ActionM () -> ScottyM ()
- patch :: RoutePattern -> ActionM () -> ScottyM ()
- options :: RoutePattern -> ActionM () -> ScottyM ()
- addroute :: StdMethod -> RoutePattern -> ActionM () -> ScottyM ()
- matchAny :: RoutePattern -> ActionM () -> ScottyM ()
- notFound :: ActionM () -> ScottyM ()
- capture :: String -> RoutePattern
- regex :: String -> RoutePattern
- function :: (Request -> Maybe [Param]) -> RoutePattern
- literal :: String -> RoutePattern
- request :: ActionM Request
- header :: Text -> ActionM (Maybe Text)
- headers :: ActionM [(Text, Text)]
- body :: ActionM ByteString
- bodyReader :: ActionM (IO ByteString)
- param :: Parsable a => Text -> ActionM a
- params :: ActionM [Param]
- jsonData :: FromJSON a => ActionM a
- files :: ActionM [File]
- status :: Status -> ActionM ()
- addHeader :: Text -> Text -> ActionM ()
- setHeader :: Text -> Text -> ActionM ()
- redirect :: Text -> ActionM a
- text :: Text -> ActionM ()
- html :: Text -> ActionM ()
- file :: FilePath -> ActionM ()
- json :: ToJSON a => a -> ActionM ()
- stream :: StreamingBody -> ActionM ()
- raw :: ByteString -> ActionM ()
- raise :: Text -> ActionM a
- raiseStatus :: Status -> Text -> ActionM a
- rescue :: ActionM a -> (Text -> ActionM a) -> ActionM a
- next :: ActionM a
- finish :: ActionM a
- defaultHandler :: (Text -> ActionM ()) -> ScottyM ()
- liftAndCatchIO :: IO a -> ActionM a
- 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
- type ScottyM = ScottyT Text IO
- type ActionM = ActionT Text IO
- data RoutePattern
- type File = (Text, FileInfo ByteString)
scotty-to-WAI
scottyApp :: ScottyM () -> IO Application Source #
Turn a scotty application into a WAI Application
, which can be
run with any WAI handler.
scottyOpts :: Options -> ScottyM () -> IO () Source #
Run a scotty application using the warp server, passing extra options.
scottySocket :: Options -> Socket -> ScottyM () -> IO () Source #
Run a scotty application using the warp server, passing extra options, and listening on the provided socket. This allows the user to provide, for example, a Unix named socket, which can be used when reverse HTTP proxying into your application.
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 -> ScottyM () 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.
addroute :: StdMethod -> RoutePattern -> ActionM () -> ScottyM () 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 param
.
addroute GET "/foo/:bar" $ do v <- param "bar" text v
>>>
curl http://localhost:3000/foo/something
something
matchAny :: RoutePattern -> ActionM () -> ScottyM () Source #
Add a route that matches regardless of the HTTP verb.
notFound :: ActionM () -> ScottyM () Source #
Specify an action to take if nothing else is found. Note: this _always_ matches, so should generally be the last route specified.
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", 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 :: Text -> ActionM (Maybe Text) Source #
Get a request header. Header name is case-insensitive.
headers :: ActionM [(Text, Text)] Source #
Get all the request headers. Header names are case-insensitive.
body :: ActionM ByteString Source #
Get the request body.
bodyReader :: ActionM (IO ByteString) Source #
param :: Parsable a => Text -> ActionM a Source #
Get a parameter. First looks in captures, then form data, then query parameters.
jsonData :: FromJSON a => ActionM a Source #
Parse the request body as a JSON object and return it. Raises an exception if parse is unsuccessful.
Modifying the Response and Redirecting
addHeader :: Text -> Text -> ActionM () Source #
Add to the response headers. Header names are case-insensitive.
setHeader :: Text -> Text -> ActionM () Source #
Set one of the response headers. Will override any previously set value for that header. Header names are case-insensitive.
redirect :: Text -> ActionM 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 :: Text -> ActionM () 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 :: Text -> ActionM () 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 :: FilePath -> ActionM () 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
.
json :: ToJSON a => a -> ActionM () 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 :: StreamingBody -> ActionM () Source #
Set the body of the response to a StreamingBody. Doesn't set the
"Content-Type" header, so you probably want to do that on your
own with setHeader
.
raw :: ByteString -> ActionM () 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
.
Exceptions
raise :: Text -> ActionM a Source #
Throw an exception, which can be caught with rescue
. Uncaught exceptions
turn into HTTP 500 responses.
raiseStatus :: Status -> Text -> ActionM a Source #
Throw an exception, which can be caught with rescue
. Uncaught exceptions turn into HTTP responses corresponding to the given status.
rescue :: ActionM a -> (Text -> ActionM a) -> ActionM a Source #
Catch an exception thrown by raise
.
raise "just kidding" `rescue` (\msg -> text msg)
Abort execution of this action and continue pattern matching routes.
Like an exception, any code after next
is not executed.
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 <- param "bar" unless (w == "special") next text "You made a request to /foo/special" get "/foo/:baz" $ do w <- param "baz" text $ "You made a request to: " <> w
Abort execution of this action. Like an exception, any code after finish
is not executed.
As an example only requests to /foo/special
will include in the response
content the text message.
get "/foo/:bar" $ do w :: Text <- param "bar" unless (w == "special") finish text "You made a request to /foo/special"
Since: 0.10.3
defaultHandler :: (Text -> ActionM ()) -> ScottyM () Source #
Global handler for uncaught exceptions.
Uncaught exceptions normally become 500 responses. You can use this to selectively override that behavior.
Note: IO exceptions are lifted into Scotty exceptions by default. This has security implications, so you probably want to provide your own defaultHandler in production which does not send out the error strings as 500 responses.
liftAndCatchIO :: IO a -> ActionM a Source #
Like liftIO
, but catch any IO exceptions and turn them into Scotty exceptions.
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 # |