{-# LANGUAGE CPP               #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RankNTypes        #-}
module Web.Scotty.Action
    ( addHeader
    , body
    , bodyReader
    , file
    , files
    , finish
    , header
    , headers
    , html
    , liftAndCatchIO
    , json
    , jsonData
    , next
    , param
    , params
    , raise
    , raiseStatus
    , raw
    , readEither
    , redirect
    , request
    , rescue
    , setHeader
    , status
    , stream
    , text
    , Param
    , Parsable(..)
      -- private to Scotty
    , runAction
    ) where

import           Blaze.ByteString.Builder   (fromLazyByteString)

import qualified Control.Exception          as E
import           Control.Monad              (liftM, when)
import           Control.Monad.Error.Class
import           Control.Monad.IO.Class     (MonadIO(..))
import           Control.Monad.Reader       (MonadReader(..), ReaderT(..))
import qualified Control.Monad.State.Strict as MS
import           Control.Monad.Trans.Except

import qualified Data.Aeson                 as A
import qualified Data.ByteString.Char8      as B
import qualified Data.ByteString.Lazy.Char8 as BL
import qualified Data.CaseInsensitive       as CI
import           Data.Default.Class         (def)
import           Data.Int
import qualified Data.Text                  as ST
import qualified Data.Text.Encoding         as STE
import qualified Data.Text.Lazy             as T
import           Data.Text.Lazy.Encoding    (encodeUtf8)
import           Data.Word

import           Network.HTTP.Types
-- not re-exported until version 0.11
#if !MIN_VERSION_http_types(0,11,0)
import           Network.HTTP.Types.Status
#endif
import           Network.Wai

import           Numeric.Natural

import           Prelude ()
import           Prelude.Compat

import           Web.Scotty.Internal.Types
import           Web.Scotty.Util

-- Nothing indicates route failed (due to Next) and pattern matching should continue.
-- Just indicates a successful response.
runAction :: (ScottyError e, Monad m) => ErrorHandler e m -> ActionEnv -> ActionT e m () -> m (Maybe Response)
runAction :: forall e (m :: * -> *).
(ScottyError e, Monad m) =>
ErrorHandler e m
-> ActionEnv -> ActionT e m () -> m (Maybe Response)
runAction ErrorHandler e m
h ActionEnv
env ActionT e m ()
action = do
    (Either (ActionError e) ()
e,ScottyResponse
r) <- forall a b c. (a -> b -> c) -> b -> a -> c
flip forall s (m :: * -> *) a. StateT s m a -> s -> m (a, s)
MS.runStateT forall a. Default a => a
def
           forall a b. (a -> b) -> a -> b
$ forall a b c. (a -> b -> c) -> b -> a -> c
flip forall r (m :: * -> *) a. ReaderT r m a -> r -> m a
runReaderT ActionEnv
env
           forall a b. (a -> b) -> a -> b
$ forall e (m :: * -> *) a. ExceptT e m a -> m (Either e a)
runExceptT
           forall a b. (a -> b) -> a -> b
$ forall e (m :: * -> *) a.
ActionT e m a
-> ExceptT
     (ActionError e) (ReaderT ActionEnv (StateT ScottyResponse m)) a
runAM
           forall a b. (a -> b) -> a -> b
$ ActionT e m ()
action forall e (m :: * -> *) a.
MonadError e m =>
m a -> (e -> m a) -> m a
`catchError` (forall e (m :: * -> *).
(ScottyError e, Monad m) =>
ErrorHandler e m -> ActionError e -> ActionT e m ()
defH ErrorHandler e m
h)
    forall (m :: * -> *) a. Monad m => a -> m a
return forall a b. (a -> b) -> a -> b
$ forall a c b. (a -> c) -> (b -> c) -> Either a b -> c
either (forall a b. a -> b -> a
const forall a. Maybe a
Nothing) (forall a b. a -> b -> a
const forall a b. (a -> b) -> a -> b
$ forall a. a -> Maybe a
Just forall a b. (a -> b) -> a -> b
$ ScottyResponse -> Response
mkResponse ScottyResponse
r) Either (ActionError e) ()
e

-- | Default error handler for all actions.
defH :: (ScottyError e, Monad m) => ErrorHandler e m -> ActionError e -> ActionT e m ()
defH :: forall e (m :: * -> *).
(ScottyError e, Monad m) =>
ErrorHandler e m -> ActionError e -> ActionT e m ()
defH ErrorHandler e m
_          (Redirect Text
url)    = do
    forall (m :: * -> *) e. Monad m => Status -> ActionT e m ()
status Status
status302
    forall (m :: * -> *) e. Monad m => Text -> Text -> ActionT e m ()
setHeader Text
"Location" Text
url
defH ErrorHandler e m
Nothing    (ActionError Status
s e
e)   = do
    forall (m :: * -> *) e. Monad m => Status -> ActionT e m ()
status Status
s
    let code :: Text
code = String -> Text
T.pack forall a b. (a -> b) -> a -> b
$ forall a. Show a => a -> String
show forall a b. (a -> b) -> a -> b
$ Status -> Int
statusCode Status
s
    let msg :: Text
msg = Text -> Text
T.fromStrict forall a b. (a -> b) -> a -> b
$ ByteString -> Text
STE.decodeUtf8 forall a b. (a -> b) -> a -> b
$ Status -> ByteString
statusMessage Status
s
    forall e (m :: * -> *).
(ScottyError e, Monad m) =>
Text -> ActionT e m ()
html forall a b. (a -> b) -> a -> b
$ forall a. Monoid a => [a] -> a
mconcat [Text
"<h1>", Text
code, Text
" ", Text
msg, Text
"</h1>", forall e. ScottyError e => e -> Text
showError e
e]
defH h :: ErrorHandler e m
h@(Just e -> ActionT e m ()
f) (ActionError Status
_ e
e)   = e -> ActionT e m ()
f e
e forall e (m :: * -> *) a.
MonadError e m =>
m a -> (e -> m a) -> m a
`catchError` (forall e (m :: * -> *).
(ScottyError e, Monad m) =>
ErrorHandler e m -> ActionError e -> ActionT e m ()
defH ErrorHandler e m
h) -- so handlers can throw exceptions themselves
defH ErrorHandler e m
_          ActionError e
Next              = forall e (m :: * -> *) a. (ScottyError e, Monad m) => ActionT e m a
next
defH ErrorHandler e m
_          ActionError e
Finish            = forall (m :: * -> *) a. Monad m => a -> m a
return ()

-- | Throw an exception, which can be caught with 'rescue'. Uncaught exceptions
-- turn into HTTP 500 responses.
raise :: (ScottyError e, Monad m) => e -> ActionT e m a
raise :: forall e (m :: * -> *) a.
(ScottyError e, Monad m) =>
e -> ActionT e m a
raise = forall e (m :: * -> *) a.
(ScottyError e, Monad m) =>
Status -> e -> ActionT e m a
raiseStatus Status
status500

-- | Throw an exception, which can be caught with 'rescue'. Uncaught exceptions turn into HTTP responses corresponding to the given status.
raiseStatus :: (ScottyError e, Monad m) => Status -> e -> ActionT e m a
raiseStatus :: forall e (m :: * -> *) a.
(ScottyError e, Monad m) =>
Status -> e -> ActionT e m a
raiseStatus Status
s = forall e (m :: * -> *) a. MonadError e m => e -> m a
throwError forall b c a. (b -> c) -> (a -> b) -> a -> c
. forall e. Status -> e -> ActionError e
ActionError Status
s

-- | 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
next :: (ScottyError e, Monad m) => ActionT e m a
next :: forall e (m :: * -> *) a. (ScottyError e, Monad m) => ActionT e m a
next = forall e (m :: * -> *) a. MonadError e m => e -> m a
throwError forall e. ActionError e
Next

-- | Catch an exception thrown by 'raise'.
--
-- > raise "just kidding" `rescue` (\msg -> text msg)
rescue :: (ScottyError e, Monad m) => ActionT e m a -> (e -> ActionT e m a) -> ActionT e m a
rescue :: forall e (m :: * -> *) a.
(ScottyError e, Monad m) =>
ActionT e m a -> (e -> ActionT e m a) -> ActionT e m a
rescue ActionT e m a
action e -> ActionT e m a
h = forall e (m :: * -> *) a.
MonadError e m =>
m a -> (e -> m a) -> m a
catchError ActionT e m a
action forall a b. (a -> b) -> a -> b
$ \ActionError e
e -> case ActionError e
e of
    ActionError Status
_ e
err -> e -> ActionT e m a
h e
err            -- handle errors
    ActionError e
other             -> forall e (m :: * -> *) a. MonadError e m => e -> m a
throwError ActionError e
other -- rethrow internal error types

-- | Like 'liftIO', but catch any IO exceptions and turn them into 'ScottyError's.
liftAndCatchIO :: (ScottyError e, MonadIO m) => IO a -> ActionT e m a
liftAndCatchIO :: forall e (m :: * -> *) a.
(ScottyError e, MonadIO m) =>
IO a -> ActionT e m a
liftAndCatchIO IO a
io = forall e (m :: * -> *) a.
ExceptT
  (ActionError e) (ReaderT ActionEnv (StateT ScottyResponse m)) a
-> ActionT e m a
ActionT forall a b. (a -> b) -> a -> b
$ do
    Either (ActionError e) a
r <- forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO forall a b. (a -> b) -> a -> b
$ forall (m :: * -> *) a1 r. Monad m => (a1 -> r) -> m a1 -> m r
liftM forall a b. b -> Either a b
Right IO a
io forall e a. Exception e => IO a -> (e -> IO a) -> IO a
`E.catch` (\ SomeException
e -> forall (m :: * -> *) a. Monad m => a -> m a
return forall a b. (a -> b) -> a -> b
$ forall a b. a -> Either a b
Left forall a b. (a -> b) -> a -> b
$ forall e. ScottyError e => String -> e
stringError forall a b. (a -> b) -> a -> b
$ forall a. Show a => a -> String
show (SomeException
e :: E.SomeException))
    forall a c b. (a -> c) -> (b -> c) -> Either a b -> c
either forall e (m :: * -> *) a. MonadError e m => e -> m a
throwError forall (m :: * -> *) a. Monad m => a -> m a
return Either (ActionError e) a
r

-- | 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"
redirect :: (ScottyError e, Monad m) => T.Text -> ActionT e m a
redirect :: forall e (m :: * -> *) a.
(ScottyError e, Monad m) =>
Text -> ActionT e m a
redirect = forall e (m :: * -> *) a. MonadError e m => e -> m a
throwError forall b c a. (b -> c) -> (a -> b) -> a -> c
. forall e. Text -> ActionError e
Redirect

-- | 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/
finish :: (ScottyError e, Monad m) => ActionT e m a
finish :: forall e (m :: * -> *) a. (ScottyError e, Monad m) => ActionT e m a
finish = forall e (m :: * -> *) a. MonadError e m => e -> m a
throwError forall e. ActionError e
Finish

-- | Get the 'Request' object.
request :: Monad m => ActionT e m Request
request :: forall (m :: * -> *) e. Monad m => ActionT e m Request
request = forall e (m :: * -> *) a.
ExceptT
  (ActionError e) (ReaderT ActionEnv (StateT ScottyResponse m)) a
-> ActionT e m a
ActionT forall a b. (a -> b) -> a -> b
$ forall (m :: * -> *) a1 r. Monad m => (a1 -> r) -> m a1 -> m r
liftM ActionEnv -> Request
getReq forall r (m :: * -> *). MonadReader r m => m r
ask

-- | Get list of uploaded files.
files :: Monad m => ActionT e m [File]
files :: forall (m :: * -> *) e. Monad m => ActionT e m [File]
files = forall e (m :: * -> *) a.
ExceptT
  (ActionError e) (ReaderT ActionEnv (StateT ScottyResponse m)) a
-> ActionT e m a
ActionT forall a b. (a -> b) -> a -> b
$ forall (m :: * -> *) a1 r. Monad m => (a1 -> r) -> m a1 -> m r
liftM ActionEnv -> [File]
getFiles forall r (m :: * -> *). MonadReader r m => m r
ask

-- | Get a request header. Header name is case-insensitive.
header :: (ScottyError e, Monad m) => T.Text -> ActionT e m (Maybe T.Text)
header :: forall e (m :: * -> *).
(ScottyError e, Monad m) =>
Text -> ActionT e m (Maybe Text)
header Text
k = do
    RequestHeaders
hs <- forall (m :: * -> *) a1 r. Monad m => (a1 -> r) -> m a1 -> m r
liftM Request -> RequestHeaders
requestHeaders forall (m :: * -> *) e. Monad m => ActionT e m Request
request
    forall (m :: * -> *) a. Monad m => a -> m a
return forall a b. (a -> b) -> a -> b
$ forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap ByteString -> Text
strictByteStringToLazyText forall a b. (a -> b) -> a -> b
$ forall a b. Eq a => a -> [(a, b)] -> Maybe b
lookup (forall s. FoldCase s => s -> CI s
CI.mk (Text -> ByteString
lazyTextToStrictByteString Text
k)) RequestHeaders
hs

-- | Get all the request headers. Header names are case-insensitive.
headers :: (ScottyError e, Monad m) => ActionT e m [(T.Text, T.Text)]
headers :: forall e (m :: * -> *).
(ScottyError e, Monad m) =>
ActionT e m [(Text, Text)]
headers = do
    RequestHeaders
hs <- forall (m :: * -> *) a1 r. Monad m => (a1 -> r) -> m a1 -> m r
liftM Request -> RequestHeaders
requestHeaders forall (m :: * -> *) e. Monad m => ActionT e m Request
request
    forall (m :: * -> *) a. Monad m => a -> m a
return [ ( ByteString -> Text
strictByteStringToLazyText (forall s. CI s -> s
CI.original CI ByteString
k)
             , ByteString -> Text
strictByteStringToLazyText ByteString
v)
           | (CI ByteString
k,ByteString
v) <- RequestHeaders
hs ]

-- | Get the request body.
body :: (ScottyError e,  MonadIO m) => ActionT e m BL.ByteString
body :: forall e (m :: * -> *).
(ScottyError e, MonadIO m) =>
ActionT e m ByteString
body = forall e (m :: * -> *) a.
ExceptT
  (ActionError e) (ReaderT ActionEnv (StateT ScottyResponse m)) a
-> ActionT e m a
ActionT forall r (m :: * -> *). MonadReader r m => m r
ask forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= (forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO forall b c a. (b -> c) -> (a -> b) -> a -> c
. ActionEnv -> IO ByteString
getBody)

-- | Get an IO action that reads body chunks
--
-- * This is incompatible with 'body' since 'body' consumes all chunks.
bodyReader :: Monad m => ActionT e m (IO B.ByteString)
bodyReader :: forall (m :: * -> *) e. Monad m => ActionT e m (IO ByteString)
bodyReader = forall e (m :: * -> *) a.
ExceptT
  (ActionError e) (ReaderT ActionEnv (StateT ScottyResponse m)) a
-> ActionT e m a
ActionT forall a b. (a -> b) -> a -> b
$ ActionEnv -> IO ByteString
getBodyChunk forall (m :: * -> *) a1 r. Monad m => (a1 -> r) -> m a1 -> m r
`liftM` forall r (m :: * -> *). MonadReader r m => m r
ask

-- | 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.
jsonData :: (A.FromJSON a, ScottyError e, MonadIO m) => ActionT e m a
jsonData :: forall a e (m :: * -> *).
(FromJSON a, ScottyError e, MonadIO m) =>
ActionT e m a
jsonData = do
    ByteString
b <- forall e (m :: * -> *).
(ScottyError e, MonadIO m) =>
ActionT e m ByteString
body
    forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
when (ByteString
b forall a. Eq a => a -> a -> Bool
== ByteString
"") forall a b. (a -> b) -> a -> b
$ do
      let htmlError :: String
htmlError = String
"jsonData - No data was provided."
      forall e (m :: * -> *) a.
(ScottyError e, Monad m) =>
Status -> e -> ActionT e m a
raiseStatus Status
status400 forall a b. (a -> b) -> a -> b
$ forall e. ScottyError e => String -> e
stringError String
htmlError
    case forall a. FromJSON a => ByteString -> Either String a
A.eitherDecode ByteString
b of
      Left String
err -> do
        let htmlError :: String
htmlError = String
"jsonData - malformed."
              forall a. Monoid a => a -> a -> a
`mappend` String
" Data was: " forall a. Monoid a => a -> a -> a
`mappend` ByteString -> String
BL.unpack ByteString
b
              forall a. Monoid a => a -> a -> a
`mappend` String
" Error was: " forall a. Monoid a => a -> a -> a
`mappend` String
err
        forall e (m :: * -> *) a.
(ScottyError e, Monad m) =>
Status -> e -> ActionT e m a
raiseStatus Status
status400 forall a b. (a -> b) -> a -> b
$ forall e. ScottyError e => String -> e
stringError String
htmlError
      Right Value
value -> case forall a. FromJSON a => Value -> Result a
A.fromJSON Value
value of
        A.Error String
err -> do
          let htmlError :: String
htmlError = String
"jsonData - failed parse."
                forall a. Monoid a => a -> a -> a
`mappend` String
" Data was: " forall a. Monoid a => a -> a -> a
`mappend` ByteString -> String
BL.unpack ByteString
b forall a. Monoid a => a -> a -> a
`mappend` String
"."
                forall a. Monoid a => a -> a -> a
`mappend` String
" Error was: " forall a. Monoid a => a -> a -> a
`mappend` String
err
          forall e (m :: * -> *) a.
(ScottyError e, Monad m) =>
Status -> e -> ActionT e m a
raiseStatus Status
status422 forall a b. (a -> b) -> a -> b
$ forall e. ScottyError e => String -> e
stringError String
htmlError
        A.Success a
a -> do
          forall (m :: * -> *) a. Monad m => a -> m a
return a
a

-- | 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 'read' 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.
param :: (Parsable a, ScottyError e, Monad m) => T.Text -> ActionT e m a
param :: forall a e (m :: * -> *).
(Parsable a, ScottyError e, Monad m) =>
Text -> ActionT e m a
param Text
k = do
    Maybe Text
val <- forall e (m :: * -> *) a.
ExceptT
  (ActionError e) (ReaderT ActionEnv (StateT ScottyResponse m)) a
-> ActionT e m a
ActionT forall a b. (a -> b) -> a -> b
$ forall (m :: * -> *) a1 r. Monad m => (a1 -> r) -> m a1 -> m r
liftM (forall a b. Eq a => a -> [(a, b)] -> Maybe b
lookup Text
k forall b c a. (b -> c) -> (a -> b) -> a -> c
. ActionEnv -> [(Text, Text)]
getParams) forall r (m :: * -> *). MonadReader r m => m r
ask
    case Maybe Text
val of
        Maybe Text
Nothing -> forall e (m :: * -> *) a.
(ScottyError e, Monad m) =>
e -> ActionT e m a
raise forall a b. (a -> b) -> a -> b
$ forall e. ScottyError e => String -> e
stringError forall a b. (a -> b) -> a -> b
$ String
"Param: " forall a. [a] -> [a] -> [a]
++ Text -> String
T.unpack Text
k forall a. [a] -> [a] -> [a]
++ String
" not found!"
        Just Text
v  -> forall a c b. (a -> c) -> (b -> c) -> Either a b -> c
either (forall a b. a -> b -> a
const forall e (m :: * -> *) a. (ScottyError e, Monad m) => ActionT e m a
next) forall (m :: * -> *) a. Monad m => a -> m a
return forall a b. (a -> b) -> a -> b
$ forall a. Parsable a => Text -> Either Text a
parseParam Text
v

-- | Get all parameters from capture, form and query (in that order).
params :: Monad m => ActionT e m [Param]
params :: forall (m :: * -> *) e. Monad m => ActionT e m [(Text, Text)]
params = forall e (m :: * -> *) a.
ExceptT
  (ActionError e) (ReaderT ActionEnv (StateT ScottyResponse m)) a
-> ActionT e m a
ActionT forall a b. (a -> b) -> a -> b
$ forall (m :: * -> *) a1 r. Monad m => (a1 -> r) -> m a1 -> m r
liftM ActionEnv -> [(Text, Text)]
getParams forall r (m :: * -> *). MonadReader r m => m r
ask

-- | Minimum implemention: 'parseParam'
class Parsable a where
    -- | Take a 'T.Text' value and parse it as 'a', or fail with a message.
    parseParam :: T.Text -> Either T.Text a

    -- | Default implementation parses comma-delimited lists.
    --
    -- > parseParamList t = mapM parseParam (T.split (== ',') t)
    parseParamList :: T.Text -> Either T.Text [a]
    parseParamList Text
t = forall (t :: * -> *) (m :: * -> *) a b.
(Traversable t, Monad m) =>
(a -> m b) -> t a -> m (t b)
mapM forall a. Parsable a => Text -> Either Text a
parseParam ((Char -> Bool) -> Text -> [Text]
T.split (forall a. Eq a => a -> a -> Bool
== Char
',') Text
t)

-- No point using 'read' for Text, ByteString, Char, and String.
instance Parsable T.Text where parseParam :: Text -> Either Text Text
parseParam = forall a b. b -> Either a b
Right
instance Parsable ST.Text where parseParam :: Text -> Either Text Text
parseParam = forall a b. b -> Either a b
Right forall b c a. (b -> c) -> (a -> b) -> a -> c
. Text -> Text
T.toStrict
instance Parsable B.ByteString where parseParam :: Text -> Either Text ByteString
parseParam = forall a b. b -> Either a b
Right forall b c a. (b -> c) -> (a -> b) -> a -> c
. Text -> ByteString
lazyTextToStrictByteString
instance Parsable BL.ByteString where parseParam :: Text -> Either Text ByteString
parseParam = forall a b. b -> Either a b
Right forall b c a. (b -> c) -> (a -> b) -> a -> c
. Text -> ByteString
encodeUtf8
-- | Overrides default 'parseParamList' to parse String.
instance Parsable Char where
    parseParam :: Text -> Either Text Char
parseParam Text
t = case Text -> String
T.unpack Text
t of
                    [Char
c] -> forall a b. b -> Either a b
Right Char
c
                    String
_   -> forall a b. a -> Either a b
Left Text
"parseParam Char: no parse"
    parseParamList :: Text -> Either Text String
parseParamList = forall a b. b -> Either a b
Right forall b c a. (b -> c) -> (a -> b) -> a -> c
. Text -> String
T.unpack -- String
-- | 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 Parsable () where
    parseParam :: Text -> Either Text ()
parseParam Text
t = if Text -> Bool
T.null Text
t then forall a b. b -> Either a b
Right () else forall a b. a -> Either a b
Left Text
"parseParam Unit: no parse"

instance (Parsable a) => Parsable [a] where parseParam :: Text -> Either Text [a]
parseParam = forall a. Parsable a => Text -> Either Text [a]
parseParamList

instance Parsable Bool where
    parseParam :: Text -> Either Text Bool
parseParam Text
t = if Text
t' forall a. Eq a => a -> a -> Bool
== Text -> Text
T.toCaseFold Text
"true"
                   then forall a b. b -> Either a b
Right Bool
True
                   else if Text
t' forall a. Eq a => a -> a -> Bool
== Text -> Text
T.toCaseFold Text
"false"
                        then forall a b. b -> Either a b
Right Bool
False
                        else forall a b. a -> Either a b
Left Text
"parseParam Bool: no parse"
        where t' :: Text
t' = Text -> Text
T.toCaseFold Text
t

instance Parsable Double where parseParam :: Text -> Either Text Double
parseParam = forall a. Read a => Text -> Either Text a
readEither
instance Parsable Float where parseParam :: Text -> Either Text Float
parseParam = forall a. Read a => Text -> Either Text a
readEither

instance Parsable Int where parseParam :: Text -> Either Text Int
parseParam = forall a. Read a => Text -> Either Text a
readEither
instance Parsable Int8 where parseParam :: Text -> Either Text Int8
parseParam = forall a. Read a => Text -> Either Text a
readEither
instance Parsable Int16 where parseParam :: Text -> Either Text Int16
parseParam = forall a. Read a => Text -> Either Text a
readEither
instance Parsable Int32 where parseParam :: Text -> Either Text Int32
parseParam = forall a. Read a => Text -> Either Text a
readEither
instance Parsable Int64 where parseParam :: Text -> Either Text Int64
parseParam = forall a. Read a => Text -> Either Text a
readEither
instance Parsable Integer where parseParam :: Text -> Either Text Integer
parseParam = forall a. Read a => Text -> Either Text a
readEither

instance Parsable Word where parseParam :: Text -> Either Text Word
parseParam = forall a. Read a => Text -> Either Text a
readEither
instance Parsable Word8 where parseParam :: Text -> Either Text Word8
parseParam = forall a. Read a => Text -> Either Text a
readEither
instance Parsable Word16 where parseParam :: Text -> Either Text Word16
parseParam = forall a. Read a => Text -> Either Text a
readEither
instance Parsable Word32 where parseParam :: Text -> Either Text Word32
parseParam = forall a. Read a => Text -> Either Text a
readEither
instance Parsable Word64 where parseParam :: Text -> Either Text Word64
parseParam = forall a. Read a => Text -> Either Text a
readEither
instance Parsable Natural where parseParam :: Text -> Either Text Natural
parseParam = forall a. Read a => Text -> Either Text a
readEither

-- | Useful for creating 'Parsable' instances for things that already implement 'Read'. Ex:
--
-- > instance Parsable Int where parseParam = readEither
readEither :: Read a => T.Text -> Either T.Text a
readEither :: forall a. Read a => Text -> Either Text a
readEither Text
t = case [ a
x | (a
x,String
"") <- forall a. Read a => ReadS a
reads (Text -> String
T.unpack Text
t) ] of
                [a
x] -> forall a b. b -> Either a b
Right a
x
                []  -> forall a b. a -> Either a b
Left Text
"readEither: no parse"
                [a]
_   -> forall a b. a -> Either a b
Left Text
"readEither: ambiguous parse"

-- | Set the HTTP response status. Default is 200.
status :: Monad m => Status -> ActionT e m ()
status :: forall (m :: * -> *) e. Monad m => Status -> ActionT e m ()
status = forall e (m :: * -> *) a.
ExceptT
  (ActionError e) (ReaderT ActionEnv (StateT ScottyResponse m)) a
-> ActionT e m a
ActionT forall b c a. (b -> c) -> (a -> b) -> a -> c
. forall s (m :: * -> *). MonadState s m => (s -> s) -> m ()
MS.modify forall b c a. (b -> c) -> (a -> b) -> a -> c
. Status -> ScottyResponse -> ScottyResponse
setStatus

-- Not exported, but useful in the functions below.
changeHeader :: Monad m
             => (CI.CI B.ByteString -> B.ByteString -> [(HeaderName, B.ByteString)] -> [(HeaderName, B.ByteString)])
             -> T.Text -> T.Text -> ActionT e m ()
changeHeader :: forall (m :: * -> *) e.
Monad m =>
(CI ByteString -> ByteString -> RequestHeaders -> RequestHeaders)
-> Text -> Text -> ActionT e m ()
changeHeader CI ByteString -> ByteString -> RequestHeaders -> RequestHeaders
f Text
k = forall e (m :: * -> *) a.
ExceptT
  (ActionError e) (ReaderT ActionEnv (StateT ScottyResponse m)) a
-> ActionT e m a
ActionT
                 forall b c a. (b -> c) -> (a -> b) -> a -> c
. forall s (m :: * -> *). MonadState s m => (s -> s) -> m ()
MS.modify
                 forall b c a. (b -> c) -> (a -> b) -> a -> c
. (RequestHeaders -> RequestHeaders)
-> ScottyResponse -> ScottyResponse
setHeaderWith
                 forall b c a. (b -> c) -> (a -> b) -> a -> c
. CI ByteString -> ByteString -> RequestHeaders -> RequestHeaders
f (forall s. FoldCase s => s -> CI s
CI.mk forall a b. (a -> b) -> a -> b
$ Text -> ByteString
lazyTextToStrictByteString Text
k)
                 forall b c a. (b -> c) -> (a -> b) -> a -> c
. Text -> ByteString
lazyTextToStrictByteString

-- | Add to the response headers. Header names are case-insensitive.
addHeader :: Monad m => T.Text -> T.Text -> ActionT e m ()
addHeader :: forall (m :: * -> *) e. Monad m => Text -> Text -> ActionT e m ()
addHeader = forall (m :: * -> *) e.
Monad m =>
(CI ByteString -> ByteString -> RequestHeaders -> RequestHeaders)
-> Text -> Text -> ActionT e m ()
changeHeader forall a b. a -> b -> [(a, b)] -> [(a, b)]
add

-- | Set one of the response headers. Will override any previously set value for that header.
-- Header names are case-insensitive.
setHeader :: Monad m => T.Text -> T.Text -> ActionT e m ()
setHeader :: forall (m :: * -> *) e. Monad m => Text -> Text -> ActionT e m ()
setHeader = forall (m :: * -> *) e.
Monad m =>
(CI ByteString -> ByteString -> RequestHeaders -> RequestHeaders)
-> Text -> Text -> ActionT e m ()
changeHeader forall a b. Eq a => a -> b -> [(a, b)] -> [(a, b)]
replace

-- | Set the body of the response to the given 'T.Text' value. Also sets \"Content-Type\"
-- header to \"text/plain; charset=utf-8\" if it has not already been set.
text :: (ScottyError e, Monad m) => T.Text -> ActionT e m ()
text :: forall e (m :: * -> *).
(ScottyError e, Monad m) =>
Text -> ActionT e m ()
text Text
t = do
    forall (m :: * -> *) e.
Monad m =>
(CI ByteString -> ByteString -> RequestHeaders -> RequestHeaders)
-> Text -> Text -> ActionT e m ()
changeHeader forall a b. Eq a => a -> b -> [(a, b)] -> [(a, b)]
addIfNotPresent Text
"Content-Type" Text
"text/plain; charset=utf-8"
    forall (m :: * -> *) e. Monad m => ByteString -> ActionT e m ()
raw forall a b. (a -> b) -> a -> b
$ Text -> ByteString
encodeUtf8 Text
t

-- | Set the body of the response to the given 'T.Text' value. Also sets \"Content-Type\"
-- header to \"text/html; charset=utf-8\" if it has not already been set.
html :: (ScottyError e, Monad m) => T.Text -> ActionT e m ()
html :: forall e (m :: * -> *).
(ScottyError e, Monad m) =>
Text -> ActionT e m ()
html Text
t = do
    forall (m :: * -> *) e.
Monad m =>
(CI ByteString -> ByteString -> RequestHeaders -> RequestHeaders)
-> Text -> Text -> ActionT e m ()
changeHeader forall a b. Eq a => a -> b -> [(a, b)] -> [(a, b)]
addIfNotPresent Text
"Content-Type" Text
"text/html; charset=utf-8"
    forall (m :: * -> *) e. Monad m => ByteString -> ActionT e m ()
raw forall a b. (a -> b) -> a -> b
$ Text -> ByteString
encodeUtf8 Text
t

-- | 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 'Network.Wai.Handler.Warp.Internal.sendResponse').
file :: Monad m => FilePath -> ActionT e m ()
file :: forall (m :: * -> *) e. Monad m => String -> ActionT e m ()
file = forall e (m :: * -> *) a.
ExceptT
  (ActionError e) (ReaderT ActionEnv (StateT ScottyResponse m)) a
