-- |
-- Copyright: © 2018-2020 IOHK
-- License: Apache-2.0
--
-- Provides a simple static files web server to be used as a fixture in tests
-- which need a HTTP server.

module Test.Utils.StaticServer
     ( withStaticServer
     ) where

import Prelude

import Network.Wai.Application.Static
    ( defaultFileServerSettings, staticApp )
import Network.Wai.Handler.Warp
    ( withApplication )

-- | Run a localhost HTTP file server on any free port, while executing the
-- given action.
withStaticServer
    :: FilePath
    -- ^ Web server root directory
    -> (String -> IO a)
    -- ^ Action, taking base URL
    -> IO a
withStaticServer :: FilePath -> (FilePath -> IO a) -> IO a
withStaticServer FilePath
root FilePath -> IO a
action =
    IO Application -> (Port -> IO a) -> IO a
forall a. IO Application -> (Port -> IO a) -> IO a
withApplication (Application -> IO Application
forall (f :: * -> *) a. Applicative f => a -> f a
pure Application
app) ((Port -> IO a) -> IO a) -> (Port -> IO a) -> IO a
forall a b. (a -> b) -> a -> b
$ \Port
port -> FilePath -> IO a
action (Port -> FilePath
forall a. Show a => a -> FilePath
baseUrl Port
port)
  where
    app :: Application
app = StaticSettings -> Application
staticApp (StaticSettings -> Application) -> StaticSettings -> Application
forall a b. (a -> b) -> a -> b
$ FilePath -> StaticSettings
defaultFileServerSettings FilePath
root
    baseUrl :: a -> FilePath
baseUrl a
port = FilePath
"http://localhost:" FilePath -> FilePath -> FilePath
forall a. Semigroup a => a -> a -> a
<> a -> FilePath
forall a. Show a => a -> FilePath
show a
port FilePath -> FilePath -> FilePath
forall a. Semigroup a => a -> a -> a
<> FilePath
"/"