From c92407620ab0eea4dc69e34bcfe144d148424193 Mon Sep 17 00:00:00 2001 From: Gregory Eremin Date: Sat, 29 Aug 2015 13:51:28 +0300 Subject: [PATCH] Add SetFlags and bootstrap functions --- confection.go | 42 +++++++++++++++++++++++++++++++++++++++--- file_ops.go | 4 +++- 2 files changed, 42 insertions(+), 4 deletions(-) diff --git a/confection.go b/confection.go index cb3b7cc..30c3711 100644 --- a/confection.go +++ b/confection.go @@ -2,16 +2,23 @@ package confection2 import ( "encoding/json" + "flag" "log" "reflect" ) var ( - // config stores application config. - config interface{} - callbacks = make(map[string][]func(oldVal, newVal interface{})) + config interface{} // config stores application config + configFile string + callbacks = make(map[string][]func(oldVal, newVal interface{})) + initialized bool ) +// SetFlags sets up Confection configuration flags. +func SetFlags() { + flag.StringVar(&configFile, "config", "config.json", "Path to config file") +} + // Manage accepts a pointer to a configuration struct. func Manage(target interface{}) { if ok := isStructPtr(target); !ok { @@ -27,6 +34,29 @@ func OnChange(field string, fun func(oldVal, newVal interface{})) { callbacks[field] = append(callbacks[field], fun) } +func bootstrap() { + if configFile == "" { + panic("path to config file is not set") + } + if fileExist(configFile) { + log.Println("Loading config file") + body, err := readFile(configFile) + if err != nil { + panic(err) + } + update(body) + } else { + log.Println("Config file not found, saving an empty one") + body, err := json.Marshal(config) + if err != nil { + panic(err) + } + if err = writeFile(configFile, body); err != nil { + panic(err) + } + } +} + func update(body []byte) { dupe := duplicate(config) if err := unmarshal(body, dupe); err != nil { @@ -41,6 +71,12 @@ func update(body []byte) { } func triggerCallbacks(oldConf, newConf interface{}) { + // Don't trigger callbacks on fist load + if !initialized { + initialized = true + return + } + return } diff --git a/file_ops.go b/file_ops.go index 5d49797..a078a3d 100644 --- a/file_ops.go +++ b/file_ops.go @@ -12,12 +12,14 @@ const ( filePerm = 0633 ) +var errFileNotExist = errors.New("Config file does not exist") + func readFile(file string) ([]byte, error) { if ok := fileExist(file); ok { return ioutil.ReadFile(file) } - return nil, errors.New("Config file does not exist") + return nil, errFileNotExist } func writeFile(file string, body []byte) error {