mcfg: add ParamJSON and fix required params error message

This commit is contained in:
Brian Picciano 2018-08-09 18:05:04 -06:00
parent 362207b002
commit 196df2b739
2 changed files with 22 additions and 1 deletions

View File

@ -161,6 +161,14 @@ func (c *Cfg) populateParams(src Source) error {
Path []string `json:",omitempty"` Path []string `json:",omitempty"`
Name string 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{} pvM := map[string]ParamValue{}
for _, pv := range pvs { for _, pv := range pvs {
@ -193,7 +201,7 @@ func (c *Cfg) populateParams(src Source) error {
if err != nil { if err != nil {
return err return err
} else if _, ok := pvM[string(keyB)]; !ok { } 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))
} }
} }

View File

@ -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}) c.ParamAdd(Param{Name: name, Usage: usage, IsString: true, Into: &d})
return &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})
}