From 2a3e657a82ec13e13094a3987a6feab2174d143e Mon Sep 17 00:00:00 2001 From: Drew Bednar Date: Sun, 16 Mar 2025 10:52:50 -0400 Subject: [PATCH] Adding some additional json notes --- README.md | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/README.md b/README.md index cf7d3e5..82edb43 100644 --- a/README.md +++ b/README.md @@ -56,6 +56,20 @@ Uses [CleanURLs](https://en.wikipedia.org/wiki/Clean_URL) The pattern `err := json.NewEncoder(w).Encode(data)` looks elegant but creates issues when needing to coditionally set headers in response to an error. The performance difference between `json.Marshal` and `json.Encoder` are so small(tiny more mem and 1 extra alloc) that it's just cleaner to use `json.Marshal`. +### How Go Marshals JSON + +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. + + +Here is the interface +``` +type Marshaler interface { + MarshalJSON() ([]byte, error) +} +``` + +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. + ### Enveloping Respsonses