Why this matters
Marshalling can fail for unsupported types or invalid data, leading to empty responses or panics if ignored.
Always check and handle errors from json.Marshal/json.Unmarshal (or Encoder/Decoder). Log context and return a safe, consistent error to callers.
Marshalling can fail for unsupported types or invalid data, leading to empty responses or panics if ignored.
Side-by-side examples engineers can pattern-match during review.
b, _ := json.Marshal(resp)
w.Write(b)b, err := json.Marshal(resp)
if err != nil {
logger.Error("marshal failed", "op", "writeResp", "err", err)
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
_, _ = w.Write(b)json.Marshal(x) // ignore errorb, err := json.Marshal(x); if err != nil { return err }From the same buckets as this rule.
Check if loops use equality operators (== or !=) in termination conditions. These can lead to infinite loops if the condition is never met exactly. Instead, use relational operators like < or > for safer loop termination.