Skip to content

Instantly share code, notes, and snippets.

@davenportw15
Created May 30, 2015 16:44
Show Gist options
  • Save davenportw15/1b4b2001a124faf2b636 to your computer and use it in GitHub Desktop.
Save davenportw15/1b4b2001a124faf2b636 to your computer and use it in GitHub Desktop.
A journey into Haskell web development
{-# LANGUAGE OverloadedStrings #-}
-- Ignore all the redundant string conversions
-- There's probably a better way to do it
import Control.Applicative
import qualified Data.Text as Text
import Data.ByteString.Lazy.Char8 (unpack)
import Web.Spock.Safe
import Data.Aeson
-- Router
main = do
runSpock 3000 $ spockT id $ do
-- Writes hello when visiting /
get root $
text "hello"
-- Squares `n` in /square/n
get ("square" <//> var) $ \number ->
let intValue = read number in
text $ Text.pack $ show (intValue ^ 2)
-- Returns the JSON instance of a user with /user/name/password
get ("user" <//> var <//> var) $ \username password ->
let user = User username password in
text $ Text.pack $ unpack $ encode user
data User = User { username :: Text.Text
, password :: Text.Text
} deriving (Show, Read, Eq)
-- JSON conversions
instance ToJSON User where
toJSON (User username password) =
object [ "username" .= username
, "password" .= password
]
instance FromJSON User where
parseJSON (Object v) =
User <$> v .: "username"
<*> v .: "password"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment