@@ -0,0 +1,34 @@
1+{-# LANGUAGE OverloadedStrings #-}
2+module Network.Wai.Middleware.Rewrite
3+ ( rewrite, autoHtmlRewrite
4+ ) where
5+
6+import Network.Wai
7+import qualified Data.ByteString.Char8 as B
8+import System.Directory (doesFileExist)
9+import Control.Monad.IO.Class (liftIO)
10+import Web.Routes.Base (decodePathInfo)
11+
12+-- | rewrite based on your own conversion rules
13+-- Example usage: rewrite (autoHtmlRewrite "static")
14+rewrite :: (B.ByteString -> IO B.ByteString) -> Middleware
15+rewrite convert app req = do
16+ newPathInfo <- liftIO $ convert $ pathInfo req
17+ app req { pathInfo = newPathInfo }
18+
19+-- | example rewriter
20+-- implements 2 rules for static html re-writes
21+-- 1) for a directory foo/, check for foo/index.html
22+-- 2) for a non-directory bar, check for bar.html
23+-- if the file exists, do the rewrite
24+autoHtmlRewrite :: String -> B.ByteString -> IO B.ByteString
25+autoHtmlRewrite staticDir pInfo = do
26+ fe <- doesFileExist $ staticDir ++ "/" ++ reWritePath
27+ return $ if fe then B.pack reWritePath else pInfo
28+ where
29+ reWritePath = concat $ map ((:) '/') reWritePieces
30+ pieces = decodePathInfo $ B.unpack $ pInfo
31+ reWritePieces =
32+ if (null pieces) || (null $ last pieces)
33+ then pieces ++ ["index.html"]
34+ else (init pieces) ++ [(last pieces) ++ ".html"]