Create a gist now

Instantly share code, notes, and snippets.

Servant Form Sample
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeOperators #-}
import GHC.Generics
import Control.Monad.IO.Class -- liftIO
import Control.Monad.Trans.Except -- Handler
import Data.Aeson.Types -- JSON
import Data.Aeson.Parser -- JSON
import Servant
import Network.Wai.Handler.Warp
import Web.Internal.FormUrlEncoded
data Req = Req { x :: Int, y :: Int} deriving (Eq, Show, Generic)
data Res = Res { ret :: Int} deriving (Eq, Show, Generic)
instance FromForm Req
instance ToJSON Res
type MyAPI = "add" :> ReqBody '[FormUrlEncoded] Req :> Post '[JSON] Res
add' :: Req -> Handler Res
add' req = do
liftIO $ putStrLn $ logAdd (x req) (y req)
return $ Res { ret = (x req) + (y req) }
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