diff --git a/config/config.go b/config/config.go index 184c04c7c..882489e50 100644 --- a/config/config.go +++ b/config/config.go @@ -1,53 +1,77 @@ package config import ( + "errors" "io/ioutil" - "launchpad.net/goyaml" "log" "os" "sync" + + "launchpad.net/goyaml" ) -var config map[string]interface{} -var lock sync.RWMutex -var loaded bool - -func ensureLoaded() { - if !loaded { - loadConfig() - } +type Config struct { + config map[string]interface{} + lock sync.RWMutex + loaded bool } -func loadConfig() { - config = make(map[string]interface{}) +var config *Config + +func init() { config_file := os.Getenv("PILOSA_CONFIG") if config_file == "" { config_file = "pilosa.yaml" } - data, err := ioutil.ReadFile(config_file) + var err error + config, err = NewConfig(config_file) if err != nil { - log.Fatal("Problem with config file. ", err) + log.Fatal(err) } - goyaml.Unmarshal(data, &config) } func GetSafe(key string) (interface{}, bool) { - lock.RLock() - ensureLoaded() - defer lock.RUnlock() - value, ok := config[key] - return value, ok + return config.GetSafe(key) } func Get(key string) interface{} { - lock.RLock() - ensureLoaded() - defer lock.RUnlock() - return config[key] + return config.Get(key) } func GetInt(key string) int { - value, ok := GetSafe(key) + return config.GetInt(key) +} + +func GetString(key string) string { + return config.GetString(key) +} + +func NewConfig(filename string) (*Config, error) { + self := Config{} + self.config = make(map[string]interface{}) + data, err := ioutil.ReadFile(filename) + if err != nil { + return nil, errors.New("Problem with config file: " + err.Error()) + } + goyaml.Unmarshal(data, self.config) + return &self, nil +} + +func (self *Config) GetSafe(key string) (interface{}, bool) { + self.lock.RLock() + defer self.lock.RUnlock() + value, ok := self.config[key] + return value, ok +} + +func (self *Config) Get(key string) interface{} { + self.lock.RLock() + defer self.lock.RUnlock() + return self.config[key] +} + +func (self *Config) GetInt(key string) int { + value, ok := self.GetSafe(key) if ok { value_int, ok := value.(int) if ok { @@ -57,8 +81,8 @@ func GetInt(key string) int { return 0 } -func GetString(key string) string { - value, ok := GetSafe(key) +func (self *Config) GetString(key string) string { + value, ok := self.GetSafe(key) if ok { value_string, ok := value.(string) if ok { diff --git a/config/config_test.go b/config/config_test.go index 635d2e562..af25d2c82 100644 --- a/config/config_test.go +++ b/config/config_test.go @@ -1,9 +1,9 @@ package config import ( - . "github.com/smartystreets/goconvey/convey" "os" "testing" + . "github.com/smartystreets/goconvey/convey" ) func TestConfig(t *testing.T) {