2015-08-17 23:56:29 +02:00
|
|
|
{-# LANGUAGE DataKinds #-}
|
|
|
|
{-# LANGUAGE DeriveGeneric #-}
|
2014-12-10 16:10:57 +01:00
|
|
|
{-# LANGUAGE OverloadedStrings #-}
|
2015-08-17 23:56:29 +02:00
|
|
|
{-# LANGUAGE PolyKinds #-}
|
|
|
|
{-# LANGUAGE TypeFamilies #-}
|
|
|
|
{-# LANGUAGE TypeOperators #-}
|
|
|
|
|
|
|
|
import Data.Aeson
|
|
|
|
import Data.Monoid
|
|
|
|
import Data.Proxy
|
|
|
|
import Data.Text
|
|
|
|
import GHC.Generics
|
|
|
|
import Network.Wai
|
|
|
|
import Network.Wai.Handler.Warp
|
|
|
|
|
|
|
|
import Servant
|
2014-12-10 16:10:57 +01:00
|
|
|
|
|
|
|
-- * Example
|
|
|
|
|
|
|
|
-- | A greet message data type
|
2015-01-13 20:40:41 +01:00
|
|
|
newtype Greet = Greet { _msg :: Text }
|
2014-12-10 16:10:57 +01:00
|
|
|
deriving (Generic, Show)
|
|
|
|
|
|
|
|
instance FromJSON Greet
|
|
|
|
instance ToJSON Greet
|
|
|
|
|
|
|
|
-- API specification
|
|
|
|
type TestApi =
|
|
|
|
-- GET /hello/:name?capital={true, false} returns a Greet as JSON
|
2015-01-13 20:40:41 +01:00
|
|
|
"hello" :> Capture "name" Text :> QueryParam "capital" Bool :> Get '[JSON] Greet
|
2014-12-10 16:10:57 +01:00
|
|
|
|
|
|
|
-- POST /greet with a Greet as JSON in the request body,
|
|
|
|
-- returns a Greet as JSON
|
2015-01-13 20:40:41 +01:00
|
|
|
:<|> "greet" :> ReqBody '[JSON] Greet :> Post '[JSON] Greet
|
2014-12-10 16:10:57 +01:00
|
|
|
|
|
|
|
-- DELETE /greet/:greetid
|
2015-05-06 21:21:35 +02:00
|
|
|
:<|> "greet" :> Capture "greetid" Text :> Delete '[JSON] ()
|
2014-12-10 16:10:57 +01:00
|
|
|
|
|
|
|
testApi :: Proxy TestApi
|
|
|
|
testApi = Proxy
|
|
|
|
|
|
|
|
-- Server-side handlers.
|
|
|
|
--
|
|
|
|
-- There's one handler per endpoint, which, just like in the type
|
|
|
|
-- that represents the API, are glued together using :<|>.
|
|
|
|
--
|
2015-09-12 14:11:24 +02:00
|
|
|
-- Each handler runs in the 'ExceptT ServantErr IO' monad.
|
2014-12-10 16:10:57 +01:00
|
|
|
server :: Server TestApi
|
|
|
|
server = helloH :<|> postGreetH :<|> deleteGreetH
|
|
|
|
|
|
|
|
where helloH name Nothing = helloH name (Just False)
|
|
|
|
helloH name (Just False) = return . Greet $ "Hello, " <> name
|
|
|
|
helloH name (Just True) = return . Greet . toUpper $ "Hello, " <> name
|
|
|
|
|
|
|
|
postGreetH greet = return greet
|
|
|
|
|
|
|
|
deleteGreetH _ = return ()
|
|
|
|
|
|
|
|
-- Turn the server into a WAI app. 'serve' is provided by servant,
|
|
|
|
-- more precisely by the Servant.Server module.
|
|
|
|
test :: Application
|
2015-12-26 14:32:43 +01:00
|
|
|
test = serve testApi EmptyConfig server
|
2014-12-10 16:10:57 +01:00
|
|
|
|
|
|
|
-- Run the server.
|
|
|
|
--
|
|
|
|
-- 'run' comes from Network.Wai.Handler.Warp
|
|
|
|
runTestServer :: Port -> IO ()
|
|
|
|
runTestServer port = run port test
|
|
|
|
|
|
|
|
-- Put this all to work!
|
|
|
|
main :: IO ()
|
|
|
|
main = runTestServer 8001
|