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: check whether structs within arrays/slices/maps implement a Marshaler interface #87

Merged
merged 3 commits into from
Apr 5, 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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
16 changes: 12 additions & 4 deletions musttag.go
Original file line number Diff line number Diff line change
Expand Up @@ -149,10 +149,6 @@ func (c *checker) checkType(typ types.Type, tag string) bool {
}
c.seenTypes[typ.String()] = struct{}{}

if implementsInterface(typ, c.ifaceWhitelist, c.imports) {
return true // the type implements a Marshaler interface; see issue #64.
}

styp, ok := c.parseStruct(typ)
if !ok {
return true // not a struct.
Expand All @@ -161,7 +157,19 @@ func (c *checker) checkType(typ types.Type, tag string) bool {
return c.checkStruct(styp, tag)
}

// recursively unwrap a type until we get to an underlying
// raw struct type that should have its fields checked
//
// SomeStruct -> struct{SomeStructField: ... }
// []*SomeStruct -> struct{SomeStructField: ... }
// ...
//
// exits early if it hits a type that implements a whitelisted interface
func (c *checker) parseStruct(typ types.Type) (*types.Struct, bool) {
if implementsInterface(typ, c.ifaceWhitelist, c.imports) {
return nil, false // the type implements a Marshaler interface; see issue #64.
}

switch typ := typ.(type) {
case *types.Pointer:
return c.parseStruct(typ.Elem())
Expand Down
11 changes: 11 additions & 0 deletions testdata/src/tests/tests.go
Original file line number Diff line number Diff line change
Expand Up @@ -164,3 +164,14 @@ func ignoredNestedType() {
json.Marshal(Foo{}) // no error
json.Marshal(&Foo{}) // no error
}

func interfaceSliceType() {
type WithMarshallableSlice struct {
List []Marshaler `json:"marshallable"`
}
var withMarshallableSlice WithMarshallableSlice

json.Marshal(withMarshallableSlice)
json.MarshalIndent(withMarshallableSlice, "", "")
json.NewEncoder(nil).Encode(withMarshallableSlice)
}