From 196df2b7397b0bbdddf0464d9ad1da1d811b77ff Mon Sep 17 00:00:00 2001 From: Brian Picciano Date: Thu, 9 Aug 2018 18:05:04 -0600 Subject: [PATCH] mcfg: add ParamJSON and fix required params error message --- mcfg/mcfg.go | 10 +++++++++- mcfg/param.go | 13 +++++++++++++ 2 files changed, 22 insertions(+), 1 deletion(-) diff --git a/mcfg/mcfg.go b/mcfg/mcfg.go index f64266d..1e0ea64 100644 --- a/mcfg/mcfg.go +++ b/mcfg/mcfg.go @@ -161,6 +161,14 @@ func (c *Cfg) populateParams(src Source) error { Path []string `json:",omitempty"` Name string } + paramFullName := func(p param) string { + if len(p.Path) == 0 { + return p.Name + } + slice := append(make([]string, 0, len(p.Path)+1), p.Name) + slice = append(slice, p.Path...) + return strings.Join(slice, "-") + } pvM := map[string]ParamValue{} for _, pv := range pvs { @@ -193,7 +201,7 @@ func (c *Cfg) populateParams(src Source) error { if err != nil { return err } else if _, ok := pvM[string(keyB)]; !ok { - return fmt.Errorf("param %s is required but wasn't populated by any configuration source", keyB) + return fmt.Errorf("param %s is required but wasn't populated by any configuration source", paramFullName(reqP)) } } diff --git a/mcfg/param.go b/mcfg/param.go index 6ed357b..1290aed 100644 --- a/mcfg/param.go +++ b/mcfg/param.go @@ -113,3 +113,16 @@ func (c *Cfg) ParamDuration(name string, defaultVal mtime.Duration, usage string c.ParamAdd(Param{Name: name, Usage: usage, IsString: true, Into: &d}) return &d } + +// ParamJSON reads the parameter value as a JSON value and unmarshals it into +// the given interface{} (which should be a pointer). The receiver (into) is +// also used to determine the default value. +func (c *Cfg) ParamJSON(name string, into interface{}, usage string) { + c.ParamAdd(Param{Name: name, Usage: usage, Into: into}) +} + +// ParamRequiredJSON reads the parameter value as a JSON value and unmarshals it +// into the given interface{} (which should be a pointer). +func (c *Cfg) ParamRequiredJSON(name string, into interface{}, usage string) { + c.ParamAdd(Param{Name: name, Required: true, Usage: usage, Into: into}) +}