Skip to content

Commit

Permalink
MarshalText for null.String
Browse files Browse the repository at this point in the history
forgot to add this
  • Loading branch information
guregu committed Feb 28, 2016
1 parent aa8aa51 commit 41961ce
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 0 deletions.
9 changes: 9 additions & 0 deletions string.go
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,15 @@ func (s String) MarshalJSON() ([]byte, error) {
return json.Marshal(s.String)
}

// MarshalText implements encoding.TextMarshaler.
// It will encode a blank string when this String is null.
func (s String) MarshalText() ([]byte, error) {
if !s.Valid {
return []byte{}, nil
}
return []byte(s.String), nil
}

// UnmarshalText implements encoding.TextUnmarshaler.
// It will unmarshal to a null String if the input is a blank string.
func (s *String) UnmarshalText(text []byte) error {
Expand Down
9 changes: 9 additions & 0 deletions string_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -93,17 +93,26 @@ func TestMarshalString(t *testing.T) {
data, err := json.Marshal(str)
maybePanic(err)
assertJSONEquals(t, data, `"test"`, "non-empty json marshal")
data, err = str.MarshalText()
maybePanic(err)
assertJSONEquals(t, data, "test", "non-empty text marshal")

// empty values should be encoded as an empty string
zero := StringFrom("")
data, err = json.Marshal(zero)
maybePanic(err)
assertJSONEquals(t, data, `""`, "empty json marshal")
data, err = zero.MarshalText()
maybePanic(err)
assertJSONEquals(t, data, "", "string marshal text")

null := StringFromPtr(nil)
data, err = json.Marshal(null)
maybePanic(err)
assertJSONEquals(t, data, `null`, "null json marshal")
data, err = null.MarshalText()
maybePanic(err)
assertJSONEquals(t, data, "", "string marshal text")
}

// Tests omitempty... broken until Go 1.4
Expand Down

0 comments on commit 41961ce

Please sign in to comment.