【问题标题】:conduit http streaming to file (sinkFile) avoid file creation when http returns error管道 http 流式传输到文件 (sinkFile) 避免在 http 返回错误时创建文件
【发布时间】:2018-06-11 14:36:26
【问题描述】:

当 http 代码不成功并且我希望 创建文件时,我需要从 getSrc 返回什么值(通过 sinkFile
如果我只是返回 getResponseBody res,则 http 错误本身会保存到文件中。

downloadURL :: String -> FilePath -> IO ()
downloadURL url location = do
  request <- parseRequest url
  runResourceT
         $ runConduit$  httpSource request getSrc
         .| sinkFile location
   where
     getSrc res = do
         let success = statusIsSuccessful . getResponseStatus $ res
         if success then
            getResponseBody res
         else
            ???

【问题讨论】:

  • 你想做什么?

标签: haskell conduit


【解决方案1】:

据我了解,如果响应成功,您希望将响应正文通过管道传输到某个管道,并在响应不成功时将其传输到备用管道。

我相信最简单的解决方案是使用您的代码中已有的if ... then ... else“选择”一个管道 - 类似于

module Main where

import Conduit ( printC
               )
import Data.Conduit ( runConduitRes
                    , (.|)
                    , yield
                    )
import Data.Conduit.Binary ( sinkFile
                           )
import Network.HTTP.Simple ( parseRequest
                           , httpSource
                           , getResponseStatus
                           , getResponseBody
                           )
import Network.HTTP.Types.Status ( statusIsSuccessful
                                 )

main :: IO ()
main = do
  requestText <- init <$> readFile "notes/request.txt"
  downloadURL requestText "notes/sink.txt"

downloadURL :: String -> FilePath -> IO ()
downloadURL url location = do
  request <- parseRequest url
  runConduitRes (httpSource request processResponse)
    where
  processResponse response =
    if statusIsSuccessful (getResponseStatus response)
    then (getResponseBody response) .| sinkFile location 
    else yield "an alternate operation" .| printC

您可以将yield "an alternate operation" .| printC 替换为另一个可以满足您实际需要的管道。

请注意,现在sinkFile location 仅在成功案例中执行,因此失败案例不会创建任何文件。

【讨论】:

    【解决方案2】:

    Kartin 的解决方案应该可以正常工作。您可以采取的另一种方法是使用sinkFileCautious 而不是sinkFile,并在无效状态代码上引发运行时异常。实际上,您可以将 parseRequest 替换为 parseUrlThrow 以自动获取此行为。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-02-16
      • 1970-01-01
      • 2017-03-08
      • 2011-12-30
      • 1970-01-01
      • 1970-01-01
      • 2017-02-16
      相关资源
      最近更新 更多