Created
May 30, 2015 16:44
-
-
Save davenportw15/1b4b2001a124faf2b636 to your computer and use it in GitHub Desktop.
A journey into Haskell web development
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{-# 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