How to deliver JSON over HTTP using Warp with Aeson

前端 未结 1 1839
深忆病人
深忆病人 2021-01-06 11:32

I want to create a high-performance HTTP-based API running on Haskell using warp as a HTTP backend.

The server shall return JSON data upon request. This data shall b

相关标签:
1条回答
  • 2021-01-06 11:56

    I'll build my example on the HaskellWiki minimal warp example.

    For the sake of simplicity I removed any code like routing, replacing the most relevant parts by stubs and comments where to place what.

    The JSON data we will serialize in this example is the list ["a","b","c"]. The same response (= the JSON) will be returned for any URL.

    The issue in connecting both libraries is that while warp requires a Blaze Builder to build its response properly, while Aeson returns (as you said) a lazy ByteString. The appropriate function to connect both together is called fromLazyByteString.

    {-# LANGUAGE OverloadedStrings #-}
    import Data.Aeson
    import Data.Text (Text)
    import Network.Wai
    import Network.Wai.Handler.Warp
    import Network.HTTP.Types (status200)
    import Network.HTTP.Types.Header (hContentType)
    import Blaze.ByteString.Builder.ByteString (fromLazyByteString)
    import qualified Data.ByteString.UTF8 as BU
    
    main = do
        let port = 3000
        putStrLn $ "Listening on port " ++ show port
        run port app
    
    app :: Application
    app req f = f $
        case pathInfo req of
            -- Place custom routes here
            _ -> anyRoute
    
    -- The data that will be converted to JSON
    jsonData = ["a","b","c"] :: [Text]
    
    anyRoute = responseLBS
                status200
                [(hContentType, "application/json")]
                (encode jsonData)
    

    Update 05/01/2015: Fix example for Warp/WAI 3.x

    0 讨论(0)
提交回复
热议问题