Skip to content

Instantly share code, notes, and snippets.

@jdoiwork
Created April 1, 2016 02:35
Show Gist options
  • Save jdoiwork/f1944a08d93c61938effc83b8fd553f1 to your computer and use it in GitHub Desktop.
Save jdoiwork/f1944a08d93c61938effc83b8fd553f1 to your computer and use it in GitHub Desktop.
Network.Wai Middleware example
{-# LANGUAGE OverloadedStrings #-}
module Main where
import Network.Wai
import Network.HTTP.Types
import Network.Wai.Handler.Warp (run)
import qualified Data.ByteString.Lazy as LBS(fromStrict)
import qualified Data.ByteString as SBS(ByteString)
import qualified Data.ByteString.Char8 as SBS(snoc)
import Blaze.ByteString.Builder (toByteString)
import Data.IORef
myApp :: Application
myApp _ respond = do
respond $ responseLBS
status200
[("Content-Type", "text/plain")]
"hello"
myMiddleware :: Middleware
myMiddleware = modifyBody (`SBS.snoc` '!')
main :: IO ()
main = do
putStrLn $ "http://localhost:18080"
run 18080 $ myMiddleware myApp
--------------------------------------------------------------------------------
modifyBody :: (SBS.ByteString -> SBS.ByteString) -> Middleware
modifyBody cnv = modifyBodyIO cnvIO
where cnvIO = return . cnv
modifyBodyIO :: (SBS.ByteString -> IO SBS.ByteString) -> Middleware
modifyBodyIO cnvIO app req respond = do
app req $ \res -> do
ref <- newIORef ""
let (status, headers, applyWithBody) = responseToStream res
write = writeIORef ref . toByteString
flush = return ()
wb stbd = do
stbd write flush
body <- readIORef ref
LBS.fromStrict <$> cnvIO body
body <- applyWithBody wb
respond $ responseLBS status headers body
@jdoiwork
Copy link
Author

jdoiwork commented Apr 1, 2016

IORef をなんとかしたい

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment