From 068d1d1ba94193a7fc9cee2e3f4d20487dedb4ab Mon Sep 17 00:00:00 2001 From: Harshavardhana Date: Thu, 20 Aug 2015 20:33:49 -0700 Subject: [PATCH] Add a new quick.Load() function to load directly any config file provided a quick compatible struct{} is also provided --- pkg/quick/quick.go | 41 +++++++++++++++++++++++++++++++++++------ 1 file changed, 35 insertions(+), 6 deletions(-) diff --git a/pkg/quick/quick.go b/pkg/quick/quick.go index ff170863e..70e9052d3 100644 --- a/pkg/quick/quick.go +++ b/pkg/quick/quick.go @@ -126,6 +126,35 @@ func (d config) Save(filename string) *probe.Error { return nil } +// Load - loads json config +func Load(filename string, data interface{}) (Config, *probe.Error) { + _, err := os.Stat(filename) + if err != nil { + return nil, probe.NewError(err) + } + + fileData, err := ioutil.ReadFile(filename) + if err != nil { + return nil, probe.NewError(err) + } + + if runtime.GOOS == "windows" { + fileData = []byte(strings.Replace(string(fileData), "\r\n", "\n", -1)) + } + + err = json.Unmarshal(fileData, &data) + if err != nil { + return nil, probe.NewError(err) + } + + config, perr := New(data) + if perr != nil { + return nil, perr.Trace() + } + + return config, nil +} + // Load - loads JSON config from file and merge with currently set values func (d *config) Load(filename string) *probe.Error { d.lock.Lock() @@ -145,6 +174,12 @@ func (d *config) Load(filename string) *probe.Error { fileData = []byte(strings.Replace(string(fileData), "\r\n", "\n", -1)) } + st := structs.New(d.data) + f, ok := st.FieldOk("Version") + if !ok { + return probe.NewError(fmt.Errorf("Argument struct [%s] does not contain field \"Version\".", st.Name())) + } + err = json.Unmarshal(fileData, d.data) if err != nil { return probe.NewError(err) @@ -154,12 +189,6 @@ func (d *config) Load(filename string) *probe.Error { return err.Trace() } - st := structs.New(d.data) - f, ok := st.FieldOk("Version") - if !ok { - return probe.NewError(fmt.Errorf("Argument struct [%s] does not contain field \"Version\".", st.Name())) - } - if (*d).Version() != f.Value() { return probe.NewError(fmt.Errorf("Version mismatch")) }