From 4b05de632c4d0eae8ae5e904cbeebda05147b51b Mon Sep 17 00:00:00 2001 From: Juan Hernandez Date: Fri, 8 Oct 2021 16:38:47 +0200 Subject: [PATCH] Add support for digging inside maps This patch adds basic support for digging inside maps to the `data.Digger` type. Signed-off-by: Juan Hernandez --- data/digger.go | 11 +++++++++++ data/digger_test.go | 18 ++++++++++++++++++ 2 files changed, 29 insertions(+) diff --git a/data/digger.go b/data/digger.go index e3c0d9f9..bd7523a8 100644 --- a/data/digger.go +++ b/data/digger.go @@ -106,6 +106,8 @@ func (d *Digger) digFieldFromValue(value reflect.Value, field string) interface{ return d.digFieldFromPtr(value, field) case reflect.Struct: return d.digFieldFromStruct(value, field) + case reflect.Map: + return d.digFieldFromMap(value, field) default: return nil } @@ -173,6 +175,15 @@ func (d *Digger) digFieldFromMethod(value reflect.Value, method reflect.Method) return result.Interface() } +func (d *Digger) digFieldFromMap(value reflect.Value, name string) interface{} { + key := reflect.ValueOf(name) + result := value.MapIndex(key) + if !result.IsValid() { + return nil + } + return result.Interface() +} + // lookupMethod tries to find a public method of the given value that matches the given path // segment. For example, if the path segment is `my_field` it will look for a method named // `GetMyField` or `MyField`. Only methods that don't have input parameters will be considered. diff --git a/data/digger_test.go b/data/digger_test.go index 3cfb5956..9807d3f4 100644 --- a/data/digger_test.go +++ b/data/digger_test.go @@ -206,6 +206,24 @@ var _ = Describe("Digger", func() { "does_not_exist", nil, ), + Entry( + "Map field", + map[string]interface{}{ + "id": "123", + }, + "id", + "123", + ), + Entry( + "Nested map field", + map[string]interface{}{ + "object": map[string]interface{}{ + "id": "123", + }, + }, + "object.id", + "123", + ), ) })