-> ActionT e m a
ActionT forall b c a. (b -> c) -> (a -> b) -> a -> c
. forall s (m :: * -> *). MonadState s m => (s -> s) -> m ()
MS.modify forall b c a. (b -> c) -> (a -> b) -> a -> c
. Content -> ScottyResponse -> ScottyResponse
setContent forall b c a. (b -> c) -> (a -> b) -> a -> c
. String -> Content
ContentFile

-- | 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.
json :: (A.ToJSON a, ScottyError e, Monad m) => a -> ActionT e m ()
json :: forall a e (m :: * -> *).
(ToJSON a, ScottyError e, Monad m) =>
a -> ActionT e m ()
json a
v = do
    forall (m :: * -> *) e.
Monad m =>
(CI ByteString -> ByteString -> RequestHeaders -> RequestHeaders)
-> Text -> Text -> ActionT e m ()
changeHeader forall a b. Eq a => a -> b -> [(a, b)] -> [(a, b)]
addIfNotPresent Text
"Content-Type" Text
"application/json; charset=utf-8"
    forall (m :: * -> *) e. Monad m => ByteString -> ActionT e m ()
raw forall a b. (a -> b) -> a -> b
$ forall a. ToJSON a => a -> ByteString
A.encode a
v

-- | 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'.
stream :: Monad m => StreamingBody -> ActionT e m ()
stream :: forall (m :: * -> *) e. Monad m => StreamingBody -> ActionT e m ()
stream = forall e (m :: * -> *) a.
ExceptT
  (ActionError e) (ReaderT ActionEnv (StateT ScottyResponse m)) a
