Create a gist now

Instantly share code, notes, and snippets.

A simple servant sample of Capture
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeOperators #-}
import Control.Monad.IO.Class -- liftIO
import Control.Monad.Trans.Except -- Handler
import Data.Aeson.Types -- JSON
import Data.Aeson.Parser -- JSON
import GHC.Generics
import Network.Wai.Handler.Warp
import Servant
data RetSum = RetSum { fst :: Int, snd :: Int, ret :: Int} deriving (Eq, Show, Generic)
instance ToJSON RetSum
type MyAPI = "add" :> Capture "fst" Int :> Capture "snd" Int :> Get '[JSON] RetSum
-- add' :: Int -> Int -> ExceptT ServantErr IO RetSum -- Handler == ExceptT ServantError IO
add' :: Int -> Int -> Handler RetSum
add' f s = do
liftIO $ (putStrLn $ logAdd f s )
return $ RetSum f s (f+s)
logAdd :: Int -> Int -> String
logAdd f s = (show f) ++ "+" ++ (show s) ++ "=" ++ (show (f + s))
myServer :: Server MyAPI
myServer = add'
myProxy :: Proxy MyAPI
myProxy = Proxy
myApp :: Application
myApp = serve myProxy myServer
main :: IO ()
main = run 8081 myApp
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment