Skip to content

Instantly share code, notes, and snippets.

@naoto-ogawa
Created February 19, 2017 04:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save naoto-ogawa/0353479d57101e3031dee5b6a7f00eb6 to your computer and use it in GitHub Desktop.
Save naoto-ogawa/0353479d57101e3031dee5b6a7f00eb6 to your computer and use it in GitHub Desktop.
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