[英]Haskell conduit: How to send data downstream while producing a monadic value
我想編寫一個代理,它會收到一個標頭,指示目標 IP、端口等。
所以我有這樣的事情:
getHeader = do
Just x <- await
let (a, rest) = splitAt headerLen x
return $ parseHeader a
-- how to send the rest data downstream ??
(resume, header) <- clientSource $$+ getHeader
-- do something according to the header
問題是,有時候header和后面的數據是一起發送的,所以getHeader
會消耗后面的數據,本來應該被后面的管道消耗掉。 那么我怎樣才能向下游發送rest
呢?
您還可以考慮使用包裝在管道中的解析器,例如Data.Conduit.Attoparsec
-extra 中的Data.Conduit.Attoparsec
。 包裝器負責根據需要請求盡可能多的輸入部分(在您的情況下,第一部分可能比headerLen
短),並處理剩余部分:
import Control.Monad.Catch
import qualified Data.Attoparsec.ByteString as P
import Data.Attoparsec.Types
import qualified Data.ByteString as BS
import Data.Conduit
import Data.Conduit.Attoparsec
parseHeader :: Parser BS.ByteString BS.ByteString
parseHeader = P.take headerLen -- do whatever parsing you need to get the header
where
headerLen = 42
consumerHeader :: (MonadThrow m) => Consumer BS.ByteString m BS.ByteString
consumerHeader = sinkParser parseHeader
Consumer
被定義為
type Consumer i m r = forall o. ConduitM i o m r
所以consumerHeader
將ByteString
作為輸入,在輸出和 monad 中是多態的,並返回解析后的ByteString
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.