options: Add namespace to Apply()

This commit is contained in:
Alexander Neumann 2017-03-25 17:20:03 +01:00
parent 2924ebc124
commit a8a7701f60
2 changed files with 14 additions and 6 deletions

View file

@ -69,7 +69,8 @@ func (o Options) Extract(ns string) Options {
} }
// Apply sets the options on dst via reflection, using the struct tag `option`. // Apply sets the options on dst via reflection, using the struct tag `option`.
func (o Options) Apply(dst interface{}) error { // The namespace argument (ns) is only used for error messages.
func (o Options) Apply(ns string, dst interface{}) error {
v := reflect.ValueOf(dst).Elem() v := reflect.ValueOf(dst).Elem()
fields := make(map[string]reflect.StructField) fields := make(map[string]reflect.StructField)
@ -92,6 +93,9 @@ func (o Options) Apply(dst interface{}) error {
for key, value := range o { for key, value := range o {
field, ok := fields[key] field, ok := fields[key]
if !ok { if !ok {
if ns != "" {
key = ns + "." + key
}
return errors.Fatalf("option %v is not known", key) return errors.Fatalf("option %v is not known", key)
} }

View file

@ -163,7 +163,7 @@ func TestOptionsApply(t *testing.T) {
for i, test := range setTests { for i, test := range setTests {
t.Run(fmt.Sprintf("test-%d", i), func(t *testing.T) { t.Run(fmt.Sprintf("test-%d", i), func(t *testing.T) {
var dst Target var dst Target
err := test.input.Apply(&dst) err := test.input.Apply("", &dst)
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
@ -176,25 +176,29 @@ func TestOptionsApply(t *testing.T) {
} }
var invalidSetTests = []struct { var invalidSetTests = []struct {
input Options input Options
err string namespace string
err string
}{ }{
{ {
Options{ Options{
"first_name": "foobar", "first_name": "foobar",
}, },
"option first_name is not known", "ns",
"option ns.first_name is not known",
}, },
{ {
Options{ Options{
"id": "foobar", "id": "foobar",
}, },
"ns",
`strconv.ParseInt: parsing "foobar": invalid syntax`, `strconv.ParseInt: parsing "foobar": invalid syntax`,
}, },
{ {
Options{ Options{
"timeout": "2134", "timeout": "2134",
}, },
"ns",
`time: missing unit in duration 2134`, `time: missing unit in duration 2134`,
}, },
} }
@ -203,7 +207,7 @@ func TestOptionsApplyInvalid(t *testing.T) {
for i, test := range invalidSetTests { for i, test := range invalidSetTests {
t.Run(fmt.Sprintf("test-%d", i), func(t *testing.T) { t.Run(fmt.Sprintf("test-%d", i), func(t *testing.T) {
var dst Target var dst Target
err := test.input.Apply(&dst) err := test.input.Apply(test.namespace, &dst)
if err == nil { if err == nil {
t.Fatalf("expected error %v not found", test.err) t.Fatalf("expected error %v not found", test.err)
} }