From 04c15c531c67439cd79087d657a7fa32c59e7d8d Mon Sep 17 00:00:00 2001 From: a Date: Tue, 28 Nov 2023 04:24:37 -0600 Subject: [PATCH] struct to map as well --- utils.go | 22 ++++++++++++++++++---- utils_test.go | 12 ++++++++++++ 2 files changed, 30 insertions(+), 4 deletions(-) diff --git a/utils.go b/utils.go index f81763e..140ff0f 100644 --- a/utils.go +++ b/utils.go @@ -128,11 +128,25 @@ func structToMap(st any) (map[string]any, error) { for i := 0; i < rv.NumField(); i++ { fieldValue := rv.Field(i) fieldType := rt.Field(i) + + fieldTag := fieldType.Tag + tags, err := structtag.Parse(string(fieldTag)) + if err != nil { + // failing to parse a struct tag means = tag is invalid = we should panic + panic(err) + } + var fieldName string + gtrsTag, err := tags.Get("gtrs") + if err == nil { + fieldName = gtrsTag.Name + } else { + fieldName = toSnakeCase(fieldType.Name) + } switch v := fieldValue.Interface().(type) { case time.Time: - out[toSnakeCase(fieldType.Name)] = v.Format(time.RFC3339Nano) + out[fieldName] = v.Format(time.RFC3339Nano) case time.Duration: - out[toSnakeCase(fieldType.Name)] = v.String() + out[fieldName] = v.String() case Metadata: js, err := json.Marshal(v) if err != nil { @@ -142,9 +156,9 @@ func structToMap(st any) (map[string]any, error) { Err: err, } } - out[toSnakeCase(fieldType.Name)] = string(js) + out[fieldName] = string(js) default: - out[toSnakeCase(fieldType.Name)] = fieldValue.Interface() + out[fieldName] = fieldValue.Interface() } } return out, nil diff --git a/utils_test.go b/utils_test.go index 1a8800e..40e7339 100644 --- a/utils_test.go +++ b/utils_test.go @@ -53,6 +53,18 @@ func TestUtils_convertStructToMap_Simple(t *testing.T) { }, m1) } +func TestUtils_convertStructToMap_Tags(t *testing.T) { + p1 := TaggedPerson{Name: "Vlad", Age: 19, Height: 172.0} + m1, err := structToMap(p1) + assert.NoError(t, err) + + assert.Equal(t, map[string]any{ + "name": "Vlad", + "age": int(19), + "cm": float32(172), + }, m1) +} + func TestUtils_convertMapToStruct_Simple(t *testing.T) { m1 := map[string]any{ "name": "Vlad",