我正在使用Control.Monad.Managed
将pipes-http
的{{1}}包装在一个连续变换器中,但我还想在之后流式传输HTTP响应:
withHTTP
此处import Pipes
import Pipes.ByteString
import Pipes.HTTP
import Control.Applicative
import Control.Monad
import Control.Monad.Managed
import qualified Data.ByteString.Char8 as BC
type RespBody = BC.ByteString
managedHTTP :: Request -> Manager -> Managed (Response (Producer RespBody IO ()))
managedHTTP r m = managed (withHTTP r m)
fromHTTP :: Request -> Manager -> Producer RespBody IO ()
fromHTTP request manager = join $ liftIO $ fmap (hoist liftIO) $ with response return
where response = responseBody <$> managedHTTP request manager
旨在流出响应正文。如果以上运行:
fromHTTP
我在第一个块之后得到main = do
request <- parseUrl "http://en.wikipedia.org/"
manager <- newManager defaultManagerSettings
runEffect $ fromHTTP request manager >-> stdout
,因为recv: invalid argument (Bad file descriptor)
的{{1}}已经关闭了我的回复正文。
如果我想公开非http-client
样式的界面,我应该如何使用管道传输HTTP响应?
谢谢&amp;如果我严重误解延续和管道,请道歉。
答案 0 :(得分:1)
您对fromHTTP
的定义有点难以理解,但它显然让您在实际开始使用生产者之前退出托管环境。这样的事情可能更接近你的意图:
import Pipes
import Pipes.ByteString
import Pipes.HTTP
import Control.Applicative
import Control.Monad
import Control.Monad.Managed
import qualified Data.ByteString.Char8 as BC
type RespBody = BC.ByteString
managedHTTP :: Request -> Manager -> Managed (Response (Producer RespBody IO ()))
managedHTTP r m = managed (withHTTP r m)
managedManager :: ManagerSettings -> Managed Manager
managedManager settings = managed (withManager settings)
main = runManaged $
do request <- liftIO $ parseUrl "http://en.wikipedia.org/"
manager <- managedManager defaultManagerSettings
producer <- managedHTTP request manager
liftIO $ runEffect $ responseBody producer >-> stdout
或者只是废弃定义并写下
main = runManaged $
do request <- liftIO $ parseUrl "http://en.wikipedia.org/"
manager <- managed (withManager defaultManagerSettings)
producer <- managed (withHTTP request manager)
liftIO $ runEffect $ responseBody producer >-> stdout
请注意,您也可以让生产者在Managed
monad中运行:
main = runManaged $
do request <- liftIO $ parseUrl "http://en.wikipedia.org/"
manager <- managed (withManager defaultManagerSettings)
producer <- managed (withHTTP request manager)
runEffect $ hoist liftIO (responseBody producer) >-> stdout