How to read response body in WAI middleware?

533 Views Asked by At

I'm trying to create some middleware that will send 500 errors to a remote server. The error information is in the response body.

How can I get the response body from a Response as any kind of string? I see responseToStream but I can't figure out how to use it.

import Network.Wai
import Data.ByteString.Lazy (ByteString)

responseBody :: Response -> IO ByteString
responseBody res = _
1

There are 1 best solutions below

0
On

An implementation of the comment by @user2407038:

import Data.IORef (newIORef,modifyIORef',readIORef)
import Data.Monoid ((<>))
import Data.ByteString.Lazy (ByteString)
import Data.ByteString.Builder (toLazyByteString)

import Network.Wai

responseBody :: Response -> IO ByteString
responseBody res =
  let (status,headers,body) = responseToStream res in
  body $ \f -> do
    content <- newIORef mempty
    f (\chunk -> modifyIORef' content (<> chunk)) (return ())
    toLazyByteString <$> readIORef content