@@ -6,56 +6,27 @@ module Hakyll.Web.Preview.Server
66 ) where
77
88import Control.Monad.Trans (liftIO)
9−import Control.Applicative ((<$>))
10−import Codec.Binary.UTF8.String
11−import Network.HTTP.Base (urlDecode)
12−import System.FilePath ((</>))
13−import System.Directory (doesFileExist)
149
15−import qualified Data.ByteString as SB
16−import Snap.Util.FileServe (serveFile)
17−import Snap.Types (Snap, rqURI, getRequest, writeBS)
18−import Snap.Http.Server ( httpServe, setAccessLog, setErrorLog, addListen
19− , ConfigListen (..), emptyConfig
10+import Snap.Types (Snap)
11+import Snap.Util.FileServe ( DirectoryConfig (..), fancyDirectoryConfig
12+ , serveDirectoryWith
13+ )
14+import Snap.Http.Server ( httpServe, setAccessLog, setErrorLog
15+ , setPort, emptyConfig
2016 )
2117
22−import Hakyll.Core.Util.String (replaceAll)
23−
24−-- | The first file in the list that actually exists is returned
25−--
26−findFile :: [FilePath] -> IO (Maybe FilePath)
27−findFile [] = return Nothing
28−findFile (x : xs) = do
29− exists <- doesFileExist x
30− if exists then return (Just x) else findFile xs
31−
3218-- | Serve a given directory
3319--
3420static :: FilePath -- ^ Directory to serve
3521 -> (FilePath -> IO ()) -- ^ Pre-serve hook
3622 -> Snap ()
37−static directory preServe = do
38− -- Obtain the path
39− uri <- rqURI <$> getRequest
40− let filePath = replaceAll "\\?.*$" (const "") -- Remove trailing ?
41− $ replaceAll "#[^#]*$" (const "") -- Remove #section
42− $ replaceAll "^/" (const "") -- Remove leading /
43− $ urlDecode $ decode $ SB.unpack uri
44−
45− -- Try to find the requested file
46− r <- liftIO $ findFile $ map (directory </>) $
47− [ filePath
48− , filePath </> "index.htm"
49− , filePath </> "index.html"
50− ]
51−
52− case r of
53− -- Not found, error
54− Nothing -> writeBS "Not found"
55− -- Found, serve
56− Just f -> do
57− liftIO $ preServe f
58− serveFile f
23+static directory preServe =
24+ serveDirectoryWith directoryConfig directory
25+ where
26+ directoryConfig :: DirectoryConfig Snap
27+ directoryConfig = fancyDirectoryConfig
28+ { preServeHook = liftIO . preServe
29+ }
5930
6031-- | Main method, runs a static server in the given directory
6132--
@@ -67,7 +38,7 @@ staticServer directory preServe port =
6738 httpServe config $ static directory preServe
6839 where
6940 -- Snap server config
70− config = addListen (ListenHttp "0.0.0.0" port)
41+ config = setPort port
7142 $ setAccessLog Nothing
7243 $ setErrorLog Nothing
7344 $ emptyConfig