• ¶
    #! /usr/bin/env nix-shell
    #! nix-shell -i runhaskell -p 'ghc.withPackages(pkgs: with pkgs; [Spock])'
    
    {-# LANGUAGE OverloadedStrings #-}
    
    import Data.Monoid
        ( (<>) )
    
    import Web.Spock
        ( SpockM, runSpock, spock, get, text
  • ¶

    read a request parameter (first from POST variables and then GET query parameters)

        , param
  • ¶

    like param above but throws an error if the request parameter is missing

        , param'
  • ¶
        )
    
    import Web.Spock.Config
        ( SpockCfg ( spc_csrfProtection )
        , PoolOrConn ( PCNoDatabase )
        , defaultSpockCfg
        )
    
    data AppSession = EmptySession
    data AppState = EmptyState
    
    main :: IO ()
    main = do
        defConfig <- defaultSpockCfg EmptySession PCNoDatabase EmptyState
        let config = defConfig { spc_csrfProtection = True }
        runSpock 5000 (spock config webapp)
    
    webapp :: SpockM () AppSession AppState ()
    webapp = do
  • ¶

    This route handles GET /hello and looks for a query parameter named name. We are forced to handle the absence of the name query parameter since param returns a Maybe.

    Try visiting:

    • http://localhost:5000/hello
    • http://localhost:5000/hello?name=Jonathan
        get "hello" $ do
            mName <- param "name"
            case mName of
                Nothing ->
                    text ("Hello stranger!  Sorry, I did not get your name.")
                Just name ->
                    text ("Hello " <> name <> "!  Nice to meet you.")
  • ¶

    This route handles GET /howdy and requires the name query parameter to be present. param' throws an error if the name query parameter is missing.

    Try visiting:

    • http://localhost:5000/howdy
    • http://localhost:5000/howdy?name=Jonathan
        get "howdy" $ do
            name <- param' "name"
            text ("Howdy " <> name <> "!  How goes it?")
  • ¶

    note: param and param' have a Typeclass constraint of FromHttpApiData. This means that you can use param and param' for any type that has instances of FromHttpApiData including your own! For the full list of types that have instances of FromHttpApiData check the docs here.