module Hakyll.Web.Preview.Server
( staticServer
) where
import Control.Monad.Trans (liftIO)
import Control.Applicative ((<$>))
import Codec.Binary.UTF8.String
import Network.HTTP.Base (urlDecode)
import System.FilePath ((</>))
import System.Directory (doesFileExist)
import qualified Data.ByteString as SB
import Snap.Util.FileServe (serveFile)
import Snap.Types (Snap, rqURI, getRequest, writeBS)
import Snap.Http.Server ( httpServe, setAccessLog, setErrorLog, addListen
, ConfigListen (..), emptyConfig
)
import Hakyll.Core.Util.String (replaceAll)
findFile :: [FilePath] -> IO (Maybe FilePath)
findFile [] = return Nothing
findFile (x : xs) = do
exists <- doesFileExist x
if exists then return (Just x) else findFile xs
static :: FilePath
-> (FilePath -> IO ())
-> Snap ()
static directory preServe = do
uri <- rqURI <$> getRequest
let filePath = replaceAll "\\?$" (const "")
$ replaceAll "#[^#]*$" (const "")
$ replaceAll "^/" (const "")
$ urlDecode $ decode $ SB.unpack uri
r <- liftIO $ findFile $ map (directory </>) $
[ filePath
, filePath </> "index.htm"
, filePath </> "index.html"
]
case r of
Nothing -> writeBS "Not found"
Just f -> do
liftIO $ preServe f
serveFile f
staticServer :: FilePath
-> (FilePath -> IO ())
-> Int
-> IO ()
staticServer directory preServe port =
httpServe config $ static directory preServe
where
config = addListen (ListenHttp "0.0.0.0" port)
$ setAccessLog Nothing
$ setErrorLog Nothing
$ emptyConfig