Skip to content

Commit fd0f800

Browse files
autobotbenggBeng Lim
andauthored
Fix panic when printing a nil Date (#419)
* fix: fix panic when printing the nil Date Not sure why, but this is only happening when running with delve. It seems like printing a nil Stringer causes a panic when debugging with delve but is handled gracefully outside of delve. Steps to reproduce: 1. Start debugger 2. Print the value of a nil Date ```go var d *Date fmt.Sprintf("%v", d) ``` Theory: `time.Time` is embedded within the `Date` type. This means that if Date is nil and Stringer is used to get the string representation of it, it'll try to call Date.Time.String() which will result in a nil dereferencing error. * Regenerate code Co-authored-by: Beng Lim <beng.lim@outlook.com>
1 parent 7884c50 commit fd0f800

2 files changed

Lines changed: 26 additions & 0 deletions

File tree

date.go

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,3 +28,7 @@ func (d *Date) UnmarshalJSON(data []byte) error {
2828
d.Time = parsed
2929
return nil
3030
}
31+
32+
func (d Date) String() string {
33+
return d.Time.Format(DateFormat)
34+
}

date_test.go

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ package types
22

33
import (
44
"encoding/json"
5+
"fmt"
56
"testing"
67
"time"
78

@@ -30,3 +31,24 @@ func TestDate_UnmarshalJSON(t *testing.T) {
3031
assert.NoError(t, err)
3132
assert.Equal(t, testDate, b.DateField.Time)
3233
}
34+
35+
func TestDate_Stringer(t *testing.T) {
36+
t.Run("nil date", func(t *testing.T) {
37+
var d *Date
38+
assert.Equal(t, "<nil>", fmt.Sprintf("%v", d))
39+
})
40+
41+
t.Run("ptr date", func(t *testing.T) {
42+
d := &Date{
43+
Time: time.Date(2019, 4, 1, 0, 0, 0, 0, time.UTC),
44+
}
45+
assert.Equal(t, "2019-04-01", fmt.Sprintf("%v", d))
46+
})
47+
48+
t.Run("value date", func(t *testing.T) {
49+
d := Date{
50+
Time: time.Date(2019, 4, 1, 0, 0, 0, 0, time.UTC),
51+
}
52+
assert.Equal(t, "2019-04-01", fmt.Sprintf("%v", d))
53+
})
54+
}

0 commit comments

Comments
 (0)