Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #52 from Fransz/master
Fixed a cookbook item: Consume a webpage with http conduit
- Loading branch information
Showing
1 changed file
with
21 additions
and
18 deletions.
There are no files selected for viewing
39 changes: 21 additions & 18 deletions
39
cookbook/Consume-a-webpage-with-http-conduit-and-print-progress-along-the-way.md
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,23 +1,26 @@ | ||
```haskell | ||
import Control.Monad.IO.Class (liftIO) | ||
import qualified Data.ByteString as S | ||
import Data.Conduit | ||
import Data.Conduit.Binary as CB | ||
import Network.HTTP.Conduit | ||
import Conduit (ResourceT, runResourceT) | ||
import Control.Monad.IO.Class (liftIO) | ||
import qualified Data.ByteString as BS | ||
import Data.Conduit | ||
import Data.Conduit.Binary as CB | ||
import Network.HTTP.Conduit | ||
|
||
main :: IO () | ||
main = withManager $ \manager -> do | ||
req <- parseUrl "http://www.yesodweb.com/" | ||
res <- http req manager | ||
responseBody res $$+- printProgress =$ CB.sinkFile "yesodweb.html" | ||
main = do | ||
man <- newManager tlsManagerSettings | ||
req <- parseRequest "http://www.yesodweb.com/" | ||
runResourceT $ do | ||
res <- http req man | ||
sealConduitT (responseBody res) $$+- printProgress .| CB.sinkFile "yesodweb.html" | ||
|
||
printProgress :: Conduit S.ByteString (ResourceT IO) S.ByteString | ||
printProgress = | ||
loop 0 | ||
printProgress :: ConduitT BS.ByteString BS.ByteString (ResourceT IO) () | ||
printProgress = loop 0 | ||
where | ||
loop len = await >>= maybe (return ()) (\bs -> do | ||
let len' = len + S.length bs | ||
liftIO $ putStrLn $ "Bytes consumed: " ++ show len' | ||
yield bs | ||
loop len') | ||
``` | ||
loop len = await >>= maybe (return ()) (showConsumed len) | ||
showConsumed len bs = do | ||
let len' = len + BS.length bs | ||
liftIO $ putStrLn $ "bytes consumed " ++ show len' | ||
yield bs | ||
loop len' | ||
``` |