breve/src/Main.hs

76 lines
2.0 KiB
Haskell
Raw Permalink Normal View History

2019-11-07 10:12:28 +01:00
{-# LANGUAGE RecordWildCards #-}
2015-04-08 12:47:56 +02:00
2019-11-06 15:09:02 +01:00
{-|
This is the main module, which actually
run the Breve webserver.
-}
module Main where
2019-11-06 00:06:50 +01:00
-- Breve modules
import Application (AppEnv(..), breve, emptyApp)
import Breve.Settings (AppSettings(..), settings)
2015-05-09 22:24:33 +02:00
import Breve.UrlTable
2019-11-06 00:06:50 +01:00
-- Data conversions
import Data.String (IsString(..))
import Data.Maybe (listToMaybe)
import Data.Text (unpack)
2015-04-08 12:54:14 +02:00
2019-11-06 00:06:50 +01:00
-- IO
import Data.Text.IO as T
import Control.Exception as E
import Control.Monad (when, void)
import Control.Concurrent (forkIO)
import System.Environment (getArgs)
2015-04-08 12:47:56 +02:00
2019-11-06 00:06:50 +01:00
-- Web server
import Servant (Application)
2019-11-06 19:36:31 +01:00
import Network.Wai.Handler.Warp (run, defaultSettings, setPort, setHost)
import Network.Wai.Handler.WarpTLS (runTLS)
2015-08-11 04:02:10 +02:00
2019-11-06 00:06:50 +01:00
-- Middlewares
import Network.Wai.Middleware.RequestLogger (logStdout)
2019-11-06 19:36:31 +01:00
import Network.Wai.Middleware.ForceSSL (forceSSL)
2015-08-11 04:02:10 +02:00
2019-11-06 00:06:50 +01:00
-- * Helpers
2015-08-11 04:02:10 +02:00
2019-11-06 00:06:50 +01:00
-- | Runs Breve on the Warp webserver
2019-11-06 19:36:31 +01:00
runApp :: AppSettings -> Application -> IO ()
runApp (AppSettings{..}) =
2019-11-06 00:06:50 +01:00
runTLS tlsSettings warpSettings
where
host = unpack bindHost
warpSettings = setPort bindPort $
setHost (fromString host) defaultSettings
2015-08-11 04:02:10 +02:00
2019-11-06 00:06:50 +01:00
-- | Main
--
2019-11-06 15:09:02 +01:00
-- Reads the configuration (given as the unique cli argument),
-- sets things accordingly and runs the webserver.
2015-04-08 12:47:56 +02:00
main :: IO ()
2015-04-08 12:54:14 +02:00
main = do
2019-11-06 00:06:50 +01:00
configPath <- fmap listToMaybe getArgs
config@(AppSettings{..}) <- settings configPath
table <- load urlTable
2019-11-06 19:36:31 +01:00
-- Redirect from HTTP to HTTPS when listening
-- on the standard port
when (bindPort == 443) $ void $
forkIO (run 80 $ forceSSL emptyApp)
2019-11-06 21:33:03 +01:00
-- Save the table just before exiting
let exit E.UserInterrupt = save table urlTable
exit e = throwIO e
2019-11-06 19:36:31 +01:00
-- Middlewares are functions (Application -> Application).
-- We use one here to add requests
let middlewares = logStdout
2019-11-06 00:06:50 +01:00
-- The environment needed while running
let env = AppEnv bindUrl table staticDir
2019-11-06 21:33:03 +01:00
handle exit $ do
T.putStrLn ("Serving on " <> bindUrl)
runApp config (middlewares $ breve env)