Skip to content

Instantly share code, notes, and snippets.

@naoto-ogawa
Created March 5, 2017 02:30
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/11dffa725e27841fccaa8265332c7834 to your computer and use it in GitHub Desktop.
Save naoto-ogawa/11dffa725e27841fccaa8265332c7834 to your computer and use it in GitHub Desktop.
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