Skip to content

Commit

Permalink
struct to map as well
Browse files Browse the repository at this point in the history
  • Loading branch information
elee1766 committed Nov 28, 2023
1 parent 6463181 commit 04c15c5
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 4 deletions.
22 changes: 18 additions & 4 deletions utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -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
Expand Down
12 changes: 12 additions & 0 deletions utils_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down

0 comments on commit 04c15c5

Please sign in to comment.