Serialize JSON responses and safe errors
Serialize JSON responses and safe errors
An API should define a stable response shape and use an appropriate HTTP status. Encode small JSON payloads before committing headers so encoding errors can still select a 500 status. Keep internal diagnostics out of client-facing error messages. Return from the handler immediately after sending an error.
package main
import ( "encoding/json" "errors" "fmt" "net/http" "net/http/httptest" "strings")
func probe(h http.Handler, method, path, body string) *httptest.ResponseRecorder { w := httptest.NewRecorder() h.ServeHTTP(w, httptest.NewRequest(method, path, strings.NewReader(body))) return w}func reply(w http.ResponseWriter, status int, v any) error { b, e := json.Marshal(v) if e != nil { status = 500 b = []byte(`{"error":"internal error"}`) } w.Header().Set("Content-Type", "application/json") w.WriteHeader(status) _, writeErr := w.Write(b) return errors.Join(e, writeErr)}func check(e error) { if e != nil { panic(e) }}func main() { h := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { check(reply(w, 200, map[string]string{"name": "Ada"})) }) w := probe(h, "GET", "/profile", "") fmt.Println(w.Code, w.Result().Header.Get("Content-Type"), w.Body.String())}Marshal prepares bytes first. The helper sets the JSON content type, commits the status, writes the bytes and returns any encoding or write error. check is a fixture assertion, not a production error policy. In production record sanitized errors; do not try to write a second status after a failed write. This helper is for small body-bearing responses, not 204, 304 or streaming responses.
Expected output:
200 application/json {"name":"Ada"}Use a safe fallback before committing
package main
import ( "encoding/json" "errors" "fmt" "math" "net/http" "net/http/httptest")
func reply(w http.ResponseWriter, status int, v any) error { b, e := json.Marshal(v) if e != nil { status = 500 b = []byte(`{"error":"internal error"}`) } w.Header().Set("Content-Type", "application/json") w.WriteHeader(status) _, writeErr := w.Write(b) return errors.Join(e, writeErr)}func main() { w := httptest.NewRecorder() e := reply(w, 200, math.Inf(1)) fmt.Println(w.Code, w.Body.String(), e != nil)}JSON cannot represent infinity. Marshal fails, the helper writes a generic 500 response, and the original error remains available to the caller. For expected client validation failures use a consistent 4xx envelope instead. Do not send raw database errors or stack traces to clients.
Expected output:
500 {"error":"internal error"} trueTry it locally
Use reply to write 404 with {"error":"not found"}; print status and body.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
HTTP servers 05: Serialize JSON responses and safe errors
Check the lesson objective before moving on.
Why marshal before writing a status?
What should a client receive for unexpected internal failures?