Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: support omitempty in custom json de/encoder #1441

Merged
merged 1 commit into from
May 8, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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":""}`},
Comment on lines +66 to +67
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice! I wonder if we should add some omitempty to test data .go files in a test as well to make sure it's working end-to-end?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Great idea! I'll do that now

}

tr := typeregistry.NewTypeRegistry()
Expand Down
Loading