package main
+import (
+ "errors"
+ "fmt"
+ "github.com/alyu/configparser"
+ "os"
+ "strconv"
+)
+
type qwConfig struct {
- user, pass, dbName, efsBasePath string
+ user, pass, dbName string
+ basePath string
+ port int
+}
+
+func checkedSection(config *configparser.Configuration, name string) (*configparser.Section, error) {
+ section, err := config.Section(name)
+ if nil != err {
+ fmt.Println("ERROR! Could not locate section [" + name + "] in config file:", err)
+ return nil, err
+ }
+ return section, nil
+}
+
+func checkedValue(section *configparser.Section, name string) (string, error) {
+ if ! section.Exists(name) {
+ return "", errors.New("ERROR! Value named \"" + name + "\" not found in config file.")
+ }
+
+ value := section.ValueOf(name)
+ return value, nil
+}
+
+// Note: Will exit if config cannot be loaded
+func GetConfig() (*qwConfig) {
+ config, err := loadConfig()
+ if nil != err {
+ fmt.Println("FATAL! Cannot load config. Unable to continue.", err)
+ os.Exit(1)
+ }
+
+ return config
}
-func getConfig() qwConfig {
- // TODO: use a real password, and load config info from a file
- return qwConfig{user:"quanlib", pass:"quanlib", dbName:"quanlib", efsBasePath:"/arc/quanlib/efs"}
+func loadConfig() (*qwConfig, error) {
+ // TODO: Make the path to the config file configurable (environment variable?)
+ // TODO: Load the config file once, and cache the values for subsequent getConfig() calls
+
+ const configFile = "quanlib.ini"
+
+ config, err := configparser.Read(configFile)
+ if nil != err {
+ fmt.Println("ERROR! Failed to read config file:", configFile, err)
+ return nil, err
+ }
+
+ var section *configparser.Section
+
+ // ------------------
+ // Section: database
+
+ var dbName, user, pass string
+
+ section, err = checkedSection(config, "database")
+ if nil != err {
+ return nil, err
+ }
+
+ dbName, err = checkedValue(section, "name")
+ if nil != err {
+ return nil, err
+ }
+
+ user, err = checkedValue(section, "user")
+ if nil != err {
+ return nil, err
+ }
+
+ pass, err = checkedValue(section, "pass")
+ if nil != err {
+ return nil, err
+ }
+
+ // --------------------
+ // Section: filesystem
+
+ var basePath string
+
+ section, err = checkedSection(config, "filesystem")
+ if nil != err {
+ return nil, err
+ }
+
+ basePath, err = checkedValue(section, "basePath")
+ if nil != err {
+ return nil, err
+ }
+
+ // -------------
+ // Section: web
+
+ var port int
+ var portStr string
+
+ section, err = checkedSection(config, "web")
+ if nil != err {
+ return nil, err
+ }
+
+ portStr, err = checkedValue(section, "port")
+ if nil != err {
+ return nil, err
+ }
+ port, err = strconv.Atoi(portStr)
+ if nil != err {
+ return nil, err
+ }
+
+ return &qwConfig{ user:user, pass:pass, dbName:dbName,
+ basePath:basePath,
+ port:port },
+ nil
}