Skip to content

Commit

Permalink
invalid null.Time will MarshalText to an empty string
Browse files Browse the repository at this point in the history
this aligns with behavior of the other null types
previously it marshaled to the string "null"
fixes #47
  • Loading branch information
guregu committed Apr 25, 2020
1 parent 9d9d7a1 commit 5deded7
Show file tree
Hide file tree
Showing 3 changed files with 10 additions and 2 deletions.
4 changes: 3 additions & 1 deletion time.go
Original file line number Diff line number Diff line change
Expand Up @@ -110,15 +110,17 @@ func (t *Time) UnmarshalJSON(data []byte) error {
return err
}

// MarshalText returns an empty string if invalid, otherwise time.Time's MarshalText.
func (t Time) MarshalText() ([]byte, error) {
if !t.Valid {
return []byte("null"), nil
return []byte{}, nil
}
return t.Time.MarshalText()
}

func (t *Time) UnmarshalText(text []byte) error {
str := string(text)
// allowing "null" is for backwards compatibility with v3
if str == "" || str == "null" {
t.Valid = false
return nil
Expand Down
2 changes: 1 addition & 1 deletion time_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ func TestUnmarshalTimeText(t *testing.T) {
assertNullTime(t, null, "unmarshal null text")
txt, err = null.MarshalText()
maybePanic(err)
assertJSONEquals(t, txt, string(nullJSON), "marshal null text")
assertJSONEquals(t, txt, "", "marshal null text")

var invalid Time
err = invalid.UnmarshalText([]byte("hello world"))
Expand Down
6 changes: 6 additions & 0 deletions zero/time.go
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,8 @@ func (t *Time) UnmarshalJSON(data []byte) error {
}
}

// MarshalText implements encoding.TextMarshaler.
// It will encode to an empty time.Time if invalid.
func (t Time) MarshalText() ([]byte, error) {
ti := t.Time
if !t.Valid {
Expand All @@ -125,8 +127,12 @@ func (t Time) MarshalText() ([]byte, error) {
return ti.MarshalText()
}

// UnmarshalText implements encoding.TextUnmarshaler.
// It has compatibility with the null package in that it will accept empty strings as invalid values,
// which will be unmarshaled to a zero value.
func (t *Time) UnmarshalText(text []byte) error {
str := string(text)
// allowing "null" is for backwards compatibility with v3
if str == "" || str == "null" {
t.Valid = false
return nil
Expand Down

0 comments on commit 5deded7

Please sign in to comment.