Skip to content

Commit 2e1fca7

Browse files
committed
marshal: descend through all interfaces/pointers when looking for time.Time
Previously, we would ignore an interface{} containing a *time.Time and treat it as a TextMarshaler. Fixes #82
1 parent 6b86383 commit 2e1fca7

File tree

2 files changed

+31
-1
lines changed

2 files changed

+31
-1
lines changed

marshal.go

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -91,6 +91,13 @@ func (p *Encoder) marshalTime(val reflect.Value) cfValue {
9191
return cfDate(time)
9292
}
9393

94+
func innermostValue(val reflect.Value) reflect.Value {
95+
for val.Kind() == reflect.Ptr || (val.Kind() == reflect.Interface && val.NumMethod() == 0) {
96+
val = val.Elem()
97+
}
98+
return val
99+
}
100+
94101
func (p *Encoder) marshal(val reflect.Value) cfValue {
95102
if !val.IsValid() {
96103
return nil
@@ -105,7 +112,7 @@ func (p *Encoder) marshal(val reflect.Value) cfValue {
105112
return p.marshalTime(val)
106113
}
107114
if val.Kind() == reflect.Ptr || (val.Kind() == reflect.Interface && val.NumMethod() == 0) {
108-
ival := val.Elem()
115+
ival := innermostValue(val)
109116
if ival.IsValid() && ival.Type() == timeType {
110117
return p.marshalTime(ival)
111118
}

marshal_test.go

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -103,3 +103,26 @@ func TestInterfaceFieldMarshal(t *testing.T) {
103103
t.Log("expect non-zero data")
104104
}
105105
}
106+
107+
func TestMarshalInterfaceFieldPtrTime(t *testing.T) {
108+
type X struct {
109+
C interface{} // C's type is unknown
110+
}
111+
112+
var sentinelTime = time.Date(2013, 11, 27, 0, 34, 0, 0, time.UTC)
113+
x := &X{
114+
C: &sentinelTime,
115+
}
116+
117+
e := &Encoder{}
118+
rval := reflect.ValueOf(x)
119+
cf := e.marshal(rval)
120+
121+
if dict, ok := cf.(*cfDictionary); ok {
122+
if _, ok := dict.values[0].(cfDate); !ok {
123+
t.Error("inner value is not a cfDate")
124+
}
125+
} else {
126+
t.Error("failed to marshal toplevel dictionary (?)")
127+
}
128+
}

0 commit comments

Comments
 (0)