When embedding a struct with a custom MarshalJSON method in Go, the promoted method causes any additional fields on the outer struct to be silently ignored during marshaling. The solution is to define a new MarshalJSON on the outer type that explicitly calls the embedded type's MarshalJSON, marshals only the new fields into a separate JSON object using a local type, then splices the two JSON byte slices together by replacing the opening brace of the second with a comma and appending it to the first (minus its closing brace). This avoids duplicating the embedded type's logic while correctly including all fields in the output.

5m read timeFrom boldlygo.tech
Post cover image
Table of contents
BackgroundThe problemWrapping the custom marshalerThe complete code
4 Impressions