Created
April 1, 2016 02:35
-
-
Save jdoiwork/f1944a08d93c61938effc83b8fd553f1 to your computer and use it in GitHub Desktop.
Network.Wai Middleware example
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
{-# 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 | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
IORef をなんとかしたい