{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}

-- | Serve generated static files with HTTP
module Rib.Server
  ( serve,
  )
where

import Network.Wai.Application.Static (defaultFileServerSettings, staticApp)
import qualified Network.Wai.Handler.Warp as Warp
import Relude

-- | Run a HTTP server to serve a directory of static files
--
-- Binds the server to host 127.0.0.1.
serve ::
  -- | Port number to bind to
  Int ->
  -- | Directory to serve.
  FilePath ->
  IO ()
serve :: Int -> FilePath -> IO ()
serve port :: Int
port path :: FilePath
path = do
  FilePath -> IO ()
forall (m :: * -> *). MonadIO m => FilePath -> m ()
putStrLn (FilePath -> IO ()) -> FilePath -> IO ()
forall a b. (a -> b) -> a -> b
$ "[Rib] Serving " FilePath -> FilePath -> FilePath
forall a. Semigroup a => a -> a -> a
<> FilePath
path FilePath -> FilePath -> FilePath
forall a. Semigroup a => a -> a -> a
<> " at http://" FilePath -> FilePath -> FilePath
forall a. Semigroup a => a -> a -> a
<> FilePath
host FilePath -> FilePath -> FilePath
forall a. Semigroup a => a -> a -> a
<> ":" FilePath -> FilePath -> FilePath
forall a. Semigroup a => a -> a -> a
<> Int -> FilePath
forall b a. (Show a, IsString b) => a -> b
show Int
port
  Settings -> Application -> IO ()
Warp.runSettings Settings
settings Application
app
  where
    app :: Application
app = StaticSettings -> Application
staticApp (StaticSettings -> Application) -> StaticSettings -> Application
forall a b. (a -> b) -> a -> b
$ FilePath -> StaticSettings
defaultFileServerSettings FilePath
path
    host :: FilePath
host = "127.0.0.1"
    settings :: Settings
settings =
      HostPreference -> Settings -> Settings
Warp.setHost (FilePath -> HostPreference
forall a. IsString a => FilePath -> a
fromString FilePath
host)
        (Settings -> Settings) -> Settings -> Settings
forall a b. (a -> b) -> a -> b
$ Int -> Settings -> Settings
Warp.setPort Int
port
        (Settings -> Settings) -> Settings -> Settings
forall a b. (a -> b) -> a -> b
$ Settings
Warp.defaultSettings