public
anonymous / gist:2229180
Created

Demonstration of Pipes for Web Programming

  • Download Gist
gistfile1.hs
Haskell
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
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
test
-}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.