Created
February 19, 2017 04:12
-
-
Save naoto-ogawa/85bbfcfb1e7014c63c9381f6c9201a10 to your computer and use it in GitHub Desktop.
A simple servant sample of error
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{-# 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 | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
$ 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