Add SetFlags and bootstrap functions
This commit is contained in:
parent
277d90ed06
commit
c92407620a
|
@ -2,16 +2,23 @@ package confection2
|
|||
|
||||
import (
|
||||
"encoding/json"
|
||||
"flag"
|
||||
"log"
|
||||
"reflect"
|
||||
)
|
||||
|
||||
var (
|
||||
// config stores application config.
|
||||
config 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
|
||||
}
|
||||
|
||||
|
|
|
@ -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 {
|
||||
|
|
Loading…
Reference in New Issue