How would I make a proxy with wai and http-client that can stream server-sent events?

42 Views Asked by At

It seems like wai's responseStream should allow streaming server-sent events, but when I do

import qualified Network.HTTP.Client                  as H
import qualified Network.Wai                          as W
…
  respond $ W.responseStream 
                 (H.responseStatus response) 
                 (H.responseHeaders response) 
                 (H.responseBody response)

it still all comes as one response. I'm guessing it's H.responseBody that consumes it, but that's just a getter like Response body -> body – how do I make it proxy the stream?

1

There are 1 best solutions below

0
unhammer On

Found a solution via Streaming bytestring as WAI HTTP server response body (though without depending on Streaming):

…
    respond $ W.responseStream 
                   (H.responseStatus response) 
                   (H.responseHeaders response) 
                   (streamBody response)

-- type W.StreamingBody = (Builder -> IO ()) -> IO () -> IO ()
streamBody :: H.Response H.BodyReader -> W.StreamingBody
streamBody response writeBuilder flush = do
  chunk <- H.brRead (H.responseBody response)
  unless (S.null chunk) $ do
    writeBuilder (S.byteString chunk)
    flush
    streamBody response writeBuilder flush