Adding 'Advanced JSON Customization' section in the README.md. Creating a runtime type (internal/data/runtime.go) to show how we can customize a JSON field.
All checks were successful
Deploy Greenlight API / deploy (push) Successful in 56s

This commit is contained in:
Maxime Delporte
2025-10-21 16:26:06 +02:00
parent e7944c3117
commit cc588a1dc0
2 changed files with 51 additions and 0 deletions

View File

@@ -82,6 +82,24 @@ Enveloping response data like this isn't strictly necessary, and whether you cho
2. It reduces the risk of errors on the client side, because it's harder to accidentally process one response thinking that it is something different. To get at the data, a client must explicitly reference it via the "movie" key.
3. If we always envelope the data returned by our API, then we mitigate a security vulnerability in older browsers which can arise if you return a JSON array as a response.
### Advanced JSON Customization
_When Go is encoding a particular type to JSON, it looks to see if the type has a **MarshalJSON()** method implemented on it. If it has, then Go will call this method to determine how to encode it._
Strictly speaking, when Go is encoding a particular type to JSON it looks to see if the type satisfies the json.Marshaler interface, which looks like this :
`type Marshaler interface {
MarshalJSON() ([]byte, error)
}`
If the type does satisfy the interface, then Go will call its **MarshalJSON()** method and use the []byte slice that it returns as the encoded JSON value.
If the type doesn't have a **MarshalJSON()** method, then Go will fall back to trying to encode it to JSON based on its own internal set of rules.
So, if we want to customize how something is encoded, all we need to do is implement a **MarshalJSON()** method on it which returns a _custom JSON representation of itself_ in a **[]byte** slice.
An example is available here : **internal/data/runtime.go**
### Performance
json.MarshalIndent() takes 65% longer to run and uses around 30% more memory than json.Marshal(), as well as making two more heap allocations. Those figures will change depending on what you're encoding, but they're fairly indicative of the performance impact.