Skip to content

Commit

Permalink
Handle time.Time to unmarshal to TimeFormat
Browse files Browse the repository at this point in the history
  • Loading branch information
darylnwk committed Apr 2, 2020
1 parent 59bd3bc commit 2311d04
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 3 deletions.
12 changes: 11 additions & 1 deletion flatten.go
Original file line number Diff line number Diff line change
Expand Up @@ -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{}) {
Expand Down Expand Up @@ -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()
Expand Down
8 changes: 6 additions & 2 deletions flatten_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package flatten_test

import (
"testing"
"time"

"github.com/darylnwk/flatten"
"github.com/stretchr/testify/assert"
Expand All @@ -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) {
Expand All @@ -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)
}

Expand All @@ -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)
}

0 comments on commit 2311d04

Please sign in to comment.