From e81ac8fbc5dcf09268f2d8e0e9dbd4c0fda98cc3 Mon Sep 17 00:00:00 2001 From: Alp Mestanogullari Date: Wed, 6 May 2015 13:36:04 +0200 Subject: [PATCH] examples: add GS4 --- servant-examples/getting-started/GS4.hs | 63 +++++++++++++++++++ .../getting-started/getting-started.hs | 2 + servant-examples/servant-examples.cabal | 2 + 3 files changed, 67 insertions(+) create mode 100644 servant-examples/getting-started/GS4.hs diff --git a/servant-examples/getting-started/GS4.hs b/servant-examples/getting-started/GS4.hs new file mode 100644 index 00000000..89e7cce3 --- /dev/null +++ b/servant-examples/getting-started/GS4.hs @@ -0,0 +1,63 @@ +{-# LANGUAGE DataKinds #-} +{-# LANGUAGE TypeFamilies #-} +{-# LANGUAGE DeriveGeneric #-} +{-# LANGUAGE TypeOperators #-} +{-# LANGUAGE FlexibleInstances #-} +{-# LANGUAGE OverloadedStrings #-} +module GS4 where + +import Data.Aeson +import Data.Foldable (foldMap) +import GHC.Generics +import Lucid +import Network.Wai +import Servant +import Servant.HTML.Lucid + +data Person = Person + { firstName :: String + , lastName :: String + , age :: Int + } deriving Generic -- for the JSON instance + +-- JSON serialization +instance ToJSON Person + +-- HTML serialization of a single person +instance ToHtml Person where + toHtml p = + tr_ $ do + td_ (toHtml $ firstName p) + td_ (toHtml $ lastName p) + td_ (toHtml . show $ age p) + + toHtmlRaw = toHtml + +-- HTML serialization of a list of persons +instance ToHtml [Person] where + toHtml persons = table_ $ do + tr_ $ do + td_ "first name" + td_ "last name" + td_ "age" + + foldMap toHtml persons + + toHtmlRaw = toHtml + +persons :: [Person] +persons = + [ Person "Isaac" "Newton" 372 + , Person "Albert" "Einstein" 136 + ] + +type PersonAPI = "persons" :> Get '[JSON, HTML] [Person] + +personAPI :: Proxy PersonAPI +personAPI = Proxy + +server :: Server PersonAPI +server = return persons + +app :: Application +app = serve personAPI server diff --git a/servant-examples/getting-started/getting-started.hs b/servant-examples/getting-started/getting-started.hs index ec0e93df..f3a0ace1 100644 --- a/servant-examples/getting-started/getting-started.hs +++ b/servant-examples/getting-started/getting-started.hs @@ -5,12 +5,14 @@ import System.Environment import qualified GS1 import qualified GS2 import qualified GS3 +import qualified GS4 app :: String -> Maybe Application app n = case n of "1" -> Just GS1.app "2" -> Just GS2.app "3" -> Just GS3.app + "4" -> Just GS4.app _ -> Nothing main :: IO () diff --git a/servant-examples/servant-examples.cabal b/servant-examples/servant-examples.cabal index 4fc63834..2e7af148 100644 --- a/servant-examples/servant-examples.cabal +++ b/servant-examples/servant-examples.cabal @@ -20,7 +20,9 @@ executable getting-started aeson >= 0.8 , base >= 4.7 , either + , lucid , servant + , servant-lucid , servant-server , time , wai