Skip to content

Instantly share code, notes, and snippets.

@edofic
Last active August 29, 2015 14:09
Show Gist options
  • Save edofic/25caf86b64ecdb01f58d to your computer and use it in GitHub Desktop.
Save edofic/25caf86b64ecdb01f58d to your computer and use it in GitHub Desktop.
a scotty server serving a file from disk and proxying a request (to itself)
module Main where
import Control.Monad (when, replicateM)
import Control.Monad.IO.Class (liftIO)
import qualified Data.ByteString as BS
import qualified Blaze.ByteString.Builder as B
import qualified Network.HTTP.Client as C
import Web.Scotty
chunkSize = 32 * 1024
totalSize = 1024 * 1024 * 1024
numChunks = totalSize `div` chunkSize
genChunk = BS.concat $ replicate (chunkSize `div` 16) ("01234567" :: BS.ByteString)
main = C.withManager C.defaultManagerSettings $ \manager ->
scotty 8000 $ do
get "/file" serveFile
get "/url" $ proxy manager
get "/gen" serveGenerated
serveFile = file "file"
proxy manager = do
response <- liftIO $ do
req <- C.parseUrl "http://localhost:8000/file"
C.responseOpen req manager
let bodyReader = fmap BS.concat $ replicateM 8 $ C.responseBody response
stream $ ioCopy bodyReader $ C.responseClose response
serveGenerated = stream $ \write flush ->
let step 0 = flush
step n = write (B.insertByteString genChunk) >> step (n-1)
in step $ numChunks
ioCopy reader close write flush = step >> flush where
step = do chunk <- reader
if (BS.length chunk > 0)
then (write $ B.insertByteString chunk) >> step
else close
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment