From e371fb886f8fdf1599b0eb23765c575a365e2520 Mon Sep 17 00:00:00 2001 From: Alp Mestanogullari Date: Fri, 24 Apr 2015 12:37:33 +0200 Subject: [PATCH] add an example to show how to apply a WAI middleware --- servant-examples/servant-examples.cabal | 14 +++++ .../wai-middleware/wai-middleware.hs | 51 +++++++++++++++++++ 2 files changed, 65 insertions(+) create mode 100644 servant-examples/wai-middleware/wai-middleware.hs diff --git a/servant-examples/servant-examples.cabal b/servant-examples/servant-examples.cabal index 3c63b278..65a92b98 100644 --- a/servant-examples/servant-examples.cabal +++ b/servant-examples/servant-examples.cabal @@ -27,3 +27,17 @@ executable hackage , transformers hs-source-dirs: hackage default-language: Haskell2010 + +executable wai-middleware + main-is: wai-middleware.hs + build-depends: + aeson >= 0.8 + , base >= 4.7 + , servant + , servant-server + , text + , wai + , wai-extra + , warp + hs-source-dirs: wai-middleware + default-language: Haskell2010 diff --git a/servant-examples/wai-middleware/wai-middleware.hs b/servant-examples/wai-middleware/wai-middleware.hs new file mode 100644 index 00000000..ef772665 --- /dev/null +++ b/servant-examples/wai-middleware/wai-middleware.hs @@ -0,0 +1,51 @@ +{-# LANGUAGE DataKinds #-} +{-# LANGUAGE DeriveGeneric #-} +{-# LANGUAGE OverloadedStrings #-} +import Data.Aeson +import Data.Text +import GHC.Generics +import Network.Wai +import Network.Wai.Handler.Warp +import Network.Wai.Middleware.RequestLogger +import Servant + +data Product = Product + { name :: Text + , brand :: Text + , current_price_eur :: Double + , available :: Bool + } deriving (Eq, Show, Generic) + +instance ToJSON Product + +products :: [Product] +products = [p1, p2] + + where p1 = Product "Haskell laptop sticker" + "GHC Industries" + 2.50 + True + + p2 = Product "Foldable USB drive" + "Well-Typed" + 13.99 + False + +type SimpleAPI = Get '[JSON] [Product] + +simpleAPI :: Proxy SimpleAPI +simpleAPI = Proxy + +server :: Server SimpleAPI +server = return products + +-- logStdout :: Middleware +-- i.e, logStdout :: Application -> Application +-- serve :: Proxy api -> Server api -> Application +-- so applying a middleware is really as simple as +-- applying a function to the result of 'serve' +app :: Application +app = logStdout (serve simpleAPI server) + +main :: IO () +main = run 8080 app