April 2012
Intermediate to advanced
294 pages
6h 27m
English
Let’s create a very simple web service: it takes a JSON request and returns a JSON
response. We’re going to write the server in WAI/Warp, and the client in http-conduit. We’ll be using aeson for
JSON parsing and rendering. We could also write the server in Yesod itself, but for such
a simple example, the extra features of Yesod don’t add much.
WAI uses the conduit package to handle streaming request
bodies, and efficiently generates responses using blaze-builder. aeson uses attoparsec for parsing; by using attoparsec-conduit we get easy interoperability with WAI. This plays out
as:
{-# LANGUAGE OverloadedStrings #-}importNetwork.Wai(Response,responseLBS,Application,requestBody)importNetwork.HTTP.Types(status200,status400)importNetwork.Wai.Handler.Warp(run)importData.Aeson.Parser(json)importData.Conduit.Attoparsec(sinkParser)importControl.Monad.IO.Class(liftIO)importData.Aeson(Value,encode,object,(.=))importControl.Exception(SomeException)importData.ByteString(ByteString)importData.Conduit(ResourceT,($$))importControl.Exception.Lifted(handle)main::IO()main=run3000appapp::Applicationappreq=handleinvalidJson$dovalue<-requestBodyreq$$sinkParserjsonnewValue<-liftIO$modValuevaluereturn$responseLBSstatus200[("Content-Type","application/json")]$encodenewValueinvalidJson::SomeException->ResourceTIOResponseinvalidJsonex=return$responseLBSstatus400[("Content-Type" ...
Read now
Unlock full access