Skip to content

Commit 7f62815

Browse files
authored
Fixes #141 (#142)
* Fixes #141 * Fixes #141 - additional fix for go 1.11
1 parent 0cfe0ec commit 7f62815

File tree

2 files changed

+53
-0
lines changed

2 files changed

+53
-0
lines changed

encoder.go

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,13 @@ func isZero(v reflect.Value) bool {
5757
}
5858
return z
5959
case reflect.Struct:
60+
type zero interface {
61+
IsZero() bool
62+
}
63+
if v.Type().Implements(reflect.TypeOf((*zero)(nil)).Elem()) {
64+
iz := v.MethodByName("IsZero").Call([]reflect.Value{})[0]
65+
return iz.Interface().(bool)
66+
}
6067
z := true
6168
for i := 0; i < v.NumField(); i++ {
6269
z = z && isZero(v.Field(i))

encoder_test.go

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import (
44
"fmt"
55
"reflect"
66
"testing"
7+
"time"
78
)
89

910
type E1 struct {
@@ -417,3 +418,48 @@ func TestRegisterEncoderCustomArrayType(t *testing.T) {
417418
encoder.Encode(s, vals)
418419
}
419420
}
421+
422+
func TestRegisterEncoderStructIsZero(t *testing.T) {
423+
type S1 struct {
424+
SomeTime1 time.Time `schema:"tim1,omitempty"`
425+
SomeTime2 time.Time `schema:"tim2,omitempty"`
426+
}
427+
428+
ss := []*S1{
429+
{
430+
SomeTime1: time.Date(2020, 8, 4, 13, 30, 1, 0, time.UTC),
431+
},
432+
}
433+
434+
for s := range ss {
435+
vals := map[string][]string{}
436+
437+
encoder := NewEncoder()
438+
encoder.RegisterEncoder(time.Time{}, func(value reflect.Value) string {
439+
return value.Interface().(time.Time).Format(time.RFC3339Nano)
440+
})
441+
442+
err := encoder.Encode(ss[s], vals)
443+
if err != nil {
444+
t.Errorf("Encoder has non-nil error: %v", err)
445+
}
446+
447+
ta, ok := vals["tim1"]
448+
if !ok {
449+
t.Error("expected tim1 to be present")
450+
}
451+
452+
if len(ta) != 1 {
453+
t.Error("expected tim1 to be present")
454+
}
455+
456+
if "2020-08-04T13:30:01Z" != ta[0] {
457+
t.Error("expected correct tim1 time")
458+
}
459+
460+
_, ok = vals["tim2"]
461+
if ok {
462+
t.Error("expected tim1 not to be present")
463+
}
464+
}
465+
}

0 commit comments

Comments
 (0)