mr-env-0.1.0.4: A simple way to read environment variables in Haskell

Copyright2020 Christian Rocha
LicenseMIT
Maintainerchristian@rocha.is
Stabilityexperimental
PortabilityPOSIX
Safe HaskellSafe
LanguageHaskell2010

System.Environment.MrEnv

Description

A simple way to read environment variables.

Synopsis

Documentation

Read environment variables with fallback values.

A simple example with do notation:

import System.Environment.MrEnv ( envAsBool, envAsInt, envAsInteger, envAsString )

main :: IO ()
main = do

    -- Get a string, with a fallback value if nothing is set.
    host <- envAsString "HOST" "localhost"

    -- Get an int. If you need an integer instead you could also use envAsInteger.
    port <- envAsInt "PORT" 8000

    -- Get a boolean. Here we're expecting the environment variable to read
    -- something along the lines of "true", "TRUE", "True", "truE" and so on.
    debug <- envAsBool "DEBUG" False

    putStrLn $
        "Let's connect to "
        ++ host
        ++ " on port "
        ++ show port
        ++ ". Debug mode is "
        ++ if debug then "on" else "off"
        ++ "."

You can also read into a record:

import System.Environment.MrEnv ( envAsBool, envAsInt, envAsInteger, envAsString )

data Config =
    Config { host  :: String
           , port  :: Int
           , debug :: Bool
           }

getConfig :: IO Config
getConfig = Config
    <$> envAsString "HOST" "localhost"
    <*> envAsInt "PORT" 8000
    <*> envAsBool "DEBUG" False

main :: IO ()
main =
    getConfig >>= conf ->
        putStrLn $
            "Let's connect to "
            ++ host conf
            ++ " on port "
            ++ show $ port conf
            ++ ". Debug mode is "
            ++ if debug conf then "on" else "off"
            ++ "."

envAsBool Source #

Arguments

:: String

Name of environment variable

-> Bool

Fallback value

-> IO Bool

Result

Get an environment variable as a boolean, with a fallback value.

Internally we use this instead of envAs @Bool, as it handles nonstandard capitalization.

envAsInt Source #

Arguments

:: String

Name of environment variable

-> Int

Fallback value

-> IO Int

Result

Get an environment variable as an Int, with a fallback value.

envAsInteger Source #

Arguments

:: String

Name of environment variable

-> Integer

Fallback value

-> IO Integer

Result

Get an environment variable as an Integer, with a fallback value.

envAsString Source #

Arguments

:: String

Name of environment variable

-> String

Fallback value

-> IO String

Result

Get an environment variable as a String, with a fallback value.

Internally we use this instead of envAs @String, because readMaybe fails unless Strings are doubly-quoted (i.e. '""value""'.