Skip to content

Commit

Permalink
Fix: Handle unset union map type (deepmap#650)
Browse files Browse the repository at this point in the history
Without this check, an uninitialised (zero-value) `t.union` will get
serialised as `null`, which then overrides the map's contents, leading
to a panic:

  panic: assignment to entry in nil map

By instead only unmarshalling this when we receive a non-nil version of
the `t.union`, we can handle zero-value'd structs.
  • Loading branch information
jamietanna committed Jul 25, 2022
1 parent d6a4776 commit 70fedbd
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 14 deletions.
32 changes: 20 additions & 12 deletions internal/test/components/components.gen.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

10 changes: 10 additions & 0 deletions internal/test/components/components_test.go
Expand Up @@ -202,3 +202,13 @@ func TestAnyOf(t *testing.T) {
assert.NoError(t, err)
assert.Equal(t, OneOfVariant5{Discriminator: "all", Id: 456}, v5)
}

func TestMarshalWhenNoUnionValueSet(t *testing.T) {
const expected = `{"one":null,"three":null,"two":null}`

var dst OneOfObject10

bytes, err := dst.MarshalJSON()
assert.Nil(t, err)
assert.Equal(t, expected, string(bytes))
}
6 changes: 4 additions & 2 deletions pkg/codegen/templates/union.tmpl
Expand Up @@ -65,9 +65,11 @@
return nil, err
}
object := make(map[string]json.RawMessage)
err = json.Unmarshal(b, &object)
if err != nil {
if t.union != nil {
err = json.Unmarshal(b, &object)
if err != nil {
return nil, err
}
}
{{range .Schema.Properties}}
object["{{.JsonFieldName}}"], err = json.Marshal(t.{{.GoFieldName}})
Expand Down

0 comments on commit 70fedbd

Please sign in to comment.