Create a gist now

Instantly share code, notes, and snippets.

anonymous /gist:2229180
Created Mar 28, 2012

Demonstration of Pipes for Web Programming
module Main where
import Prelude hiding (take)
import Control.Pipe
import Control.Pipe.Combinators hiding (take)
import Control.Pipe.Binary
import Data.ByteString hiding (take,cons)
import Data.ByteString.Char8 hiding (take,cons)
type Header = Int
requestSize :: Header -> Int
requestSize = id
main = runPipe (fileReader "input.txt" >+> webserver echoApp >+> fileWriter "output.txt")
echoApp :: Pipe ByteString ByteString IO ()
echoApp = idP
webserver :: Pipe ByteString ByteString IO a -> Pipe ByteString ByteString IO ()
webserver app = do
(header,rest) <- getHeader
cons rest >+> (take (requestSize header) >> return ()) >+> (app >> discard)
cons :: (Monad m) => a -> Pipe a a m r
cons x = yield x >> idP
getHeader :: Pipe ByteString ByteString IO (Header,ByteString)
getHeader = await >>= return . maybe (error "couldn't parse header") id . readInt
{- input.txt
13 hello this
is a
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment