Skip to content

Commit

Permalink
feat: support omitempty in custom json de/encoder (#1441)
Browse files Browse the repository at this point in the history
Fixes #1262
  • Loading branch information
deniseli authored May 8, 2024
1 parent 76ae43c commit 23b18fa
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 1 deletion.
17 changes: 16 additions & 1 deletion go-runtime/encoding/encoding.go
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,8 @@ func encodeValue(ctx context.Context, v reflect.Value, w *bytes.Buffer) error {
enc := v.Interface().(OptionMarshaler) //nolint:forcetypeassert
return enc.Marshal(ctx, w, encodeValue)

//TODO: Remove once we support `omitempty` tag
// TODO(Issue #1439): remove this special case by removing all usage of
// json.RawMessage, which is not a type we support.
case t == reflect.TypeFor[json.RawMessage]():
data, err := json.Marshal(v.Interface())
if err != nil {
Expand Down Expand Up @@ -137,6 +138,9 @@ func encodeStruct(ctx context.Context, v reflect.Value, w *bytes.Buffer) error {
// (t == reflect.TypeOf((*any)(nil)).Elem() && fv.IsZero()) {
// continue
// }
if isTaggedOmitempty(v, i) && fv.IsZero() {
continue
}
if afterFirst {
w.WriteRune(',')
}
Expand All @@ -150,6 +154,17 @@ func encodeStruct(ctx context.Context, v reflect.Value, w *bytes.Buffer) error {
return nil
}

func isTaggedOmitempty(v reflect.Value, i int) bool {
tag := v.Type().Field(i).Tag
tagVals := strings.Split(tag.Get("json"), ",")
for _, tagVal := range tagVals {
if strings.TrimSpace(tagVal) == "omitempty" {
return true
}
}
return false
}

func encodeBytes(v reflect.Value, w *bytes.Buffer) error {
data := base64.StdEncoding.EncodeToString(v.Bytes())
fmt.Fprintf(w, "%q", data)
Expand Down
7 changes: 7 additions & 0 deletions go-runtime/encoding/encoding_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,11 @@ func TestMarshal(t *testing.T) {
type inner struct {
FooBar string
}
type validateOmitempty struct {
ShouldOmit string `json:",omitempty"`
ShouldntOmit string `json:""`
NotTagged string
}
tests := []struct {
name string
input any
Expand All @@ -58,6 +63,8 @@ func TestMarshal(t *testing.T) {
{name: "Pointer", input: &struct{ String string }{"foo"}, err: `pointer types are not supported: *struct { String string }`},
{name: "SumType", input: struct{ D discriminator }{variant{"hello"}}, expected: `{"d":{"name":"Variant","value":{"message":"hello"}}}`},
{name: "UnregisteredSumType", input: struct{ D unregistered }{variant{"hello"}}, err: `the only supported interface types are enums or any, not encoding_test.unregistered`},
{name: "OmitEmptyNotNull", input: validateOmitempty{"foo", "bar", "baz"}, expected: `{"shouldOmit":"foo","shouldntOmit":"bar","notTagged":"baz"}`},
{name: "OmitEmptyNull", input: validateOmitempty{}, expected: `{"shouldntOmit":"","notTagged":""}`},
}

tr := typeregistry.NewTypeRegistry()
Expand Down

0 comments on commit 23b18fa

Please sign in to comment.