Skip to content

Instantly share code, notes, and snippets.

@naoto-ogawa
Created February 19, 2017 04:12
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/85bbfcfb1e7014c63c9381f6c9201a10 to your computer and use it in GitHub Desktop.
Save naoto-ogawa/85bbfcfb1e7014c63c9381f6c9201a10 to your computer and use it in GitHub Desktop.
A simple servant sample of error
{-# 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 RetDiv = RetDiv { fst :: Double, snd :: Double, ret :: Double} deriving (Eq, Show, Generic)
instance ToJSON RetDiv
type MyAPI = "div" :> Capture "fst" Double :> Capture "snd" Double:> Get '[JSON] RetDiv
div' :: Double -> Double -> Handler RetDiv
div' f s = do
liftIO $ (putStrLn $ logDiv f s )
if s == 0
then throwError err400 {errBody="zero division"}
else return $ RetDiv f s (f/s)
logDiv :: Double -> Double -> String
logDiv f s = (show f) ++ "/" ++ (show s) ++ "=" ++ (show (f / s))
myServer :: Server MyAPI
myServer = div'
myProxy :: Proxy MyAPI
myProxy = Proxy
myApp :: Application
myApp = serve myProxy myServer
main :: IO ()
main = run 8081 myApp
@naoto-ogawa
Copy link
Author

$ curl -i http://127.0.0.1:8081/div/5/4
HTTP/1.1 200 OK
Transfer-Encoding: chunked
Date: Sat, 18 Feb 2017 11:30:30 GMT
Server: Warp/3.2.9
Content-Type: application/json

$ curl -i http://127.0.0.1:8081/div/5/0
HTTP/1.1 303 See Other
Transfer-Encoding: chunked
Date: Sat, 18 Feb 2017 11:31:12 GMT
Server: Warp/3.2.9

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment