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`.
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.