go 18 lines · 1 tab

WriteJSON helper with consistent headers and status

Leah Thompson Jan 2026
1 tab
package api

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

func WriteJSON(w http.ResponseWriter, status int, v any) {
  b, err := json.Marshal(v)
  if err != nil {
    http.Error(w, "server error", http.StatusInternalServerError)
    return
  }
  w.Header().Set("Content-Type", "application/json; charset=utf-8")
  w.Header().Set("Cache-Control", "no-store")
  w.WriteHeader(status)
  _, _ = w.Write(b)
}
1 file · go Explain with highlit

I like explicit response helpers because they prevent subtle inconsistencies: missing Content-Type, forgetting Cache-Control, or writing headers after the body has started. A WriteJSON function centralizes the “happy path” and makes error handling consistent too. The key is to set headers before WriteHeader, and to handle json.Marshal errors (which can happen if you accidentally include channels, funcs, or cyclic data). In production, I also add an option to pretty-print for non-prod environments, and I make sure errors are not leaking internal messages. This helper is intentionally small: it doesn’t try to be a framework, it just standardizes the output contract. When combined with a typed error-to-HTTP mapping, you get predictable responses that are easy to test with httptest and easy to consume from clients.


Related snips

Share this code

Here's the card — post it anywhere.

WriteJSON helper with consistent headers and status — share card
Link copied