-> ActionT e m a
ActionT forall b c a. (b -> c) -> (a -> b) -> a -> c
. forall s (m :: * -> *). MonadState s m => (s -> s) -> m ()
MS.modify forall b c a. (b -> c) -> (a -> b) -> a -> c
. Content -> ScottyResponse -> ScottyResponse
setContent forall b c a. (b -> c) -> (a -> b) -> a -> c
. StreamingBody -> Content
ContentStream

-- | Set the body of the response to the given 'BL.ByteString' value. Doesn't set the
-- \"Content-Type\" header, so you probably want to do that on your
-- own with 'setHeader'.
raw :: Monad m => BL.ByteString -> ActionT e m ()
raw :: forall (m :: * -> *) e. Monad m => ByteString -> ActionT e m ()
raw = forall e (m :: * -> *) a.
ExceptT
  (ActionError e) (ReaderT ActionEnv (StateT ScottyResponse m)) a
-> ActionT e m a
ActionT forall b c a. (b -> c) -> (a -> b) -> a -> c
. forall s (m :: * -> *). MonadState s m => (s -> s) -> m ()
MS.modify forall b c a. (b -> c) -> (a -> b) -> a -> c
. Content -> ScottyResponse -> ScottyResponse
setContent forall b c a. (b -> c) -> (a -> b) -> a -> c
. Builder -> Content
ContentBuilder forall b c a. (b -> c) -> (a -> b) -> a -> c
. ByteString -> Builder
fromLazyByteString