fix: ignore empty json strings for locale

This commit is contained in:
Tim Möhlmann 2024-11-11 12:16:55 +02:00
parent 759105530d
commit e59961cb2a
2 changed files with 37 additions and 9 deletions

View file

@ -82,6 +82,9 @@ func (l *Locale) MarshalJSON() ([]byte, error) {
// to an empty value (language "und") and no error will be returned. // to an empty value (language "und") and no error will be returned.
// This state can be checked with the `l.Tag().IsRoot()` method. // This state can be checked with the `l.Tag().IsRoot()` method.
func (l *Locale) UnmarshalJSON(data []byte) error { func (l *Locale) UnmarshalJSON(data []byte) error {
if len(data) == 0 || string(data) == "\"\"" {
return nil
}
err := json.Unmarshal(data, &l.tag) err := json.Unmarshal(data, &l.tag)
if err == nil { if err == nil {
return nil return nil

View file

@ -217,6 +217,30 @@ func TestLocale_UnmarshalJSON(t *testing.T) {
want dst want dst
wantErr bool wantErr bool
}{ }{
{
name: "value not present",
input: `{}`,
wantErr: false,
want: dst{
Locale: nil,
},
},
{
name: "null",
input: `{"locale": null}`,
wantErr: false,
want: dst{
Locale: nil,
},
},
{
name: "empty, ignored",
input: `{"locale": ""}`,
wantErr: false,
want: dst{
Locale: &Locale{},
},
},
{ {
name: "afrikaans, ok", name: "afrikaans, ok",
input: `{"locale": "af"}`, input: `{"locale": "af"}`,
@ -237,16 +261,17 @@ func TestLocale_UnmarshalJSON(t *testing.T) {
wantErr: true, wantErr: true,
}, },
} }
for _, tt := range tests { for _, tt := range tests {
var got dst t.Run(tt.name, func(t *testing.T) {
err := json.Unmarshal([]byte(tt.input), &got) var got dst
if tt.wantErr { err := json.Unmarshal([]byte(tt.input), &got)
require.Error(t, err) if tt.wantErr {
return require.Error(t, err)
} return
require.NoError(t, err) }
assert.Equal(t, tt.want, got) require.NoError(t, err)
assert.Equal(t, tt.want, got)
})
} }
} }