go 22 lines · 1 tab

Consistent JSON responses (content-type + error envelopes)

Leah Thompson Jan 2026
1 tab
package api

import (
  "encoding/json"
  "net/http"
)

func WriteJSON(w http.ResponseWriter, status int, v any) {
  w.Header().Set("Content-Type", "application/json; charset=utf-8")
  w.WriteHeader(status)
  if err := json.NewEncoder(w).Encode(v); err != nil {
    http.Error(w, "internal server error", http.StatusInternalServerError)
  }
}

func WriteError(w http.ResponseWriter, status int, code string, details any) {
  payload := map[string]any{"error": code}
  if details != nil {
    payload["details"] = details
  }
  WriteJSON(w, status, payload)
}
1 file · go Explain with highlit

One of the easiest ways to reduce frontend complexity is to be consistent about API responses. I keep a small helper that always sets Content-Type: application/json; charset=utf-8, uses a stable error envelope (error + optional details), and returns correct status codes. The tricky part is not overengineering: you don’t need a framework to do this, just a couple of functions that every handler uses. I also make sure JSON encoding errors are handled safely (by writing a plain 500 rather than partial JSON). In production, this helps with observability too: logs and APM can key off a stable error code instead of parsing freeform messages. It’s small glue code, but it makes the whole API feel “designed,” not accidental.


Related snips

Share this code

Here's the card — post it anywhere.

Consistent JSON responses (content-type + error envelopes) — share card
Link copied