Skip to content

Commit 41961ce

Browse files
committed
MarshalText for null.String
forgot to add this
1 parent aa8aa51 commit 41961ce

File tree

2 files changed

+18
-0
lines changed

2 files changed

+18
-0
lines changed

string.go

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -73,6 +73,15 @@ func (s String) MarshalJSON() ([]byte, error) {
7373
return json.Marshal(s.String)
7474
}
7575

76+
// MarshalText implements encoding.TextMarshaler.
77+
// It will encode a blank string when this String is null.
78+
func (s String) MarshalText() ([]byte, error) {
79+
if !s.Valid {
80+
return []byte{}, nil
81+
}
82+
return []byte(s.String), nil
83+
}
84+
7685
// UnmarshalText implements encoding.TextUnmarshaler.
7786
// It will unmarshal to a null String if the input is a blank string.
7887
func (s *String) UnmarshalText(text []byte) error {

string_test.go

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -93,17 +93,26 @@ func TestMarshalString(t *testing.T) {
9393
data, err := json.Marshal(str)
9494
maybePanic(err)
9595
assertJSONEquals(t, data, `"test"`, "non-empty json marshal")
96+
data, err = str.MarshalText()
97+
maybePanic(err)
98+
assertJSONEquals(t, data, "test", "non-empty text marshal")
9699

97100
// empty values should be encoded as an empty string
98101
zero := StringFrom("")
99102
data, err = json.Marshal(zero)
100103
maybePanic(err)
101104
assertJSONEquals(t, data, `""`, "empty json marshal")
105+
data, err = zero.MarshalText()
106+
maybePanic(err)
107+
assertJSONEquals(t, data, "", "string marshal text")
102108

103109
null := StringFromPtr(nil)
104110
data, err = json.Marshal(null)
105111
maybePanic(err)
106112
assertJSONEquals(t, data, `null`, "null json marshal")
113+
data, err = null.MarshalText()
114+
maybePanic(err)
115+
assertJSONEquals(t, data, "", "string marshal text")
107116
}
108117

109118
// Tests omitempty... broken until Go 1.4

0 commit comments

Comments
 (0)