-
Notifications
You must be signed in to change notification settings - Fork 38
/
04-Accept.hs
63 lines (48 loc) · 1.62 KB
/
04-Accept.hs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE OverloadedStrings #-}
-- An endpoint can deliver data in different formats. The Accept sent
-- by the cliet header is used to determine the correct format.
import Servant
import Network.Wai (Application)
import Network.Wai.Middleware.RequestLogger (logStdoutDev)
import Network.Wai.Handler.Warp (run)
import GHC.Generics
import Data.Aeson
import qualified Data.ByteString.Lazy.Char8 as BC
type PairsEndpoint = "pairs" :> Get '[PlainText, JSON] [Pair]
type API = "hello" :> Get '[JSON] String
:<|> "numbers" :> Get '[JSON] [Int]
:<|> PairsEndpoint
helloServer = return "Hello World!"
numberServer = return [1..17]
data Pair = Pair
{ x :: Int
, y :: Int
} deriving (Eq, Show, Generic)
instance ToJSON Pair
instance MimeRender PlainText a => MimeRender PlainText [a] where
mimeRender p xs = BC.intercalate ", " (map (mimeRender p) xs)
instance MimeRender PlainText Pair where
mimeRender _ = BC.pack . show
pairServer :: Server PairsEndpoint
pairServer = return [Pair 10 20, Pair 1 2]
server :: Server API
server = helloServer
:<|> numberServer
:<|> pairServer
proxy :: Proxy API
proxy = Proxy
app :: Application
app = serve proxy server
main :: IO ()
main = do
putStrLn "Server endpoints:"
putStrLn " http://localhost:8000/hello/"
putStrLn " http://localhost:8000/numbers/"
putStrLn " http://localhost:8000/pairs/ (application/json, text/plain)"
run 8000 $ logStdoutDev $ app