Le Nguyen The Dat bio photo

Le Nguyen The Dat

~ Data Science & Engineering

Twitter Facebook LinkedIn Github
Sample config files:
  • app:
    port: 9000
    limit: 100
    db:
    host: "my.database.com"
    port: 5439
    user: "admin"
    database: "mydb"
    s3:
    bucket: "my-s3-bucket"
    access: "ABASDSAMPLEACESSKEY"
    secret: "312312YASDASAMPLESECRETKEY"

Import necessary modules:
  • import Control.Applicative
    import Data.Yaml -- you need to install yaml beforehand with cabal

Define your config data type:
  • data MyConfig = MyConfig {
    app :: AppConfig,
    db :: DbConfig,
    s3 :: S3Config
    } deriving Show
    data AppConfig = AppConfig {
    port :: Int,
    limit :: Int
    } deriving Show
    data DbConfig = DbConfig {
    host :: String,
    port :: Int,
    user :: String,
    database :: String
    } deriving Show
    data S3Config = S3Config {
    bucket :: String,
    access :: String,
    secret :: String
    } deriving Show

Define your config data types as instances of FromJSON - for parsing purpose:
  • instance FromJSON MyConfig where
    parseJSON (Object m) = MyConfig <$>
    m .: "app" <*>
    m .: "db" <*>
    m .: "s3"
    parseJSON x = fail ("not an object: " ++ show x)
    instance FromJSON AppConfig where
    parseJSON (Object m) = AppConfig <$>
    m .: "port" <*>
    m .: "limit"
    parseJSON x = fail ("not an object: " ++ show x)
    instance FromJSON DbConfig where
    parseJSON (Object m) = DbConfig <$>
    m .: "host" <*>
    m .: "port" <*>
    m .: "user" <*>
    m .: "database"
    parseJSON x = fail ("not an object: " ++ show x)
    instance FromJSON S3Config where
    parseJSON (Object m) = S3Config <$>
    m .: "bucket" <*>
    m .: "access" <*>
    m .: "secret"
    parseJSON x = fail ("not an object: " ++ show x)

Finally, to read the given config file:
  • readMyConfig :: IO MyConfig
    readMyConfig =
    either (error . show) id <$>
    decodeFileEither "./Config/myconfig.cfg"