From 2311d04cabea8f0232a77b8bc5ed7a6403b336f6 Mon Sep 17 00:00:00 2001 From: Daryl Ng Date: Thu, 2 Apr 2020 16:10:18 +0800 Subject: [PATCH] Handle time.Time to unmarshal to TimeFormat --- flatten.go | 12 +++++++++++- flatten_test.go | 8 ++++++-- 2 files changed, 17 insertions(+), 3 deletions(-) diff --git a/flatten.go b/flatten.go index d3d6f4c..1cef66f 100644 --- a/flatten.go +++ b/flatten.go @@ -4,8 +4,13 @@ import ( "log" "reflect" "strings" + "time" ) +// TimeFormat defines default time format when unmarshalling time.Time +// Override this to unmarshal time.Time to a different format +var TimeFormat = time.RFC3339Nano + // Struct parses a struct `s` with JSON tags and flattens nested parameters // to only one level and passes the result to `m`. func Struct(s interface{}, m map[string]interface{}) { @@ -33,7 +38,12 @@ func flatten(key string, s interface{}, m map[string]interface{}) { switch reflect.ValueOf(val.Field(i).Interface()).Kind() { case reflect.Struct: - flatten(tag, val.Field(i).Interface(), m) + switch val.Field(i).Interface().(type) { + case time.Time: + m[tag] = val.Field(i).Interface().(time.Time).Format(TimeFormat) + default: + flatten(tag, val.Field(i).Interface(), m) + } default: if !reflect.DeepEqual(val.Field(i).Interface(), reflect.Zero(val.Field(i).Type()).Interface()) { m[tag] = val.Field(i).Interface() diff --git a/flatten_test.go b/flatten_test.go index 1a74c27..5a2d94c 100644 --- a/flatten_test.go +++ b/flatten_test.go @@ -2,6 +2,7 @@ package flatten_test import ( "testing" + "time" "github.com/darylnwk/flatten" "github.com/stretchr/testify/assert" @@ -16,6 +17,7 @@ type FooBar struct { Foo string `json:"foo"` Bar string `json:"bar"` NestedFooBar NestedFooBar `json:"nested"` + Time time.Time `json:"time"` } func TestFlatten(t *testing.T) { @@ -27,8 +29,9 @@ func TestFlatten(t *testing.T) { }, m) assert.Equal(t, map[string]interface{}{ - "foo": "foo", - "bar": "bar", + "foo": "foo", + "bar": "bar", + "time": "0001-01-01T00:00:00Z", }, m) } @@ -49,5 +52,6 @@ func TestFlatten_Nested(t *testing.T) { "bar": "bar", "nested.foo": "foo", "nested.bar": "bar", + "time": "0001-01-01T00:00:00Z", }, m) }