package main import ( "encoding/json" "log" "net/http" ) func respondWithError(w http.ResponseWriter, code int, msg string) { if code / 100 == 5 { log.Println("Responding with 5XX error:", msg) } type ErrorResponse struct { Error string `json:"error"` } respondWithJSON(w, code, ErrorResponse{ Error: msg }) } func respondWithJSON(w http.ResponseWriter, code int, payload interface{}) { dat, err := json.Marshal(payload) if err != nil { log.Printf("Failed to marshal JSON response: %v\n", payload) w.WriteHeader(500) return } w.Header().Add("Content-Type", "application/json"); w.WriteHeader(code); w.Write(dat) }