MarshalJSON is a Go method convention for customizing how a value becomes JSON. It is useful when ordinary struct-field encoding cannot enforce output requirements such as redaction or transformation. section 10.5.1
A MarshalJSON method returns a JSON byte slice and an error. Inside it, marshal an anonymous structure containing the intended output fields; this avoids recursively invoking MarshalJSON on the receiver. section 10.5.1
Redacting configuration output
For a Config value, copy the public fields into a temporary structure and replace Host before calling json.Marshal: func (c Config) MarshalJSON() ([]byte, error) { temp := &struct { Name string `json:"name"`; Version string `json:"version"`; Debug bool `json:"debug"`; Port int `json:"port"`; Host string `json:"host"` }{c.Name, c.Version, c.Debug, c.Port, "[REDACTED]"}; return json.Marshal(temp) }. This keeps sensitive data out of logs or external JSON. section 10.5.1
