2015-05-15 12:58:12 +02:00
|
|
|
{-# LANGUAGE CPP #-}
|
2014-12-10 16:10:57 +01:00
|
|
|
-- | This module defines a sever-side handler that lets you serve static files.
|
|
|
|
--
|
|
|
|
-- - 'serveDirectory' lets you serve anything that lives under a particular
|
|
|
|
-- directory on your filesystem.
|
|
|
|
module Servant.Utils.StaticFiles (
|
|
|
|
serveDirectory,
|
|
|
|
) where
|
|
|
|
|
2015-05-15 12:58:12 +02:00
|
|
|
import Data.List (isSuffixOf)
|
2015-01-06 17:25:25 +01:00
|
|
|
import Network.Wai.Application.Static (staticApp, defaultFileServerSettings)
|
|
|
|
import Servant.API.Raw (Raw)
|
2015-03-09 15:16:38 +01:00
|
|
|
import Servant.Server (Server)
|
2015-05-15 12:58:12 +02:00
|
|
|
#if !MIN_VERSION_wai_app_static(3,1,0)
|
|
|
|
import Filesystem.Path.CurrentOS (decodeString)
|
|
|
|
#endif
|
2014-12-10 16:10:57 +01:00
|
|
|
|
|
|
|
-- | Serve anything under the specified directory as a 'Raw' endpoint.
|
|
|
|
--
|
|
|
|
-- @
|
|
|
|
-- type MyApi = "static" :> Raw
|
|
|
|
--
|
|
|
|
-- server :: Server MyApi
|
|
|
|
-- server = serveDirectory "\/var\/www"
|
|
|
|
-- @
|
|
|
|
--
|
|
|
|
-- would capture any request to @\/static\/\<something>@ and look for
|
|
|
|
-- @\<something>@ under @\/var\/www@.
|
|
|
|
--
|
|
|
|
-- It will do its best to guess the MIME type for that file, based on the extension,
|
|
|
|
-- and send an appropriate /Content-Type/ header if possible.
|
|
|
|
--
|
|
|
|
-- If your goal is to serve HTML, CSS and Javascript files that use the rest of the API
|
|
|
|
-- as a webapp backend, you will most likely not want the static files to be hidden
|
|
|
|
-- behind a /\/static\// prefix. In that case, remember to put the 'serveDirectory'
|
|
|
|
-- handler in the last position, because /servant/ will try to match the handlers
|
|
|
|
-- in order.
|
|
|
|
serveDirectory :: FilePath -> Server Raw
|
2015-05-15 12:58:12 +02:00
|
|
|
serveDirectory =
|
|
|
|
#if MIN_VERSION_wai_app_static(3,1,0)
|
|
|
|
staticApp . defaultFileServerSettings . mkSuff
|
|
|
|
#else
|
|
|
|
staticApp . defaultFileServerSettings . decodeString . mkSuff
|
|
|
|
#endif
|
|
|
|
where mkSuff x = if "/" `isSuffixOf` x then x else x ++ "/"
|