Created
March 12, 2017 05:24
-
-
Save naoto-ogawa/1e69e03f1c24d6ebb551935493813f25 to your computer and use it in GitHub Desktop.
a sample of reading a yaml file by Haskell
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{-# LANGUAGE OverloadedStrings #-} | |
{-# LANGUAGE DeriveGeneric #-} | |
import GHC.Generics | |
import Data.Yaml | |
import Control.Applicative | |
data Config = Config { app :: AppConfig, db :: DbConfig } deriving (Show, Generic) | |
data AppConfig = AppConfig { port :: Int } deriving (Show) | |
data DbConfig = DbConfig { user :: String, password :: String, database :: String} deriving (Show, Generic) | |
-- instance FromJSON Config where | |
-- parseJSON (Object o) = Config <$> | |
-- o .: "app" <*> | |
-- o .: "db" | |
-- parseJSON x = fail $ show x | |
instance FromJSON Config | |
instance FromJSON AppConfig where | |
parseJSON (Object m) = AppConfig <$> m .:? "port" .!= 8081 -- default | |
instance FromJSON DbConfig | |
readConfig :: IO Config | |
readConfig = | |
either (error . show) id <$> | |
decodeFileEither "./conf/conf.yaml" | |
main :: IO () | |
main = do | |
conf <- readConfig | |
putStrLn $ show conf | |
return () | |
-- | |
-- app : | |
-- port : | |
-- db : | |
-- user : "admin" | |
-- password : "pass" | |
-- database : "mydb" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment